file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/* solium-disable function-order */ pragma solidity 0.5.17; import {IBondedECDSAKeepFactory} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeepFactory.sol"; import {VendingMachine} from "./VendingMachine.sol"; import {DepositFactory} from "../proxy/DepositFactory.sol"; import {IRelay} from "@summa-tx/relay-sol/contracts/Relay.sol"; import "../external/IMedianizer.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {ISatWeiPriceFeed} from "../interfaces/ISatWeiPriceFeed.sol"; import {DepositLog} from "../DepositLog.sol"; import {TBTCDepositToken} from "./TBTCDepositToken.sol"; import "./TBTCToken.sol"; import "./FeeRebateToken.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./KeepFactorySelection.sol"; /// @title TBTC System. /// @notice This contract acts as a central point for access control, /// value governance, and price feed. /// @dev Governable values should only affect new deposit creation. contract TBTCSystem is Ownable, ITBTCSystem, DepositLog { using SafeMath for uint256; using KeepFactorySelection for KeepFactorySelection.Storage; event EthBtcPriceFeedAdditionStarted(address _priceFeed, uint256 _timestamp); event LotSizesUpdateStarted(uint64[] _lotSizes, uint256 _timestamp); event SignerFeeDivisorUpdateStarted(uint16 _signerFeeDivisor, uint256 _timestamp); event CollateralizationThresholdsUpdateStarted( uint16 _initialCollateralizedPercent, uint16 _undercollateralizedThresholdPercent, uint16 _severelyUndercollateralizedThresholdPercent, uint256 _timestamp ); event KeepFactoriesUpdateStarted( address _keepStakedFactory, address _fullyBackedFactory, address _factorySelector, uint256 _timestamp ); event EthBtcPriceFeedAdded(address _priceFeed); event LotSizesUpdated(uint64[] _lotSizes); event AllowNewDepositsUpdated(bool _allowNewDeposits); event SignerFeeDivisorUpdated(uint16 _signerFeeDivisor); event CollateralizationThresholdsUpdated( uint16 _initialCollateralizedPercent, uint16 _undercollateralizedThresholdPercent, uint16 _severelyUndercollateralizedThresholdPercent ); event KeepFactoriesUpdated( address _keepStakedFactory, address _fullyBackedFactory, address _factorySelector ); uint256 initializedTimestamp = 0; uint256 pausedTimestamp; uint256 constant pausedDuration = 10 days; ISatWeiPriceFeed public priceFeed; IRelay public relay; KeepFactorySelection.Storage keepFactorySelection; uint16 public keepSize; uint16 public keepThreshold; // Parameters governed by the TBTCSystem owner bool private allowNewDeposits = false; uint16 private signerFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005 uint16 private initialCollateralizedPercent = 150; // percent uint16 private undercollateralizedThresholdPercent = 125; // percent uint16 private severelyUndercollateralizedThresholdPercent = 110; // percent uint64[] lotSizesSatoshis = [10**6, 10**7, 2 * 10**7, 5 * 10**7, 10**8]; // [0.01, 0.1, 0.2, 0.5, 1.0] BTC uint256 constant governanceTimeDelay = 48 hours; uint256 constant keepFactoriesUpgradeabilityPeriod = 180 days; uint256 private signerFeeDivisorChangeInitiated; uint256 private lotSizesChangeInitiated; uint256 private collateralizationThresholdsChangeInitiated; uint256 private keepFactoriesUpdateInitiated; uint16 private newSignerFeeDivisor; uint64[] newLotSizesSatoshis; uint16 private newInitialCollateralizedPercent; uint16 private newUndercollateralizedThresholdPercent; uint16 private newSeverelyUndercollateralizedThresholdPercent; address private newKeepStakedFactory; address private newFullyBackedFactory; address private newFactorySelector; // price feed uint256 constant priceFeedGovernanceTimeDelay = 90 days; uint256 ethBtcPriceFeedAdditionInitiated; IMedianizer nextEthBtcPriceFeed; constructor(address _priceFeed, address _relay) public { priceFeed = ISatWeiPriceFeed(_priceFeed); relay = IRelay(_relay); } /// @notice Initialize contracts /// @dev Only the Deposit factory should call this, and only once. /// @param _defaultKeepFactory ECDSA keep factory backed by KEEP stake. /// @param _depositFactory Deposit Factory. More info in `DepositFactory`. /// @param _masterDepositAddress Master Deposit address. More info in `Deposit`. /// @param _tbtcToken TBTCToken. More info in `TBTCToken`. /// @param _tbtcDepositToken TBTCDepositToken (TDT). More info in `TBTCDepositToken`. /// @param _feeRebateToken FeeRebateToken (FRT). More info in `FeeRebateToken`. /// @param _keepThreshold Signing group honesty threshold. /// @param _keepSize Signing group size. function initialize( IBondedECDSAKeepFactory _defaultKeepFactory, DepositFactory _depositFactory, address payable _masterDepositAddress, TBTCToken _tbtcToken, TBTCDepositToken _tbtcDepositToken, FeeRebateToken _feeRebateToken, VendingMachine _vendingMachine, uint16 _keepThreshold, uint16 _keepSize ) external onlyOwner { require(initializedTimestamp == 0, "already initialized"); keepFactorySelection.initialize(_defaultKeepFactory); keepThreshold = _keepThreshold; keepSize = _keepSize; initializedTimestamp = block.timestamp; allowNewDeposits = true; setTbtcDepositToken(_tbtcDepositToken); _vendingMachine.setExternalAddresses( _tbtcToken, _tbtcDepositToken, _feeRebateToken ); _depositFactory.setExternalDependencies( _masterDepositAddress, this, _tbtcToken, _tbtcDepositToken, _feeRebateToken, address(_vendingMachine) ); } /// @notice Returns whether new deposits should be allowed. /// @return True if new deposits should be allowed by the emergency pause button function getAllowNewDeposits() external view returns (bool) { return allowNewDeposits; } /// @notice Return the lowest lot size currently enabled for deposits. /// @return The lowest lot size, in satoshis. function getMinimumLotSize() public view returns (uint256) { return lotSizesSatoshis[0]; } /// @notice Return the largest lot size currently enabled for deposits. /// @return The largest lot size, in satoshis. function getMaximumLotSize() external view returns (uint256) { return lotSizesSatoshis[lotSizesSatoshis.length - 1]; } /// @notice One-time-use emergency function to disallow future deposit creation for 10 days. function emergencyPauseNewDeposits() external onlyOwner { require(pausedTimestamp == 0, "emergencyPauseNewDeposits can only be called once"); uint256 sinceInit = block.timestamp - initializedTimestamp; require(sinceInit < 180 days, "emergencyPauseNewDeposits can only be called within 180 days of initialization"); pausedTimestamp = block.timestamp; allowNewDeposits = false; emit AllowNewDepositsUpdated(false); } /// @notice Anyone can reactivate deposit creations after the pause duration is over. function resumeNewDeposits() external { require(! allowNewDeposits, "New deposits are currently allowed"); require(pausedTimestamp != 0, "Deposit has not been paused"); require(block.timestamp.sub(pausedTimestamp) >= pausedDuration, "Deposits are still paused"); allowNewDeposits = true; emit AllowNewDepositsUpdated(true); } function getRemainingPauseTerm() external view returns (uint256) { require(! allowNewDeposits, "New deposits are currently allowed"); return (block.timestamp.sub(pausedTimestamp) >= pausedDuration)? 0: pausedDuration.sub(block.timestamp.sub(pausedTimestamp)); } /// @notice Set the system signer fee divisor. /// @dev This can be finalized by calling `finalizeSignerFeeDivisorUpdate` /// Anytime after `governanceTimeDelay` has elapsed. /// @param _signerFeeDivisor The signer fee divisor. function beginSignerFeeDivisorUpdate(uint16 _signerFeeDivisor) external onlyOwner { require( _signerFeeDivisor > 9, "Signer fee divisor must be greater than 9, for a signer fee that is <= 10%" ); require( _signerFeeDivisor < 5000, "Signer fee divisor must be less than 5000, for a signer fee that is > 0.02%" ); newSignerFeeDivisor = _signerFeeDivisor; signerFeeDivisorChangeInitiated = block.timestamp; emit SignerFeeDivisorUpdateStarted(_signerFeeDivisor, block.timestamp); } /// @notice Set the allowed deposit lot sizes. /// @dev Lot size array should always contain 10**8 satoshis (1 BTC) and /// cannot contain values less than 50000 satoshis (0.0005 BTC) or /// greater than 10**10 satoshis (100 BTC). Lot size array must not /// have duplicates and it must be sorted. /// This can be finalized by calling `finalizeLotSizesUpdate` /// anytime after `governanceTimeDelay` has elapsed. /// @param _lotSizes Array of allowed lot sizes. function beginLotSizesUpdate(uint64[] calldata _lotSizes) external onlyOwner { bool hasSingleBitcoin = false; for (uint i = 0; i < _lotSizes.length; i++) { if (_lotSizes[i] == 10**8) { hasSingleBitcoin = true; } else if (_lotSizes[i] < 50 * 10**3) { // Failed the minimum requirement, break on out. revert("Lot sizes less than 0.0005 BTC are not allowed"); } else if (_lotSizes[i] > 10 * 10**9) { // Failed the maximum requirement, break on out. revert("Lot sizes greater than 100 BTC are not allowed"); } else if (i > 0 && _lotSizes[i] == _lotSizes[i-1]) { revert("Lot size array must not have duplicates"); } else if (i > 0 && _lotSizes[i] < _lotSizes[i-1]) { revert("Lot size array must be sorted"); } } require(hasSingleBitcoin, "Lot size array must always contain 1 BTC"); emit LotSizesUpdateStarted(_lotSizes, block.timestamp); newLotSizesSatoshis = _lotSizes; lotSizesChangeInitiated = block.timestamp; } /// @notice Set the system collateralization levels /// @dev This can be finalized by calling `finalizeCollateralizationThresholdsUpdate` /// Anytime after `governanceTimeDelay` has elapsed. /// @param _initialCollateralizedPercent default signing bond percent for new deposits /// @param _undercollateralizedThresholdPercent first undercollateralization trigger /// @param _severelyUndercollateralizedThresholdPercent second undercollateralization trigger function beginCollateralizationThresholdsUpdate( uint16 _initialCollateralizedPercent, uint16 _undercollateralizedThresholdPercent, uint16 _severelyUndercollateralizedThresholdPercent ) external onlyOwner { require( _initialCollateralizedPercent <= 300, "Initial collateralized percent must be <= 300%" ); require( _initialCollateralizedPercent > 100, "Initial collateralized percent must be >= 100%" ); require( _initialCollateralizedPercent > _undercollateralizedThresholdPercent, "Undercollateralized threshold must be < initial collateralized percent" ); require( _undercollateralizedThresholdPercent > _severelyUndercollateralizedThresholdPercent, "Severe undercollateralized threshold must be < undercollateralized threshold" ); newInitialCollateralizedPercent = _initialCollateralizedPercent; newUndercollateralizedThresholdPercent = _undercollateralizedThresholdPercent; newSeverelyUndercollateralizedThresholdPercent = _severelyUndercollateralizedThresholdPercent; collateralizationThresholdsChangeInitiated = block.timestamp; emit CollateralizationThresholdsUpdateStarted( _initialCollateralizedPercent, _undercollateralizedThresholdPercent, _severelyUndercollateralizedThresholdPercent, block.timestamp ); } /// @notice Sets the addresses of the KEEP-staked ECDSA keep factory, /// ETH-only-backed ECDSA keep factory and the selection strategy /// that will choose between the two factories for new deposits. /// When the ETH-only-backed factory and strategy are not set TBTCSystem /// will use KEEP-staked factory. When both factories and strategy /// are set, TBTCSystem load balances between two factories based on /// the selection strategy. /// @dev It can be finalized by calling `finalizeKeepFactoriesUpdate` /// any time after `governanceTimeDelay` has elapsed. This can be /// called more than once until finalized to reset the values and /// timer. An update can only be initialized before /// `keepFactoriesUpgradeabilityPeriod` elapses after system initialization; /// after that, no further updates can be initialized, though any pending /// update can be finalized. All calls must set all three properties to /// their desired value; leaving a value as 0, even if it was previously /// set, will update that value to be 0. ETH-bond-only factory or the /// strategy are allowed to be set as zero addresses. /// @param _keepStakedFactory Address of the KEEP staked based factory. /// @param _fullyBackedFactory Address of the ETH-bond-only-based factory. /// @param _factorySelector Address of the keep factory selection strategy. function beginKeepFactoriesUpdate( address _keepStakedFactory, address _fullyBackedFactory, address _factorySelector ) external onlyOwner { uint256 sinceInit = block.timestamp - initializedTimestamp; require( sinceInit < keepFactoriesUpgradeabilityPeriod, "beginKeepFactoriesUpdate can only be called within 180 days of initialization" ); // It is required that KEEP staked factory address is configured as this is // a default choice factory. Fully backed factory and factory selector // are optional for the system to work, hence they don't have to be provided. require( _keepStakedFactory != address(0), "KEEP staked factory must be a nonzero address" ); newKeepStakedFactory = _keepStakedFactory; newFullyBackedFactory = _fullyBackedFactory; newFactorySelector = _factorySelector; keepFactoriesUpdateInitiated = block.timestamp; emit KeepFactoriesUpdateStarted( _keepStakedFactory, _fullyBackedFactory, _factorySelector, block.timestamp ); } /// @notice Add a new ETH/BTC price feed contract to the priecFeed. /// @dev This can be finalized by calling `finalizeEthBtcPriceFeedAddition` /// anytime after `priceFeedGovernanceTimeDelay` has elapsed. function beginEthBtcPriceFeedAddition(IMedianizer _ethBtcPriceFeed) external onlyOwner { bool ethBtcActive; (, ethBtcActive) = _ethBtcPriceFeed.peek(); require(ethBtcActive, "Cannot add inactive feed"); nextEthBtcPriceFeed = _ethBtcPriceFeed; ethBtcPriceFeedAdditionInitiated = block.timestamp; emit EthBtcPriceFeedAdditionStarted(address(_ethBtcPriceFeed), block.timestamp); } modifier onlyAfterGovernanceDelay( uint256 _changeInitializedTimestamp, uint256 _delay ) { require(_changeInitializedTimestamp > 0, "Change not initiated"); require( block.timestamp.sub(_changeInitializedTimestamp) >= _delay, "Governance delay has not elapsed" ); _; } /// @notice Finish setting the system signer fee divisor. /// @dev `beginSignerFeeDivisorUpdate` must be called first, once `governanceTimeDelay` /// has passed, this function can be called to set the signer fee divisor to the /// value set in `beginSignerFeeDivisorUpdate` function finalizeSignerFeeDivisorUpdate() external onlyOwner onlyAfterGovernanceDelay(signerFeeDivisorChangeInitiated, governanceTimeDelay) { signerFeeDivisor = newSignerFeeDivisor; emit SignerFeeDivisorUpdated(newSignerFeeDivisor); newSignerFeeDivisor = 0; signerFeeDivisorChangeInitiated = 0; } /// @notice Finish setting the accepted system lot sizes. /// @dev `beginLotSizesUpdate` must be called first, once `governanceTimeDelay` /// has passed, this function can be called to set the lot sizes to the /// value set in `beginLotSizesUpdate` function finalizeLotSizesUpdate() external onlyOwner onlyAfterGovernanceDelay(lotSizesChangeInitiated, governanceTimeDelay) { lotSizesSatoshis = newLotSizesSatoshis; emit LotSizesUpdated(newLotSizesSatoshis); lotSizesChangeInitiated = 0; newLotSizesSatoshis.length = 0; refreshMinimumBondableValue(); } /// @notice Finish setting the system collateralization levels /// @dev `beginCollateralizationThresholdsUpdate` must be called first, once `governanceTimeDelay` /// has passed, this function can be called to set the collateralization thresholds to the /// value set in `beginCollateralizationThresholdsUpdate` function finalizeCollateralizationThresholdsUpdate() external onlyOwner onlyAfterGovernanceDelay( collateralizationThresholdsChangeInitiated, governanceTimeDelay ) { initialCollateralizedPercent = newInitialCollateralizedPercent; undercollateralizedThresholdPercent = newUndercollateralizedThresholdPercent; severelyUndercollateralizedThresholdPercent = newSeverelyUndercollateralizedThresholdPercent; emit CollateralizationThresholdsUpdated( newInitialCollateralizedPercent, newUndercollateralizedThresholdPercent, newSeverelyUndercollateralizedThresholdPercent ); newInitialCollateralizedPercent = 0; newUndercollateralizedThresholdPercent = 0; newSeverelyUndercollateralizedThresholdPercent = 0; collateralizationThresholdsChangeInitiated = 0; } /// @notice Finish setting addresses of the KEEP-staked ECDSA keep factory, /// ETH-only-backed ECDSA keep factory, and the selection strategy /// that will choose between the two factories for new deposits. /// @dev `beginKeepFactoriesUpdate` must be called first; once /// `governanceTimeDelay` has passed, this function can be called to /// set factories addresses to the values set in `beginKeepFactoriesUpdate`. function finalizeKeepFactoriesUpdate() external onlyOwner onlyAfterGovernanceDelay( keepFactoriesUpdateInitiated, governanceTimeDelay ) { keepFactorySelection.setFactories( newKeepStakedFactory, newFullyBackedFactory, newFactorySelector ); emit KeepFactoriesUpdated( newKeepStakedFactory, newFullyBackedFactory, newFactorySelector ); keepFactoriesUpdateInitiated = 0; newKeepStakedFactory = address(0); newFullyBackedFactory = address(0); newFactorySelector = address(0); } /// @notice Finish adding a new price feed contract to the priceFeed. /// @dev `beginEthBtcPriceFeedAddition` must be called first; once /// `ethBtcPriceFeedAdditionInitiated` has passed, this function can be /// called to append a new price feed. function finalizeEthBtcPriceFeedAddition() external onlyOwner onlyAfterGovernanceDelay( ethBtcPriceFeedAdditionInitiated, priceFeedGovernanceTimeDelay ) { // This process interacts with external contracts, so // Checks-Effects-Interactions it. IMedianizer _nextEthBtcPriceFeed = nextEthBtcPriceFeed; nextEthBtcPriceFeed = IMedianizer(0); ethBtcPriceFeedAdditionInitiated = 0; emit EthBtcPriceFeedAdded(address(_nextEthBtcPriceFeed)); priceFeed.addEthBtcFeed(_nextEthBtcPriceFeed); } /// @notice Gets the system signer fee divisor. /// @return The signer fee divisor. function getSignerFeeDivisor() external view returns (uint16) { return signerFeeDivisor; } /// @notice Gets the allowed lot sizes /// @return Uint64 array of allowed lot sizes function getAllowedLotSizes() external view returns (uint64[] memory){ return lotSizesSatoshis; } /// @notice Get the system undercollateralization level for new deposits function getUndercollateralizedThresholdPercent() external view returns (uint16) { return undercollateralizedThresholdPercent; } /// @notice Get the system severe undercollateralization level for new deposits function getSeverelyUndercollateralizedThresholdPercent() external view returns (uint16) { return severelyUndercollateralizedThresholdPercent; } /// @notice Get the system initial collateralized level for new deposits. function getInitialCollateralizedPercent() external view returns (uint16) { return initialCollateralizedPercent; } /// @notice Get the price of one satoshi in wei. /// @dev Reverts if the price of one satoshi is 0 wei, or if the price of /// one satoshi is 1 ether. Can only be called by a deposit with minted /// TDT. /// @return The price of one satoshi in wei. function fetchBitcoinPrice() external view returns (uint256) { require( tbtcDepositToken.exists(uint256(msg.sender)), "Caller must be a Deposit contract" ); return _fetchBitcoinPrice(); } // Difficulty Oracle function fetchRelayCurrentDifficulty() external view returns (uint256) { return relay.getCurrentEpochDifficulty(); } function fetchRelayPreviousDifficulty() external view returns (uint256) { return relay.getPrevEpochDifficulty(); } /// @notice Get the time remaining until the signer fee divisor can be updated. function getRemainingSignerFeeDivisorUpdateTime() external view returns (uint256) { return getRemainingChangeTime( signerFeeDivisorChangeInitiated, governanceTimeDelay ); } /// @notice Get the time remaining until the lot sizes can be updated. function getRemainingLotSizesUpdateTime() external view returns (uint256) { return getRemainingChangeTime( lotSizesChangeInitiated, governanceTimeDelay ); } /// @notice Get the time remaining until the collateralization thresholds can be updated. function getRemainingCollateralizationThresholdsUpdateTime() external view returns (uint256) { return getRemainingChangeTime( collateralizationThresholdsChangeInitiated, governanceTimeDelay ); } /// @notice Get the time remaining until the Keep ETH-only-backed ECDSA keep /// factory and the selection strategy that will choose between it /// and the KEEP-backed factory can be updated. function getRemainingKeepFactoriesUpdateTime() external view returns (uint256) { return getRemainingChangeTime( keepFactoriesUpdateInitiated, governanceTimeDelay ); } /// @notice Get the time remaining until the signer fee divisor can be updated. function getRemainingEthBtcPriceFeedAdditionTime() external view returns (uint256) { return getRemainingChangeTime( ethBtcPriceFeedAdditionInitiated, priceFeedGovernanceTimeDelay ); } /// @notice Get the time remaining until Keep factories can no longer be updated. function getRemainingKeepFactoriesUpgradeabilityTime() external view returns (uint256) { return getRemainingChangeTime( initializedTimestamp, keepFactoriesUpgradeabilityPeriod ); } /// @notice Refreshes the minimum bondable value required from the operator /// to join the sortition pool for tBTC. The minimum bondable value is /// equal to the current minimum lot size collateralized 150% multiplied by /// the current BTC price. /// @dev It is recommended to call this function on tBTC initialization and /// after minimum lot size update. function refreshMinimumBondableValue() public { keepFactorySelection.setMinimumBondableValue( calculateBondRequirementWei(getMinimumLotSize()), keepSize, keepThreshold ); } /// @notice Returns the time delay used for governance actions except for /// price feed additions. function getGovernanceTimeDelay() external pure returns (uint256) { return governanceTimeDelay; } /// @notice Returns the time period when keep factories upgrades are allowed. function getKeepFactoriesUpgradeabilityPeriod() public pure returns (uint256) { return keepFactoriesUpgradeabilityPeriod; } /// @notice Returns the time delay used for price feed addition governance /// actions. function getPriceFeedGovernanceTimeDelay() external pure returns (uint256) { return priceFeedGovernanceTimeDelay; } /// @notice Gets a fee estimate for creating a new Deposit. /// @return Uint256 estimate. function getNewDepositFeeEstimate() external view returns (uint256) { IBondedECDSAKeepFactory _keepFactory = keepFactorySelection.selectFactory(); return _keepFactory.openKeepFeeEstimate(); } /// @notice Request a new keep opening. /// @param _requestedLotSizeSatoshis Lot size in satoshis. /// @param _maxSecuredLifetime Duration of stake lock in seconds. /// @return Address of a new keep. function requestNewKeep( uint64 _requestedLotSizeSatoshis, uint256 _maxSecuredLifetime ) external payable returns (address) { require(tbtcDepositToken.exists(uint256(msg.sender)), "Caller must be a Deposit contract"); require(isAllowedLotSize(_requestedLotSizeSatoshis), "provided lot size not supported"); IBondedECDSAKeepFactory _keepFactory = keepFactorySelection.selectFactoryAndRefresh(); uint256 bond = calculateBondRequirementWei(_requestedLotSizeSatoshis); return _keepFactory.openKeep.value(msg.value)(keepSize, keepThreshold, msg.sender, bond, _maxSecuredLifetime); } /// @notice Check if a lot size is allowed. /// @param _requestedLotSizeSatoshis Lot size to check. /// @return True if lot size is allowed, false otherwise. function isAllowedLotSize(uint64 _requestedLotSizeSatoshis) public view returns (bool){ for( uint i = 0; i < lotSizesSatoshis.length; i++){ if (lotSizesSatoshis[i] == _requestedLotSizeSatoshis){ return true; } } return false; } /// @notice Calculates bond requirement in wei for the given lot size in /// satoshis based on the current ETHBTC price. /// @param _requestedLotSizeSatoshis Lot size in satoshis. /// @return Bond requirement in wei. function calculateBondRequirementWei( uint256 _requestedLotSizeSatoshis ) internal view returns (uint256) { uint256 lotSizeInWei = _fetchBitcoinPrice().mul(_requestedLotSizeSatoshis); return lotSizeInWei.mul(initialCollateralizedPercent).div(100); } function _fetchBitcoinPrice() internal view returns (uint256) { uint256 price = priceFeed.getPrice(); if (price == 0 || price > 10 ** 18) { // This is if a sat is worth 0 wei, or is worth >1 ether. Revert at // once. revert("System returned a bad price"); } return price; } /// @notice Get the time remaining until the function parameter timer value can be updated. function getRemainingChangeTime( uint256 _changeTimestamp, uint256 _delayAmount ) internal view returns (uint256){ require(_changeTimestamp > 0, "Update not initiated"); uint256 elapsed = block.timestamp.sub(_changeTimestamp); if (elapsed >= _delayAmount) { return 0; } else { return _delayAmount.sub(elapsed); } } }
Finish setting the accepted system lot sizes. `beginLotSizesUpdate` must be called first, once `governanceTimeDelay` has passed, this function can be called to set the lot sizes to the value set in `beginLotSizesUpdate`
function finalizeLotSizesUpdate() external onlyOwner onlyAfterGovernanceDelay(lotSizesChangeInitiated, governanceTimeDelay) { lotSizesSatoshis = newLotSizesSatoshis; emit LotSizesUpdated(newLotSizesSatoshis); lotSizesChangeInitiated = 0; newLotSizesSatoshis.length = 0; refreshMinimumBondableValue(); }
1,057,838
./full_match/3/0x336e7f473522FE446459FcBfB288DB01f4f2d24D/sources/localhost/FlashSwapGun.sol
emit UniswapV2CallInit(sender, amount0, amount1, wethAddress, pairBAddress);
function testCall6() public view returns (uint) { return uint(3); }
8,205,479
/** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../interface/RocketStorageInterface.sol"; /// @title Base settings / modifiers for each contract in Rocket Pool /// @author David Rugendyke abstract contract RocketBase { // Calculate using this as the base uint256 constant calcBase = 1 ether; // Version of the contract uint8 public version; // The main storage contract where primary persistant storage is maintained RocketStorageInterface rocketStorage = RocketStorageInterface(0); /*** Modifiers **********************************************************/ /** * @dev Throws if called by any sender that doesn't match a Rocket Pool network contract */ modifier onlyLatestNetworkContract() { require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract"); _; } /** * @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract */ modifier onlyLatestContract(string memory _contractName, address _contractAddress) { require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract"); _; } /** * @dev Throws if called by any sender that isn't a registered node */ modifier onlyRegisteredNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress))), "Invalid node"); _; } /** * @dev Throws if called by any sender that isn't a trusted node DAO member */ modifier onlyTrustedNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("dao.trustednodes.", "member", _nodeAddress))), "Invalid trusted node"); _; } /** * @dev Throws if called by any sender that isn't a registered minipool */ modifier onlyRegisteredMinipool(address _minipoolAddress) { require(getBool(keccak256(abi.encodePacked("minipool.exists", _minipoolAddress))), "Invalid minipool"); _; } /** * @dev Throws if called by any account other than a guardian account (temporary account allowed access to settings before DAO is fully enabled) */ modifier onlyGuardian() { require(msg.sender == rocketStorage.getGuardian(), "Account is not a temporary guardian"); _; } /*** Methods **********************************************************/ /// @dev Set the main Rocket Storage address constructor(RocketStorageInterface _rocketStorageAddress) { // Update the contract address rocketStorage = RocketStorageInterface(_rocketStorageAddress); } /// @dev Get the address of a network contract by name function getContractAddress(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Check it require(contractAddress != address(0x0), "Contract not found"); // Return return contractAddress; } /// @dev Get the address of a network contract by name (returns address(0x0) instead of reverting if contract does not exist) function getContractAddressUnsafe(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Return return contractAddress; } /// @dev Get the name of a network contract by address function getContractName(address _contractAddress) internal view returns (string memory) { // Get the contract name string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress))); // Check it require(bytes(contractName).length > 0, "Contract not found"); // Return return contractName; } /// @dev Get revert error message from a .call method function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /*** Rocket Storage Methods ****************************************/ // Note: Unused helpers have been removed to keep contract sizes down /// @dev Storage get methods function getAddress(bytes32 _key) internal view returns (address) { return rocketStorage.getAddress(_key); } function getUint(bytes32 _key) internal view returns (uint) { return rocketStorage.getUint(_key); } function getString(bytes32 _key) internal view returns (string memory) { return rocketStorage.getString(_key); } function getBytes(bytes32 _key) internal view returns (bytes memory) { return rocketStorage.getBytes(_key); } function getBool(bytes32 _key) internal view returns (bool) { return rocketStorage.getBool(_key); } function getInt(bytes32 _key) internal view returns (int) { return rocketStorage.getInt(_key); } function getBytes32(bytes32 _key) internal view returns (bytes32) { return rocketStorage.getBytes32(_key); } /// @dev Storage set methods function setAddress(bytes32 _key, address _value) internal { rocketStorage.setAddress(_key, _value); } function setUint(bytes32 _key, uint _value) internal { rocketStorage.setUint(_key, _value); } function setString(bytes32 _key, string memory _value) internal { rocketStorage.setString(_key, _value); } function setBytes(bytes32 _key, bytes memory _value) internal { rocketStorage.setBytes(_key, _value); } function setBool(bytes32 _key, bool _value) internal { rocketStorage.setBool(_key, _value); } function setInt(bytes32 _key, int _value) internal { rocketStorage.setInt(_key, _value); } function setBytes32(bytes32 _key, bytes32 _value) internal { rocketStorage.setBytes32(_key, _value); } /// @dev Storage delete methods function deleteAddress(bytes32 _key) internal { rocketStorage.deleteAddress(_key); } function deleteUint(bytes32 _key) internal { rocketStorage.deleteUint(_key); } function deleteString(bytes32 _key) internal { rocketStorage.deleteString(_key); } function deleteBytes(bytes32 _key) internal { rocketStorage.deleteBytes(_key); } function deleteBool(bytes32 _key) internal { rocketStorage.deleteBool(_key); } function deleteInt(bytes32 _key) internal { rocketStorage.deleteInt(_key); } function deleteBytes32(bytes32 _key) internal { rocketStorage.deleteBytes32(_key); } /// @dev Storage arithmetic methods function addUint(bytes32 _key, uint256 _amount) internal { rocketStorage.addUint(_key, _amount); } function subUint(bytes32 _key, uint256 _amount) internal { rocketStorage.subUint(_key, _amount); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../../../RocketBase.sol"; import "../../../../interface/dao/protocol/settings/RocketDAOProtocolSettingsInterface.sol"; // Settings in RP which the DAO will have full control over // This settings contract enables storage using setting paths with namespaces, rather than explicit set methods abstract contract RocketDAOProtocolSettings is RocketBase, RocketDAOProtocolSettingsInterface { // The namespace for a particular group of settings bytes32 settingNameSpace; // Only allow updating from the DAO proposals contract modifier onlyDAOProtocolProposal() { // If this contract has been initialised, only allow access from the proposals contract if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress("rocketDAOProtocolProposals") == msg.sender, "Only DAO Protocol Proposals contract can update a setting"); _; } // Construct constructor(RocketStorageInterface _rocketStorageAddress, string memory _settingNameSpace) RocketBase(_rocketStorageAddress) { // Apply the setting namespace settingNameSpace = keccak256(abi.encodePacked("dao.protocol.setting.", _settingNameSpace)); } /*** Uints ****************/ // A general method to return any setting given the setting path is correct, only accepts uints function getSettingUint(string memory _settingPath) public view override returns (uint256) { return getUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath))); } // Update a Uint setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed function setSettingUint(string memory _settingPath, uint256 _value) virtual public override onlyDAOProtocolProposal { // Update setting now setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value); } /*** Bools ****************/ // A general method to return any setting given the setting path is correct, only accepts bools function getSettingBool(string memory _settingPath) public view override returns (bool) { return getBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath))); } // Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed function setSettingBool(string memory _settingPath, bool _value) virtual public override onlyDAOProtocolProposal { // Update setting now setBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value); } /*** Addresses ****************/ // A general method to return any setting given the setting path is correct, only accepts addresses function getSettingAddress(string memory _settingPath) external view override returns (address) { return getAddress(keccak256(abi.encodePacked(settingNameSpace, _settingPath))); } // Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed function setSettingAddress(string memory _settingPath, address _value) virtual external override onlyDAOProtocolProposal { // Update setting now setAddress(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "./RocketDAOProtocolSettings.sol"; import "../../../../interface/dao/protocol/settings/RocketDAOProtocolSettingsAuctionInterface.sol"; // Network auction settings contract RocketDAOProtocolSettingsAuction is RocketDAOProtocolSettings, RocketDAOProtocolSettingsAuctionInterface { // Construct constructor(RocketStorageInterface _rocketStorageAddress) RocketDAOProtocolSettings(_rocketStorageAddress, "auction") { // Set version version = 1; // Initialize settings on deployment if(!getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) { // Apply settings setSettingBool("auction.lot.create.enabled", true); setSettingBool("auction.lot.bidding.enabled", true); setSettingUint("auction.lot.value.minimum", 1 ether); setSettingUint("auction.lot.value.maximum", 10 ether); setSettingUint("auction.lot.duration", 40320); // 7 days setSettingUint("auction.price.start", 1 ether); // 100% setSettingUint("auction.price.reserve", 0.5 ether); // 50% // Settings initialised setBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")), true); } } // Lot creation currently enabled function getCreateLotEnabled() override external view returns (bool) { return getSettingBool("auction.lot.create.enabled"); } // Bidding on lots currently enabled function getBidOnLotEnabled() override external view returns (bool) { return getSettingBool("auction.lot.bidding.enabled"); } // The minimum lot size relative to ETH value function getLotMinimumEthValue() override external view returns (uint256) { return getSettingUint("auction.lot.value.minimum"); } // The maximum lot size relative to ETH value function getLotMaximumEthValue() override external view returns (uint256) { return getSettingUint("auction.lot.value.maximum"); } // The maximum auction duration in blocks function getLotDuration() override external view returns (uint256) { return getSettingUint("auction.lot.duration"); } // The starting price relative to current RPL price, as a fraction of 1 ether function getStartingPriceRatio() override external view returns (uint256) { return getSettingUint("auction.price.start"); } // The reserve price relative to current RPL price, as a fraction of 1 ether function getReservePriceRatio() override external view returns (uint256) { return getSettingUint("auction.price.reserve"); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketStorageInterface { // Deploy status function getDeployedStatus() external view returns (bool); // Guardian function getGuardian() external view returns(address); function setGuardian(address _newAddress) external; function confirmGuardian() external; // Getters function getAddress(bytes32 _key) external view returns (address); function getUint(bytes32 _key) external view returns (uint); function getString(bytes32 _key) external view returns (string memory); function getBytes(bytes32 _key) external view returns (bytes memory); function getBool(bytes32 _key) external view returns (bool); function getInt(bytes32 _key) external view returns (int); function getBytes32(bytes32 _key) external view returns (bytes32); // Setters function setAddress(bytes32 _key, address _value) external; function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string calldata _value) external; function setBytes(bytes32 _key, bytes calldata _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; // Deleters function deleteAddress(bytes32 _key) external; function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; // Arithmetic function addUint(bytes32 _key, uint256 _amount) external; function subUint(bytes32 _key, uint256 _amount) external; // Protected storage function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address); function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address); function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external; function confirmWithdrawalAddress(address _nodeAddress) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAOProtocolSettingsAuctionInterface { function getCreateLotEnabled() external view returns (bool); function getBidOnLotEnabled() external view returns (bool); function getLotMinimumEthValue() external view returns (uint256); function getLotMaximumEthValue() external view returns (uint256); function getLotDuration() external view returns (uint256); function getStartingPriceRatio() external view returns (uint256); function getReservePriceRatio() external view returns (uint256); } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAOProtocolSettingsInterface { function getSettingUint(string memory _settingPath) external view returns (uint256); function setSettingUint(string memory _settingPath, uint256 _value) external; function getSettingBool(string memory _settingPath) external view returns (bool); function setSettingBool(string memory _settingPath, bool _value) external; function getSettingAddress(string memory _settingPath) external view returns (address); function setSettingAddress(string memory _settingPath, address _value) external; }
The maximum auction duration in blocks
function getLotDuration() override external view returns (uint256) { return getSettingUint("auction.lot.duration"); }
13,416,388
/** *Submitted for verification at Etherscan.io on 2020-10-12 */ // SPDX-License-Identifier: GPL-3.0-or-later /** Author: CoFiX Core, https://cofix.io Commit hash: v0.9.5-1-g7141c43 Repository: https://github.com/Computable-Finance/CoFiX Issues: https://github.com/Computable-Finance/CoFiX/issues */ pragma solidity 0.6.12; // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // /* * ABDK Math 64.64 Smart Contract Library. Copyright 1 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /** * @dev Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /** * @dev Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1)); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << 127 - msb; for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= 63 - (x >> 64); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= xe; else x <<= -xe; uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= re; else if (re < 0) result >>= -re; return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x, uint256 r) private pure returns (uint128) { if (x == 0) return 0; else { require (r > 0); while (true) { uint256 rr = x / r; if (r == rr || r + 1 == rr) return uint128 (r); else if (r == rr + 1) return uint128 (rr); r = r + rr + 1 >> 1; } } } } // interface INest_3_OfferPrice { function transfer(address to, uint value) external returns (bool); /** * @dev Update and check the latest price * @param tokenAddress Token address * @return ethAmount ETH amount * @return erc20Amount Erc20 amount * @return blockNum Price block */ function updateAndCheckPriceNow(address tokenAddress) external payable returns(uint256 ethAmount, uint256 erc20Amount, uint256 blockNum); /** * @dev Update and check the effective price list * @param tokenAddress Token address * @param num Number of prices to check * @return uint256[] price list */ function updateAndCheckPriceList(address tokenAddress, uint256 num) external payable returns (uint256[] memory); // Activate the price checking function function activation() external; // Check the minimum ETH cost of obtaining the price function checkPriceCostLeast(address tokenAddress) external view returns(uint256); // Check the maximum ETH cost of obtaining the price function checkPriceCostMost(address tokenAddress) external view returns(uint256); // Check the cost of a single price data function checkPriceCostSingle(address tokenAddress) external view returns(uint256); // Check whether the price-checking functions can be called function checkUseNestPrice(address target) external view returns (bool); // Check whether the address is in the blocklist function checkBlocklist(address add) external view returns(bool); // Check the amount of NEST to destroy to call prices function checkDestructionAmount() external view returns(uint256); // Check the waiting time to start calling prices function checkEffectTime() external view returns (uint256); } // interface ICoFiXKTable { function setK0(uint256 tIdx, uint256 sigmaIdx, int128 k0) external; function setK0InBatch(uint256[] memory tIdxs, uint256[] memory sigmaIdxs, int128[] memory k0s) external; function getK0(uint256 tIdx, uint256 sigmaIdx) external view returns (int128); } // // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // interface ICoFiXController { event NewK(address token, int128 K, int128 sigma, uint256 T, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 tIdx, uint256 sigmaIdx, int128 K0); event NewGovernance(address _new); event NewOracle(address _priceOracle); event NewKTable(address _kTable); event NewTimespan(uint256 _timeSpan); event NewKRefreshInterval(uint256 _interval); event NewKLimit(int128 maxK0); event NewGamma(int128 _gamma); event NewTheta(address token, uint32 theta); function addCaller(address caller) external; function queryOracle(address token, uint8 op, bytes memory data) external payable returns (uint256 k, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 theta); } // interface INest_3_VoteFactory { // 1111 function checkAddress(string calldata name) external view returns (address contractAddress); // _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice"))); } // interface ICoFiXERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); // function name() external pure returns (string memory); // function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } // interface ICoFiXPair is ICoFiXERC20 { struct OraclePrice { uint256 ethAmount; uint256 erc20Amount; uint256 blockNum; uint256 K; uint256 theta; } // All pairs: {ETH <-> ERC20 Token} event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, address outToken, uint outAmount, address indexed to); event Swap( address indexed sender, uint amountIn, uint amountOut, address outToken, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1); function mint(address to) external payable returns (uint liquidity, uint oracleFeeChange); function burn(address outToken, address to) external payable returns (uint amountOut, uint oracleFeeChange); function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo); function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo); function skim(address to) external; function sync() external; function initialize(address, address, string memory, string memory) external; /// @dev get Net Asset Value Per Share /// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token} /// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token} /// @return navps The Net Asset Value Per Share (liquidity) represents function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps); } // // Controller contract to call NEST Oracle for prices, managed by governance // Governance role of this contract should be the `Timelock` contract, which is further managed by a multisig contract contract CoFiXController is ICoFiXController { using SafeMath for uint256; enum CoFiX_OP { QUERY, MINT, BURN, SWAP_WITH_EXACT, SWAP_FOR_EXACT } // operations in CoFiX uint256 constant public AONE = 1 ether; uint256 constant public K_BASE = 1E8; uint256 constant public NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy uint256 constant internal TIMESTAMP_MODULUS = 2**32; int128 constant internal SIGMA_STEP = 0x346DC5D638865; // (0.00005*2**64).toString(16), 0.00005 as 64.64-bit fixed point int128 constant internal ZERO_POINT_FIVE = 0x8000000000000000; // (0.5*2**64).toString(16) uint256 constant internal K_EXPECTED_VALUE = 0.0025*1E8; // impact cost params uint256 constant internal C_BUYIN_ALPHA = 25700000000000; // 1=2.570e-05*1e18 uint256 constant internal C_BUYIN_BETA = 854200000000; // 1=8.542e-07*1e18 uint256 constant internal C_SELLOUT_ALPHA = 117100000000000; // 1=-1.171e-04*1e18 uint256 constant internal C_SELLOUT_BETA = 838600000000; // 1=8.386e-07*1e18 mapping(address => uint32[3]) internal KInfoMap; // gas saving, index [0] is k vlaue, index [1] is updatedAt, index [2] is theta mapping(address => bool) public callerAllowed; INest_3_VoteFactory public immutable voteFactory; // managed by governance address public governance; address public immutable nestToken; address public immutable factory; address public kTable; uint256 public timespan = 14; uint256 public kRefreshInterval = 5 minutes; uint256 public DESTRUCTION_AMOUNT = 0 ether; // from nest oracle int128 public MAX_K0 = 0xCCCCCCCCCCCCD00; // (0.05*2**64).toString(16) int128 public GAMMA = 0x8000000000000000; // (0.5*2**64).toString(16) modifier onlyGovernance() { require(msg.sender == governance, "CoFiXCtrl: !governance"); _; } constructor(address _voteFactory, address _nest, address _factory, address _kTable) public { governance = msg.sender; voteFactory = INest_3_VoteFactory(address(_voteFactory)); nestToken = _nest; factory = _factory; kTable = _kTable; } receive() external payable {} /* setters for protocol governance */ function setGovernance(address _new) external onlyGovernance { governance = _new; emit NewGovernance(_new); } function setKTable(address _kTable) external onlyGovernance { kTable = _kTable; emit NewKTable(_kTable); } function setTimespan(uint256 _timeSpan) external onlyGovernance { timespan = _timeSpan; emit NewTimespan(_timeSpan); } function setKRefreshInterval(uint256 _interval) external onlyGovernance { kRefreshInterval = _interval; emit NewKRefreshInterval(_interval); } function setOracleDestructionAmount(uint256 _amount) external onlyGovernance { DESTRUCTION_AMOUNT = _amount; } function setKLimit(int128 maxK0) external onlyGovernance { MAX_K0 = maxK0; emit NewKLimit(maxK0); } function setGamma(int128 _gamma) external onlyGovernance { GAMMA = _gamma; emit NewGamma(_gamma); } function setTheta(address token, uint32 theta) external onlyGovernance { KInfoMap[token][2] = theta; emit NewTheta(token, theta); } // Activate on NEST Oracle, should not be called twice for the same nest oracle function activate() external onlyGovernance { // address token, address from, address to, uint value TransferHelper.safeTransferFrom(nestToken, msg.sender, address(this), DESTRUCTION_AMOUNT); address oracle = voteFactory.checkAddress("nest.v3.offerPrice"); // address token, address to, uint value TransferHelper.safeApprove(nestToken, oracle, DESTRUCTION_AMOUNT); INest_3_OfferPrice(oracle).activation(); // nest.transferFrom will be called TransferHelper.safeApprove(nestToken, oracle, 0); // ensure safety } function addCaller(address caller) external override { require(msg.sender == factory || msg.sender == governance, "CoFiXCtrl: only factory or gov"); callerAllowed[caller] = true; } // Calc variance of price and K in CoFiX is very expensive // We use expected value of K based on statistical calculations here to save gas // In the near future, NEST could provide the variance of price directly. We will adopt it then. // We can make use of `data` bytes in the future function queryOracle(address token, uint8 op, bytes memory data) external override payable returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum, uint256 _theta) { require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed"); (_ethAmount, _erc20Amount, _blockNum) = getLatestPrice(token); CoFiX_OP cop = CoFiX_OP(op); uint256 impactCost; if (cop == CoFiX_OP.SWAP_WITH_EXACT) { impactCost = calcImpactCostFor_SWAP_WITH_EXACT(token, data, _ethAmount, _erc20Amount); } else if (cop == CoFiX_OP.SWAP_FOR_EXACT) { impactCost = calcImpactCostFor_SWAP_FOR_EXACT(token, data, _ethAmount, _erc20Amount); } else if (cop == CoFiX_OP.BURN) { impactCost = calcImpactCostFor_BURN(token, data, _ethAmount, _erc20Amount); } return (K_EXPECTED_VALUE.add(impactCost), _ethAmount, _erc20Amount, _blockNum, KInfoMap[token][2]); } function calcImpactCostFor_BURN(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) { // bytes memory data = abi.encode(msg.sender, outToken, to, liquidity); (, address outToken, , uint256 liquidity) = abi.decode(data, (address, address, address, uint256)); // calc real vol by liquidity * np uint256 navps = ICoFiXPair(msg.sender).getNAVPerShare(ethAmount, erc20Amount); // pair call controller, msg.sender is pair uint256 vol = liquidity.mul(navps).div(NAVPS_BASE); if (block.coinbase != token) { //injected CONTRACT AFFECTED BY MINERS // buy in ETH, outToken is ETH return impactCostForBuyInETH(vol); } // sell out liquidity, outToken is token, take this as sell out ETH and get token return impactCostForSellOutETH(vol); } function calcImpactCostFor_SWAP_WITH_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) { (, address outToken, , uint256 amountIn) = abi.decode(data, (address, address, address, uint256)); if (outToken != token) { // buy in ETH, outToken is ETH, amountIn is token // convert to amountIn in ETH uint256 vol = uint256(amountIn).mul(ethAmount).div(erc20Amount); return impactCostForBuyInETH(vol); } // sell out ETH, amountIn is ETH return impactCostForSellOutETH(amountIn); } function calcImpactCostFor_SWAP_FOR_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) { (, address outToken, uint256 amountOutExact,) = abi.decode(data, (address, address, uint256, address)); if (outToken != token) { // buy in ETH, outToken is ETH, amountOutExact is ETH return impactCostForBuyInETH(amountOutExact); } // sell out ETH, amountIn is ETH, amountOutExact is token // convert to amountOutExact in ETH uint256 vol = uint256(amountOutExact).mul(ethAmount).div(erc20Amount); return impactCostForSellOutETH(vol); } // impact cost // - C = 0, if VOL < 500 // - C = 1 + 1 * VOL, if VOL >= 500 // 1=2.570e-0511=8.542e-07 function impactCostForBuyInETH(uint256 vol) public pure returns (uint256 impactCost) { if (vol < 500 ether) { return 0; } // return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).mul(1e8).div(1e18); return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).div(1e10); // combine mul div } // 1=-1.171e-0411=8.386e-07 function impactCostForSellOutETH(uint256 vol) public pure returns (uint256 impactCost) { if (vol < 500 ether) { return 0; } // return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).mul(1e8).div(1e18); return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).div(1e10); // combine mul div } // // We can make use of `data` bytes in the future // function queryOracle(address token, bytes memory /*data*/) external override payable returns (uint256 _k, uint256, uint256, uint256, uint256) { // require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed"); // uint256 _now = block.timestamp % TIMESTAMP_MODULUS; // 2106 // { // uint256 _lastUpdate = KInfoMap[token][1]; // if (_now >= _lastUpdate && _now.sub(_lastUpdate) <= kRefreshInterval) { // lastUpdate (2105) | 2106 | now (1) // return getLatestPrice(token); // } // } // uint256 _balanceBefore = address(this).balance; // // int128 K0; // K0AndK[0] // // int128 K; // K0AndK[1] // int128[2] memory K0AndK; // // OraclePrice memory _op; // uint256[7] memory _op; // int128 _variance; // // (_variance, _op.T, _op.ethAmount, _op.erc20Amount, _op.blockNum) = calcVariance(token); // (_variance, _op[0], _op[1], _op[2], _op[3]) = calcVariance(token); // { // // int128 _volatility = ABDKMath64x64.sqrt(_variance); // // int128 _sigma = ABDKMath64x64.div(_volatility, ABDKMath64x64.sqrt(ABDKMath64x64.fromUInt(timespan))); // int128 _sigma = ABDKMath64x64.sqrt(ABDKMath64x64.div(_variance, ABDKMath64x64.fromUInt(timespan))); // combined into one sqrt // // tIdx is _op[4] // // sigmaIdx is _op[5] // _op[4] = (_op[0].add(5)).div(10); // rounding to the nearest // _op[5] = ABDKMath64x64.toUInt( // ABDKMath64x64.add( // ABDKMath64x64.div(_sigma, SIGMA_STEP), // _sigma / 0.0001, e.g. (0.00098/0.0001)=9.799 => 9 // ZERO_POINT_FIVE // e.g. (0.00098/0.0001)+0.5=10.299 => 10 // ) // ); // if (_op[5] > 0) { // _op[5] = _op[5].sub(1); // } // // getK0(uint256 tIdx, uint256 sigmaIdx) // // K0 is K0AndK[0] // K0AndK[0] = ICoFiXKTable(kTable).getK0( // _op[4], // _op[5] // ); // // K = gamma * K0 // K0AndK[1] = ABDKMath64x64.mul(GAMMA, K0AndK[0]); // emit NewK(token, K0AndK[1], _sigma, _op[0], _op[1], _op[2], _op[3], _op[4], _op[5], K0AndK[0]); // } // require(K0AndK[0] <= MAX_K0, "CoFiXCtrl: K0"); // { // // we could decode data in the future to pay the fee change and mining award token directly to reduce call cost // // TransferHelper.safeTransferETH(payback, msg.value.sub(_balanceBefore.sub(address(this).balance))); // uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance)); // if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); // _k = ABDKMath64x64.toUInt(ABDKMath64x64.mul(K0AndK[1], ABDKMath64x64.fromUInt(K_BASE))); // _op[6] = KInfoMap[token][2]; // theta // KInfoMap[token][0] = uint32(_k); // k < MAX_K << uint32(-1) // KInfoMap[token][1] = uint32(_now); // 2106 // return (_k, _op[1], _op[2], _op[3], _op[6]); // } // } // function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta) { // k = KInfoMap[token][0]; // updatedAt = KInfoMap[token][1]; // theta = KInfoMap[token][2]; // } function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta) { k = uint32(K_EXPECTED_VALUE); updatedAt = uint32(block.timestamp); theta = KInfoMap[token][2]; } function getLatestPrice(address token) internal returns (uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum) { uint256 _balanceBefore = address(this).balance; address oracle = voteFactory.checkAddress("nest.v3.offerPrice"); uint256[] memory _rawPriceList = INest_3_OfferPrice(oracle).updateAndCheckPriceList{value: msg.value}(token, 1); require(_rawPriceList.length == 3, "CoFiXCtrl: bad price len"); // validate T uint256 _T = block.number.sub(_rawPriceList[2]).mul(timespan); require(_T < 900, "CoFiXCtrl: oralce price outdated"); uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance)); if (block.number > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); //injected CONTRACT AFFECTED BY MINERS return (_rawPriceList[0], _rawPriceList[1], _rawPriceList[2]); // return (K_EXPECTED_VALUE, _rawPriceList[0], _rawPriceList[1], _rawPriceList[2], KInfoMap[token][2]); } // calc Variance, a.k.a. sigma squared function calcVariance(address token) internal returns ( int128 _variance, uint256 _T, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum ) // keep these variables to make return values more clear { address oracle = voteFactory.checkAddress("nest.v3.offerPrice"); // query raw price list from nest oracle (newest to oldest) uint256[] memory _rawPriceList = INest_3_OfferPrice(oracle).updateAndCheckPriceList{value: msg.value}(token, 50); require(_rawPriceList.length == 150, "CoFiXCtrl: bad price len"); // calc P a.k.a. price from the raw price data (ethAmount, erc20Amount, blockNum) uint256[] memory _prices = new uint256[](50); for (uint256 i = 0; i < 50; i++) { // 0..50 (newest to oldest), so _prices[0] is p49 (latest price), _prices[49] is p0 (base price) _prices[i] = calcPrice(_rawPriceList[i*3], _rawPriceList[i*3+1]); } // calc x a.k.a. standardized sequence of differences (newest to oldest) int128[] memory _stdSeq = new int128[](49); for (uint256 i = 0; i < 49; i++) { _stdSeq[i] = calcStdSeq(_prices[i], _prices[i+1], _prices[49], _rawPriceList[i*3+2], _rawPriceList[(i+1)*3+2]); } // Option 1: calc variance of x // Option 2: calc mean value first and then calc variance // Use option 1 for gas saving int128 _sumSq; // sum of squares of x int128 _sum; // sum of x for (uint256 i = 0; i < 49; i++) { _sumSq = ABDKMath64x64.add(ABDKMath64x64.pow(_stdSeq[i], 2), _sumSq); _sum = ABDKMath64x64.add(_stdSeq[i], _sum); } _variance = ABDKMath64x64.sub( ABDKMath64x64.div( _sumSq, ABDKMath64x64.fromUInt(49) ), ABDKMath64x64.div( ABDKMath64x64.pow(_sum, 2), ABDKMath64x64.fromUInt(49*49) ) ); _T = block.number.sub(_rawPriceList[2]).mul(timespan); return (_variance, _T, _rawPriceList[0], _rawPriceList[1], _rawPriceList[2]); } function calcPrice(uint256 _ethAmount, uint256 _erc20Amount) internal pure returns (uint256) { return AONE.mul(_erc20Amount).div(_ethAmount); } // diff ratio could be negative // p2: P_{i} // p1: P_{i-1} // p0: P_{0} function calcDiffRatio(uint256 p2, uint256 p1, uint256 p0) internal pure returns (int128) { int128 _p2 = ABDKMath64x64.fromUInt(p2); int128 _p1 = ABDKMath64x64.fromUInt(p1); int128 _p0 = ABDKMath64x64.fromUInt(p0); return ABDKMath64x64.div(ABDKMath64x64.sub(_p2, _p1), _p0); } // p2: P_{i} // p1: P_{i-1} // p0: P_{0} // bn2: blocknum_{i} // bn1: blocknum_{i-1} function calcStdSeq(uint256 p2, uint256 p1, uint256 p0, uint256 bn2, uint256 bn1) internal pure returns (int128) { return ABDKMath64x64.div( calcDiffRatio(p2, p1, p0), ABDKMath64x64.sqrt( ABDKMath64x64.fromUInt(bn2.sub(bn1)) // c must be larger than d ) ); } }
diff ratio could be negative p2: P_{i} p1: P_{i-1} p0: P_{0}
function calcDiffRatio(uint256 p2, uint256 p1, uint256 p0) internal pure returns (int128) { int128 _p2 = ABDKMath64x64.fromUInt(p2); int128 _p1 = ABDKMath64x64.fromUInt(p1); int128 _p0 = ABDKMath64x64.fromUInt(p0); return ABDKMath64x64.div(ABDKMath64x64.sub(_p2, _p1), _p0); }
12,711,977
./full_match/3/0xe3E78C43980456568eE5902C155079e725dcBB99/sources/browser/ERC1400ERC20.sol
[ERC1400 INTERFACE (9/9)] Know the reason on success or failure based on the EIP-1066 application-specific status codes. partition Name of the partition. from Token holder. to Token recipient. value Number of tokens to transfer. data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] operatorData Information attached to the transfer, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] return ESC (Ethereum Status Code) following the EIP-1066 standard. return Additional bytes32 parameter that can be used to define application specific reason codes with additional details (for example the transfer restriction rule responsible for making the transfer operation invalid). return Destination partition./
function canOperatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external view returns (byte, bytes32, bytes32) { if(!_checkCertificate(operatorData, 0, functionSig)) { return _canTransfer(functionSig, partition, msg.sender, from, to, value, data, operatorData); } }
14,141,614
// Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev 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-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) 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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) 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 interfaces/IPreparable.sol pragma solidity 0.8.9; interface IPreparable { event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay); event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay); event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue); event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue); event ConfigReset(bytes32 indexed key); } // File interfaces/IStrategy.sol pragma solidity 0.8.9; interface IStrategy { function name() external view returns (string memory); function deposit() external payable returns (bool); function balance() external view returns (uint256); function withdraw(uint256 amount) external returns (bool); function withdrawAll() external returns (uint256); function harvestable() external view returns (uint256); function harvest() external returns (uint256); function strategist() external view returns (address); function shutdown() external returns (bool); function hasPendingFunds() external view returns (bool); } // File interfaces/IVault.sol pragma solidity 0.8.9; /** * @title Interface for a Vault */ interface IVault is IPreparable { event StrategyActivated(address indexed strategy); event StrategyDeactivated(address indexed strategy); /** * @dev 'netProfit' is the profit after all fees have been deducted */ event Harvest(uint256 indexed netProfit, uint256 indexed loss); function initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) external; function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256); function deposit() external payable; function withdraw(uint256 amount) external returns (bool); function initializeStrategy(address strategy_) external returns (bool); function withdrawAll() external; function withdrawFromReserve(uint256 amount) external; function getStrategy() external view returns (IStrategy); function getStrategiesWaitingForRemoval() external view returns (address[] memory); function getAllocatedToStrategyWaitingForRemoval(address strategy) external view returns (uint256); function getTotalUnderlying() external view returns (uint256); function getUnderlying() external view returns (address); } // File interfaces/pool/ILiquidityPool.sol pragma solidity 0.8.9; interface ILiquidityPool is IPreparable { event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens); event DepositFor( address indexed minter, address indexed mintee, uint256 depositAmount, uint256 mintedLpTokens ); event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens); event LpTokenSet(address indexed lpToken); event StakerVaultSet(address indexed stakerVault); function redeem(uint256 redeemTokens) external returns (uint256); function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256); function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256); function deposit(uint256 mintAmount) external payable returns (uint256); function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256); function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable returns (uint256); function depositFor(address account, uint256 depositAmount) external payable returns (uint256); function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) external payable returns (uint256); function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external returns (uint256); function handleLpTokenTransfer( address from, address to, uint256 amount ) external; function executeNewVault() external returns (address); function executeNewMaxWithdrawalFee() external returns (uint256); function executeNewRequiredReserves() external returns (uint256); function executeNewReserveDeviation() external returns (uint256); function setLpToken(address _lpToken) external returns (bool); function setStaker() external returns (bool); function isCapped() external returns (bool); function uncap() external returns (bool); function updateDepositCap(uint256 _depositCap) external returns (bool); function getUnderlying() external view returns (address); function getLpToken() external view returns (address); function getWithdrawalFee(address account, uint256 amount) external view returns (uint256); function getVault() external view returns (IVault); function exchangeRate() external view returns (uint256); } // File interfaces/IGasBank.sol pragma solidity 0.8.9; interface IGasBank { event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, address indexed receiver, uint256 value); function depositFor(address account) external payable; function withdrawUnused(address account) external; function withdrawFrom(address account, uint256 amount) external; function withdrawFrom( address account, address payable to, uint256 amount ) external; function balanceOf(address account) external view returns (uint256); } // File interfaces/oracles/IOracleProvider.sol pragma solidity 0.8.9; interface IOracleProvider { /// @notice Quotes the USD price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the USD price of the asset function getPriceUSD(address baseAsset) external view returns (uint256); /// @notice Quotes the ETH price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the ETH price of the asset function getPriceETH(address baseAsset) external view returns (uint256); } // File libraries/AddressProviderMeta.sol pragma solidity 0.8.9; library AddressProviderMeta { struct Meta { bool freezable; bool frozen; } function fromUInt(uint256 value) internal pure returns (Meta memory) { Meta memory meta; meta.freezable = (value & 1) == 1; meta.frozen = ((value >> 1) & 1) == 1; return meta; } function toUInt(Meta memory meta) internal pure returns (uint256) { uint256 value; value |= meta.freezable ? 1 : 0; value |= meta.frozen ? 1 << 1 : 0; return value; } } // File interfaces/IAddressProvider.sol pragma solidity 0.8.9; // solhint-disable ordering interface IAddressProvider is IPreparable { event KnownAddressKeyAdded(bytes32 indexed key); event StakerVaultListed(address indexed stakerVault); event StakerVaultDelisted(address indexed stakerVault); event ActionListed(address indexed action); event PoolListed(address indexed pool); event PoolDelisted(address indexed pool); event VaultUpdated(address indexed previousVault, address indexed newVault); /** Key functions */ function getKnownAddressKeys() external view returns (bytes32[] memory); function freezeAddress(bytes32 key) external; /** Pool functions */ function allPools() external view returns (address[] memory); function addPool(address pool) external; function poolsCount() external view returns (uint256); function getPoolAtIndex(uint256 index) external view returns (address); function isPool(address pool) external view returns (bool); function removePool(address pool) external returns (bool); function getPoolForToken(address token) external view returns (ILiquidityPool); function safeGetPoolForToken(address token) external view returns (address); /** Vault functions */ function updateVault(address previousVault, address newVault) external; function allVaults() external view returns (address[] memory); function vaultsCount() external view returns (uint256); function getVaultAtIndex(uint256 index) external view returns (address); function isVault(address vault) external view returns (bool); /** Action functions */ function allActions() external view returns (address[] memory); function addAction(address action) external returns (bool); function isAction(address action) external view returns (bool); /** Address functions */ function initializeAddress( bytes32 key, address initialAddress, bool frezable ) external; function initializeAndFreezeAddress(bytes32 key, address initialAddress) external; function getAddress(bytes32 key) external view returns (address); function getAddress(bytes32 key, bool checkExists) external view returns (address); function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory); function prepareAddress(bytes32 key, address newAddress) external returns (bool); function executeAddress(bytes32 key) external returns (address); function resetAddress(bytes32 key) external returns (bool); /** Staker vault functions */ function allStakerVaults() external view returns (address[] memory); function tryGetStakerVault(address token) external view returns (bool, address); function getStakerVault(address token) external view returns (address); function addStakerVault(address stakerVault) external returns (bool); function isStakerVault(address stakerVault, address token) external view returns (bool); function isStakerVaultRegistered(address stakerVault) external view returns (bool); function isWhiteListedFeeHandler(address feeHandler) external view returns (bool); } // File interfaces/tokenomics/IInflationManager.sol pragma solidity 0.8.9; interface IInflationManager { event KeeperGaugeListed(address indexed pool, address indexed keeperGauge); event AmmGaugeListed(address indexed token, address indexed ammGauge); event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge); event AmmGaugeDelisted(address indexed token, address indexed ammGauge); /** Pool functions */ function setKeeperGauge(address pool, address _keeperGauge) external returns (bool); function setAmmGauge(address token, address _ammGauge) external returns (bool); function getAllAmmGauges() external view returns (address[] memory); function getLpRateForStakerVault(address stakerVault) external view returns (uint256); function getKeeperRateForPool(address pool) external view returns (uint256); function getAmmRateForToken(address token) external view returns (uint256); function getKeeperWeightForPool(address pool) external view returns (uint256); function getAmmWeightForToken(address pool) external view returns (uint256); function getLpPoolWeight(address pool) external view returns (uint256); function getKeeperGaugeForPool(address pool) external view returns (address); function getAmmGaugeForToken(address token) external view returns (address); function isInflationWeightManager(address account) external view returns (bool); function removeStakerVaultFromInflation(address stakerVault, address lpToken) external; function addGaugeForVault(address lpToken) external returns (bool); function whitelistGauge(address gauge) external; function checkpointAllGauges() external returns (bool); function mintRewards(address beneficiary, uint256 amount) external; function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool) external returns (bool); /** Weight setter functions **/ function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool); function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool); function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool); function executeLpPoolWeight(address lpToken) external returns (uint256); function executeAmmTokenWeight(address token) external returns (uint256); function executeKeeperPoolWeight(address pool) external returns (uint256); function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights) external returns (bool); function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights) external returns (bool); function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights) external returns (bool); function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool); function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool); function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool); } // File interfaces/IController.sol pragma solidity 0.8.9; // solhint-disable ordering interface IController is IPreparable { function addressProvider() external view returns (IAddressProvider); function inflationManager() external view returns (IInflationManager); function addStakerVault(address stakerVault) external returns (bool); function removePool(address pool) external returns (bool); /** Keeper functions */ function prepareKeeperRequiredStakedBKD(uint256 amount) external; function executeKeeperRequiredStakedBKD() external; function getKeeperRequiredStakedBKD() external view returns (uint256); function canKeeperExecuteAction(address keeper) external view returns (bool); /** Miscellaneous functions */ function getTotalEthRequiredForGas(address payer) external view returns (uint256); } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] // 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 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 `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); } // File interfaces/ILpToken.sol pragma solidity 0.8.9; interface ILpToken is IERC20Upgradeable { function mint(address account, uint256 lpTokens) external; function burn(address account, uint256 burnAmount) external returns (uint256); function burn(uint256 burnAmount) external; function minter() external view returns (address); function initialize( string memory name_, string memory symbol_, uint8 _decimals, address _minter ) external returns (bool); } // File interfaces/IStakerVault.sol pragma solidity 0.8.9; interface IStakerVault { event Staked(address indexed account, uint256 amount); event Unstaked(address indexed account, uint256 amount); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function initialize(address _token) external; function initializeLpGauge(address _lpGauge) external returns (bool); function stake(uint256 amount) external returns (bool); function stakeFor(address account, uint256 amount) external returns (bool); function unstake(uint256 amount) external returns (bool); function unstakeFor( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transfer(address account, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function getToken() external view returns (address); function balanceOf(address account) external view returns (uint256); function stakedAndActionLockedBalanceOf(address account) external view returns (uint256); function actionLockedBalanceOf(address account) external view returns (uint256); function increaseActionLockedBalance(address account, uint256 amount) external returns (bool); function decreaseActionLockedBalance(address account, uint256 amount) external returns (bool); function getStakedByActions() external view returns (uint256); function addStrategy(address strategy) external returns (bool); function getPoolTotalStaked() external view returns (uint256); function prepareLpGauge(address _lpGauge) external returns (bool); function executeLpGauge() external returns (bool); function getLpGauge() external view returns (address); function poolCheckpoint() external returns (bool); function isStrategy(address user) external view returns (bool); } // File interfaces/IVaultReserve.sol pragma solidity 0.8.9; interface IVaultReserve { event Deposit(address indexed vault, address indexed token, uint256 amount); event Withdraw(address indexed vault, address indexed token, uint256 amount); event VaultListed(address indexed vault); function deposit(address token, uint256 amount) external payable returns (bool); function withdraw(address token, uint256 amount) external returns (bool); function getBalance(address vault, address token) external view returns (uint256); function canWithdraw(address vault) external view returns (bool); } // File interfaces/IRoleManager.sol pragma solidity 0.8.9; interface IRoleManager { event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, address account ) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, bytes32 role3, address account ) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } // File interfaces/tokenomics/IBkdToken.sol pragma solidity 0.8.9; interface IBkdToken is IERC20 { function mint(address account, uint256 amount) external; } // File libraries/AddressProviderKeys.sol pragma solidity 0.8.9; library AddressProviderKeys { bytes32 internal constant _TREASURY_KEY = "treasury"; bytes32 internal constant _GAS_BANK_KEY = "gasBank"; bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve"; bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry"; bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider"; bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory"; bytes32 internal constant _CONTROLLER_KEY = "controller"; bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker"; bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager"; } // File libraries/AddressProviderHelpers.sol pragma solidity 0.8.9; library AddressProviderHelpers { /** * @return The address of the treasury. */ function getTreasury(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._TREASURY_KEY); } /** * @return The gas bank. */ function getGasBank(IAddressProvider provider) internal view returns (IGasBank) { return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY)); } /** * @return The address of the vault reserve. */ function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) { return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY)); } /** * @return The address of the swapperRegistry. */ function getSwapperRegistry(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY); } /** * @return The oracleProvider. */ function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) { return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY)); } /** * @return the address of the BKD locker */ function getBKDLocker(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY); } /** * @return the address of the BKD locker */ function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) { return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY)); } /** * @return the controller */ function getController(IAddressProvider provider) internal view returns (IController) { return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY)); } } // File libraries/Errors.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Error { string internal constant ADDRESS_WHITELISTED = "address already whitelisted"; string internal constant ADMIN_ALREADY_SET = "admin has already been set once"; string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted"; string internal constant ADDRESS_NOT_FOUND = "address not found"; string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once"; string internal constant CONTRACT_PAUSED = "contract is paused"; string internal constant INVALID_AMOUNT = "invalid amount"; string internal constant INVALID_INDEX = "invalid index"; string internal constant INVALID_VALUE = "invalid msg.value"; string internal constant INVALID_SENDER = "invalid msg.sender"; string internal constant INVALID_TOKEN = "token address does not match pool's LP token address"; string internal constant INVALID_DECIMALS = "incorrect number of decimals"; string internal constant INVALID_ARGUMENT = "invalid argument"; string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted"; string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_POOL_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_LP_TOKEN_IMPLEMENTATION = "invalid LP Token implementation for given coin"; string internal constant INVALID_VAULT_IMPLEMENTATION = "invalid vault implementation for given coin"; string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION = "invalid stakerVault implementation for given coin"; string internal constant INSUFFICIENT_BALANCE = "insufficient balance"; string internal constant ADDRESS_ALREADY_SET = "Address is already set"; string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance"; string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received"; string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist"; string internal constant ADDRESS_FROZEN = "address is frozen"; string internal constant ROLE_EXISTS = "role already exists"; string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role"; string internal constant UNAUTHORIZED_ACCESS = "unauthorized access"; string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed"; string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed"; string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed"; string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed"; string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10"; string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold"; string internal constant NO_POSITION_EXISTS = "no position exists"; string internal constant POSITION_ALREADY_EXISTS = "position already exists"; string internal constant PROTOCOL_NOT_FOUND = "protocol not found"; string internal constant TOP_UP_FAILED = "top up failed"; string internal constant SWAP_PATH_NOT_FOUND = "swap path not found"; string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported"; string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN = "not enough funds were withdrawn from the pool"; string internal constant FAILED_TRANSFER = "transfer failed"; string internal constant FAILED_MINT = "mint failed"; string internal constant FAILED_REPAY_BORROW = "repay borrow failed"; string internal constant FAILED_METHOD_CALL = "method call failed"; string internal constant NOTHING_TO_CLAIM = "there is no claimable balance"; string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance"; string internal constant INVALID_MINTER = "the minter address of the LP token and the pool address do not match"; string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token"; string internal constant DEADLINE_NOT_ZERO = "deadline must be 0"; string internal constant DEADLINE_NOT_SET = "deadline is 0"; string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet"; string internal constant DELAY_TOO_SHORT = "delay be at least 3 days"; string internal constant INSUFFICIENT_UPDATE_BALANCE = "insufficient funds for updating the position"; string internal constant SAME_AS_CURRENT = "value must be different to existing value"; string internal constant NOT_CAPPED = "the pool is not currently capped"; string internal constant ALREADY_CAPPED = "the pool is already capped"; string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap"; string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas"; string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw"; string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas"; string internal constant DEPOSIT_FAILED = "deposit failed"; string internal constant GAS_TOO_HIGH = "too much ETH used for gas"; string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas"; string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add"; string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed"; string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet"; string internal constant UNDERLYING_NOT_WITHDRAWABLE = "pool does not support additional underlying coins to be withdrawn"; string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down"; string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist"; string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported"; string internal constant NO_DEX_SET = "no dex has been set for token"; string internal constant INVALID_TOKEN_PAIR = "invalid token pair"; string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action"; string internal constant ADDRESS_NOT_ACTION = "address is not registered action"; string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance"; string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve"; string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block"; string internal constant GAUGE_EXISTS = "Gauge already exists"; string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist"; string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex"; string internal constant PREPARED_WITHDRAWAL = "Cannot relock funds when withdrawal is being prepared"; string internal constant ASSET_NOT_SUPPORTED = "Asset not supported"; string internal constant STALE_PRICE = "Price is stale"; string internal constant NEGATIVE_PRICE = "Price is negative"; string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked"; string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded"; } // File libraries/ScaledMath.sol pragma solidity 0.8.9; /* * @dev To use functions of this contract, at least one of the numbers must * be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE` * if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale * of the number not scaled by `DECIMAL_SCALE` */ library ScaledMath { // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant DECIMAL_SCALE = 1e18; // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant ONE = 1e18; /** * @notice Performs a multiplication between two scaled numbers */ function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) { return (a * b) / DECIMAL_SCALE; } /** * @notice Performs a division between two scaled numbers */ function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE) / b; } /** * @notice Performs a division between two numbers, rounding up the result */ function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE + b - 1) / b; } /** * @notice Performs a division between two numbers, ignoring any scaling and rounding up the result */ function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a + b - 1) / b; } } // File libraries/Roles.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Roles { bytes32 internal constant GOVERNANCE = "governance"; bytes32 internal constant ADDRESS_PROVIDER = "address_provider"; bytes32 internal constant POOL_FACTORY = "pool_factory"; bytes32 internal constant CONTROLLER = "controller"; bytes32 internal constant GAUGE_ZAP = "gauge_zap"; bytes32 internal constant MAINTENANCE = "maintenance"; bytes32 internal constant INFLATION_MANAGER = "inflation_manager"; bytes32 internal constant POOL = "pool"; bytes32 internal constant VAULT = "vault"; } // File contracts/access/AuthorizationBase.sol pragma solidity 0.8.9; /** * @notice Provides modifiers for authorization */ abstract contract AuthorizationBase { /** * @notice Only allows a sender with `role` to perform the given action */ modifier onlyRole(bytes32 role) { require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with GOVERNANCE role to perform the given action */ modifier onlyGovernance() { require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles2(bytes32 role1, bytes32 role2) { require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles3( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _roleManager().hasAnyRole(role1, role2, role3, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } function roleManager() external view virtual returns (IRoleManager) { return _roleManager(); } function _roleManager() internal view virtual returns (IRoleManager); } // File contracts/access/Authorization.sol pragma solidity 0.8.9; contract Authorization is AuthorizationBase { IRoleManager internal immutable __roleManager; constructor(IRoleManager roleManager) { __roleManager = roleManager; } function _roleManager() internal view override returns (IRoleManager) { return __roleManager; } } // File contracts/utils/Preparable.sol pragma solidity 0.8.9; /** * @notice Implements the base logic for a two-phase commit * @dev This does not implements any access-control so publicly exposed * callers should make sure to have the proper checks in palce */ contract Preparable is IPreparable { uint256 private constant _MIN_DELAY = 3 days; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingUInts256; mapping(bytes32 => address) public currentAddresses; mapping(bytes32 => uint256) public currentUInts256; /** * @dev Deadlines shares the same namespace regardless of the type * of the pending variable so this needs to be enforced in the caller */ mapping(bytes32 => uint256) public deadlines; function _prepareDeadline(bytes32 key, uint256 delay) internal { require(deadlines[key] == 0, Error.DEADLINE_NOT_ZERO); require(delay >= _MIN_DELAY, Error.DELAY_TOO_SHORT); deadlines[key] = block.timestamp + delay; } /** * @notice Prepares an uint256 that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, uint256 value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingUInts256[key] = value; emit ConfigPreparedNumber(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay */ function _prepare(bytes32 key, uint256 value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Prepares an address that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, address value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingAddresses[key] = value; emit ConfigPreparedAddress(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,address,uint256)` but uses a default delay */ function _prepare(bytes32 key, address value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Reset a uint256 key * @return `true` if success. */ function _resetUInt256Config(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingUInts256[key] = 0; emit ConfigReset(key); return true; } /** * @notice Reset an address key * @return `true` if success. */ function _resetAddressConfig(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingAddresses[key] = address(0); emit ConfigReset(key); return true; } /** * @dev Checks the deadline of the key and reset it */ function _executeDeadline(bytes32 key) internal { uint256 deadline = deadlines[key]; require(block.timestamp >= deadline, Error.DEADLINE_NOT_REACHED); require(deadline != 0, Error.DEADLINE_NOT_SET); deadlines[key] = 0; } /** * @notice Execute uint256 config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeUInt256(bytes32 key) internal returns (uint256) { _executeDeadline(key); uint256 newValue = pendingUInts256[key]; _setConfig(key, newValue); return newValue; } /** * @notice Execute address config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeAddress(bytes32 key) internal returns (address) { _executeDeadline(key); address newValue = pendingAddresses[key]; _setConfig(key, newValue); return newValue; } function _setConfig(bytes32 key, address value) internal returns (address) { address oldValue = currentAddresses[key]; currentAddresses[key] = value; pendingAddresses[key] = address(0); deadlines[key] = 0; emit ConfigUpdatedAddress(key, oldValue, value); return value; } function _setConfig(bytes32 key, uint256 value) internal returns (uint256) { uint256 oldValue = currentUInts256[key]; currentUInts256[key] = value; pendingUInts256[key] = 0; deadlines[key] = 0; emit ConfigUpdatedNumber(key, oldValue, value); return value; } } // File contracts/utils/Pausable.sol pragma solidity 0.8.9; abstract contract Pausable { bool public isPaused; modifier notPaused() { require(!isPaused, Error.CONTRACT_PAUSED); _; } modifier onlyAuthorizedToPause() { require(_isAuthorizedToPause(msg.sender), Error.CONTRACT_PAUSED); _; } /** * @notice Pause the contract. * @return `true` if success. */ function pause() external onlyAuthorizedToPause returns (bool) { isPaused = true; return true; } /** * @notice Unpause the contract. * @return `true` if success. */ function unpause() external onlyAuthorizedToPause returns (bool) { isPaused = false; return true; } /** * @notice Returns true if `account` is authorized to pause the contract * @dev This should be implemented in contracts inheriting `Pausable` * to provide proper access control */ function _isAuthorizedToPause(address account) internal view virtual returns (bool); } // File contracts/pool/LiquidityPool.sol pragma solidity 0.8.9; /** * @dev Pausing/unpausing the pool will disable/re-enable deposits. */ abstract contract LiquidityPool is ILiquidityPool, Authorization, Preparable, Pausable, Initializable { using AddressProviderHelpers for IAddressProvider; using ScaledMath for uint256; using SafeERC20 for IERC20; struct WithdrawalFeeMeta { uint64 timeToWait; uint64 feeRatio; uint64 lastActionTimestamp; } bytes32 internal constant _VAULT_KEY = "Vault"; bytes32 internal constant _RESERVE_DEVIATION_KEY = "ReserveDeviation"; bytes32 internal constant _REQUIRED_RESERVES_KEY = "RequiredReserves"; bytes32 internal constant _MAX_WITHDRAWAL_FEE_KEY = "MaxWithdrawalFee"; bytes32 internal constant _MIN_WITHDRAWAL_FEE_KEY = "MinWithdrawalFee"; bytes32 internal constant _WITHDRAWAL_FEE_DECREASE_PERIOD_KEY = "WithdrawalFeeDecreasePeriod"; uint256 internal constant _INITIAL_RESERVE_DEVIATION = 0.005e18; // 0.5% uint256 internal constant _INITIAL_FEE_DECREASE_PERIOD = 1 weeks; uint256 internal constant _INITIAL_MAX_WITHDRAWAL_FEE = 0.03e18; // 3% /** * @notice even through admin votes and later governance, the withdrawal * fee will never be able to go above this value */ uint256 internal constant _MAX_WITHDRAWAL_FEE = 0.05e18; /** * @notice Keeps track of the withdrawal fees on a per-address basis */ mapping(address => WithdrawalFeeMeta) public withdrawalFeeMetas; IController public immutable controller; IAddressProvider public immutable addressProvider; uint256 public depositCap; IStakerVault public staker; ILpToken public lpToken; string public name; constructor(IController _controller) Authorization(_controller.addressProvider().getRoleManager()) { require(address(_controller) != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); controller = IController(_controller); addressProvider = IController(_controller).addressProvider(); } /** * @notice Deposit funds into liquidity pool and mint LP tokens in exchange. * @param depositAmount Amount of the underlying asset to supply. * @return The actual amount minted. */ function deposit(uint256 depositAmount) external payable override returns (uint256) { return depositFor(msg.sender, depositAmount, 0); } /** * @notice Deposit funds into liquidity pool and mint LP tokens in exchange. * @param depositAmount Amount of the underlying asset to supply. * @param minTokenAmount Minimum amount of LP tokens that should be minted. * @return The actual amount minted. */ function deposit(uint256 depositAmount, uint256 minTokenAmount) external payable override returns (uint256) { return depositFor(msg.sender, depositAmount, minTokenAmount); } /** * @notice Deposit funds into liquidity pool and stake LP Tokens in Staker Vault. * @param depositAmount Amount of the underlying asset to supply. * @param minTokenAmount Minimum amount of LP tokens that should be minted. * @return The actual amount minted and staked. */ function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable override returns (uint256) { uint256 amountMinted_ = depositFor(address(this), depositAmount, minTokenAmount); staker.stakeFor(msg.sender, amountMinted_); return amountMinted_; } /** * @notice Withdraws all funds from vault. * @dev Should be called in case of emergencies. */ function withdrawAll() external onlyGovernance { getVault().withdrawAll(); } function setLpToken(address _lpToken) external override onlyRoles2(Roles.GOVERNANCE, Roles.POOL_FACTORY) returns (bool) { require(address(lpToken) == address(0), Error.ADDRESS_ALREADY_SET); require(ILpToken(_lpToken).minter() == address(this), Error.INVALID_MINTER); lpToken = ILpToken(_lpToken); _approveStakerVaultSpendingLpTokens(); emit LpTokenSet(_lpToken); return true; } /** * @notice Checkpoint function to update a user's withdrawal fees on deposit and redeem * @param from Address sending from * @param to Address sending to * @param amount Amount to redeem or deposit */ function handleLpTokenTransfer( address from, address to, uint256 amount ) external override { require( msg.sender == address(lpToken) || msg.sender == address(staker), Error.UNAUTHORIZED_ACCESS ); if ( addressProvider.isStakerVault(to, address(lpToken)) || addressProvider.isStakerVault(from, address(lpToken)) || addressProvider.isAction(to) || addressProvider.isAction(from) ) { return; } if (to != address(0)) { _updateUserFeesOnDeposit(to, from, amount); } } /** * @notice Prepare update of required reserve ratio (with time delay enforced). * @param _newRatio New required reserve ratio. * @return `true` if success. */ function prepareNewRequiredReserves(uint256 _newRatio) external onlyGovernance returns (bool) { require(_newRatio <= ScaledMath.ONE, Error.INVALID_AMOUNT); return _prepare(_REQUIRED_RESERVES_KEY, _newRatio); } /** * @notice Execute required reserve ratio update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New required reserve ratio. */ function executeNewRequiredReserves() external override returns (uint256) { uint256 requiredReserveRatio = _executeUInt256(_REQUIRED_RESERVES_KEY); _rebalanceVault(); return requiredReserveRatio; } /** * @notice Reset the prepared required reserves. * @return `true` if success. */ function resetRequiredReserves() external onlyGovernance returns (bool) { return _resetUInt256Config(_REQUIRED_RESERVES_KEY); } /** * @notice Prepare update of reserve deviation ratio (with time delay enforced). * @param newRatio New reserve deviation ratio. * @return `true` if success. */ function prepareNewReserveDeviation(uint256 newRatio) external onlyGovernance returns (bool) { require(newRatio <= (ScaledMath.DECIMAL_SCALE * 50) / 100, Error.INVALID_AMOUNT); return _prepare(_RESERVE_DEVIATION_KEY, newRatio); } /** * @notice Execute reserve deviation ratio update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New reserve deviation ratio. */ function executeNewReserveDeviation() external override returns (uint256) { uint256 reserveDeviation = _executeUInt256(_RESERVE_DEVIATION_KEY); _rebalanceVault(); return reserveDeviation; } /** * @notice Reset the prepared reserve deviation. * @return `true` if success. */ function resetNewReserveDeviation() external onlyGovernance returns (bool) { return _resetUInt256Config(_RESERVE_DEVIATION_KEY); } /** * @notice Prepare update of min withdrawal fee (with time delay enforced). * @param newFee New min withdrawal fee. * @return `true` if success. */ function prepareNewMinWithdrawalFee(uint256 newFee) external onlyGovernance returns (bool) { _checkFeeInvariants(newFee, getMaxWithdrawalFee()); return _prepare(_MIN_WITHDRAWAL_FEE_KEY, newFee); } /** * @notice Execute min withdrawal fee update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New withdrawal fee. */ function executeNewMinWithdrawalFee() external returns (uint256) { uint256 newFee = _executeUInt256(_MIN_WITHDRAWAL_FEE_KEY); _checkFeeInvariants(newFee, getMaxWithdrawalFee()); return newFee; } /** * @notice Reset the prepared min withdrawal fee * @return `true` if success. */ function resetNewMinWithdrawalFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_MIN_WITHDRAWAL_FEE_KEY); } /** * @notice Prepare update of max withdrawal fee (with time delay enforced). * @param newFee New max withdrawal fee. * @return `true` if success. */ function prepareNewMaxWithdrawalFee(uint256 newFee) external onlyGovernance returns (bool) { _checkFeeInvariants(getMinWithdrawalFee(), newFee); return _prepare(_MAX_WITHDRAWAL_FEE_KEY, newFee); } /** * @notice Execute max withdrawal fee update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New max withdrawal fee. */ function executeNewMaxWithdrawalFee() external override returns (uint256) { uint256 newFee = _executeUInt256(_MAX_WITHDRAWAL_FEE_KEY); _checkFeeInvariants(getMinWithdrawalFee(), newFee); return newFee; } /** * @notice Reset the prepared max fee. * @return `true` if success. */ function resetNewMaxWithdrawalFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_MAX_WITHDRAWAL_FEE_KEY); } /** * @notice Prepare update of withdrawal decrease fee period (with time delay enforced). * @param newPeriod New withdrawal fee decrease period. * @return `true` if success. */ function prepareNewWithdrawalFeeDecreasePeriod(uint256 newPeriod) external onlyGovernance returns (bool) { return _prepare(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY, newPeriod); } /** * @notice Execute withdrawal fee decrease period update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New withdrawal fee decrease period. */ function executeNewWithdrawalFeeDecreasePeriod() external returns (uint256) { return _executeUInt256(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY); } /** * @notice Reset the prepared withdrawal fee decrease period update. * @return `true` if success. */ function resetNewWithdrawalFeeDecreasePeriod() external onlyGovernance returns (bool) { return _resetUInt256Config(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY); } /** * @notice Set the staker vault for this pool's LP token * @dev Staker vault and LP token pairs are immutable and the staker vault can only be set once for a pool. * Only one vault exists per LP token. This information will be retrieved from the controller of the pool. * @return Address of the new staker vault for the pool. */ function setStaker() external override onlyRoles2(Roles.GOVERNANCE, Roles.POOL_FACTORY) returns (bool) { require(address(staker) == address(0), Error.ADDRESS_ALREADY_SET); address stakerVault = addressProvider.getStakerVault(address(lpToken)); require(stakerVault != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); staker = IStakerVault(stakerVault); _approveStakerVaultSpendingLpTokens(); emit StakerVaultSet(stakerVault); return true; } /** * @notice Prepare setting a new Vault (with time delay enforced). * @param _vault Address of new Vault contract. * @return `true` if success. */ function prepareNewVault(address _vault) external onlyGovernance returns (bool) { _prepare(_VAULT_KEY, _vault); return true; } /** * @notice Execute Vault update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return Address of new Vault contract. */ function executeNewVault() external override returns (address) { IVault vault = getVault(); if (address(vault) != address(0)) { vault.withdrawAll(); } address newVault = _executeAddress(_VAULT_KEY); addressProvider.updateVault(address(vault), newVault); return newVault; } /** * @notice Reset the vault deadline. * @return `true` if success. */ function resetNewVault() external onlyGovernance returns (bool) { return _resetAddressConfig(_VAULT_KEY); } /** * @notice Redeems the underlying asset by burning LP tokens. * @param redeemLpTokens Number of tokens to burn for redeeming the underlying. * @return Actual amount of the underlying redeemed. */ function redeem(uint256 redeemLpTokens) external override returns (uint256) { return redeem(redeemLpTokens, 0); } /** * @notice Uncap the pool to remove the deposit limit. * @return `true` if success. */ function uncap() external override onlyGovernance returns (bool) { require(isCapped(), Error.NOT_CAPPED); depositCap = 0; return true; } /** * @notice Update the deposit cap value. * @param _depositCap The maximum allowed deposits per address in the pool * @return `true` if success. */ function updateDepositCap(uint256 _depositCap) external override onlyGovernance returns (bool) { require(isCapped(), Error.NOT_CAPPED); require(depositCap != _depositCap, Error.SAME_AS_CURRENT); require(_depositCap > 0, Error.INVALID_AMOUNT); depositCap = _depositCap; return true; } /** * @notice Rebalance vault according to required underlying backing reserves. */ function rebalanceVault() external onlyGovernance { _rebalanceVault(); } /** * @notice Deposit funds for an address into liquidity pool and mint LP tokens in exchange. * @param account Account to deposit for. * @param depositAmount Amount of the underlying asset to supply. * @return Actual amount minted. */ function depositFor(address account, uint256 depositAmount) external payable override returns (uint256) { return depositFor(account, depositAmount, 0); } /** * @notice Redeems the underlying asset by burning LP tokens, unstaking any LP tokens needed. * @param redeemLpTokens Number of tokens to unstake and/or burn for redeeming the underlying. * @param minRedeemAmount Minimum amount of underlying that should be received. * @return Actual amount of the underlying redeemed. */ function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external override returns (uint256) { uint256 lpBalance_ = lpToken.balanceOf(msg.sender); require( lpBalance_ + staker.balanceOf(msg.sender) >= redeemLpTokens, Error.INSUFFICIENT_BALANCE ); if (lpBalance_ < redeemLpTokens) { staker.unstakeFor(msg.sender, msg.sender, redeemLpTokens - lpBalance_); } return redeem(redeemLpTokens, minRedeemAmount); } /** * @notice Returns the address of the LP token of this pool * @return The address of the LP token */ function getLpToken() external view override returns (address) { return address(lpToken); } /** * @notice Calculates the amount of LP tokens that need to be redeemed to get a certain amount of underlying (includes fees and exchange rate) * @param account Address of the account redeeming. * @param underlyingAmount The amount of underlying desired. * @return Amount of LP tokens that need to be redeemed. */ function calcRedeem(address account, uint256 underlyingAmount) external view override returns (uint256) { require(underlyingAmount > 0, Error.INVALID_AMOUNT); ILpToken lpToken_ = lpToken; require(lpToken_.balanceOf(account) > 0, Error.INSUFFICIENT_BALANCE); uint256 currentExchangeRate = exchangeRate(); uint256 withoutFeesLpAmount = underlyingAmount.scaledDiv(currentExchangeRate); if (withoutFeesLpAmount == lpToken_.totalSupply()) { return withoutFeesLpAmount; } WithdrawalFeeMeta memory meta = withdrawalFeeMetas[account]; uint256 currentFeeRatio = 0; if (!addressProvider.isAction(account)) { currentFeeRatio = getNewCurrentFees( meta.timeToWait, meta.lastActionTimestamp, meta.feeRatio ); } uint256 scalingFactor = currentExchangeRate.scaledMul((ScaledMath.ONE - currentFeeRatio)); uint256 neededLpTokens = underlyingAmount.scaledDivRoundUp(scalingFactor); return neededLpTokens; } function getUnderlying() external view virtual override returns (address); /** * @notice Deposit funds for an address into liquidity pool and mint LP tokens in exchange. * @param account Account to deposit for. * @param depositAmount Amount of the underlying asset to supply. * @param minTokenAmount Minimum amount of LP tokens that should be minted. * @return Actual amount minted. */ function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) public payable override notPaused returns (uint256) { uint256 rate = exchangeRate(); if (isCapped()) { uint256 lpBalance = lpToken.balanceOf(account); uint256 stakedAndLockedBalance = staker.stakedAndActionLockedBalanceOf(account); uint256 currentUnderlyingBalance = (lpBalance + stakedAndLockedBalance).scaledMul(rate); require( currentUnderlyingBalance + depositAmount <= depositCap, Error.EXCEEDS_DEPOSIT_CAP ); } _doTransferIn(msg.sender, depositAmount); uint256 mintedLp = depositAmount.scaledDiv(rate); require(mintedLp >= minTokenAmount, Error.INVALID_AMOUNT); lpToken.mint(account, mintedLp); _rebalanceVault(); if (msg.sender == account || address(this) == account) { emit Deposit(msg.sender, depositAmount, mintedLp); } else { emit DepositFor(msg.sender, account, depositAmount, mintedLp); } return mintedLp; } /** * @notice Redeems the underlying asset by burning LP tokens. * @param redeemLpTokens Number of tokens to burn for redeeming the underlying. * @param minRedeemAmount Minimum amount of underlying that should be received. * @return Actual amount of the underlying redeemed. */ function redeem(uint256 redeemLpTokens, uint256 minRedeemAmount) public override returns (uint256) { require(redeemLpTokens > 0, Error.INVALID_AMOUNT); ILpToken lpToken_ = lpToken; require(lpToken_.balanceOf(msg.sender) >= redeemLpTokens, Error.INSUFFICIENT_BALANCE); uint256 withdrawalFee = addressProvider.isAction(msg.sender) ? 0 : getWithdrawalFee(msg.sender, redeemLpTokens); uint256 redeemMinusFees = redeemLpTokens - withdrawalFee; // Pay no fees on the last withdrawal (avoid locking funds in the pool) if (redeemLpTokens == lpToken_.totalSupply()) { redeemMinusFees = redeemLpTokens; } uint256 redeemUnderlying = redeemMinusFees.scaledMul(exchangeRate()); require(redeemUnderlying >= minRedeemAmount, Error.NOT_ENOUGH_FUNDS_WITHDRAWN); _rebalanceVault(redeemUnderlying); lpToken_.burn(msg.sender, redeemLpTokens); _doTransferOut(payable(msg.sender), redeemUnderlying); emit Redeem(msg.sender, redeemUnderlying, redeemLpTokens); return redeemUnderlying; } /** * @return the current required reserves ratio */ function getRequiredReserveRatio() public view virtual returns (uint256) { return currentUInts256[_REQUIRED_RESERVES_KEY]; } /** * @return the current maximum reserve deviation ratio */ function getMaxReserveDeviationRatio() public view virtual returns (uint256) { return currentUInts256[_RESERVE_DEVIATION_KEY]; } /** * @notice Returns the current minimum withdrawal fee */ function getMinWithdrawalFee() public view returns (uint256) { return currentUInts256[_MIN_WITHDRAWAL_FEE_KEY]; } /** * @notice Returns the current maximum withdrawal fee */ function getMaxWithdrawalFee() public view returns (uint256) { return currentUInts256[_MAX_WITHDRAWAL_FEE_KEY]; } /** * @notice Returns the current withdrawal fee decrease period */ function getWithdrawalFeeDecreasePeriod() public view returns (uint256) { return currentUInts256[_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY]; } /** * @return the current vault of the liquidity pool */ function getVault() public view virtual override returns (IVault) { return IVault(currentAddresses[_VAULT_KEY]); } /** * @notice Compute current exchange rate of LP tokens to underlying scaled to 1e18. * @dev Exchange rate means: underlying = LP token * exchangeRate * @return Current exchange rate. */ function exchangeRate() public view override returns (uint256) { uint256 totalUnderlying_ = totalUnderlying(); uint256 totalSupply = lpToken.totalSupply(); if (totalSupply == 0 || totalUnderlying_ == 0) { return ScaledMath.ONE; } return totalUnderlying_.scaledDiv(totalSupply); } /** * @notice Compute total amount of underlying tokens for this pool. * @return Total amount of underlying in pool. */ function totalUnderlying() public view returns (uint256) { IVault vault = getVault(); uint256 balanceUnderlying = _getBalanceUnderlying(); if (address(vault) == address(0)) { return balanceUnderlying; } uint256 investedUnderlying = vault.getTotalUnderlying(); return investedUnderlying + balanceUnderlying; } /** * @notice Retuns if the pool has an active deposit limit * @return `true` if there is currently a deposit limit */ function isCapped() public view override returns (bool) { return depositCap != 0; } /** * @notice Returns the withdrawal fee for `account` * @param account Address to get the withdrawal fee for * @param amount Amount to calculate the withdrawal fee for * @return Withdrawal fee in LP tokens */ function getWithdrawalFee(address account, uint256 amount) public view override returns (uint256) { WithdrawalFeeMeta memory meta = withdrawalFeeMetas[account]; if (lpToken.balanceOf(account) == 0) { return 0; } uint256 currentFee = getNewCurrentFees( meta.timeToWait, meta.lastActionTimestamp, meta.feeRatio ); return amount.scaledMul(currentFee); } /** * @notice Calculates the withdrawal fee a user would currently need to pay on currentBalance. * @param timeToWait The total time to wait until the withdrawal fee reached the min. fee * @param lastActionTimestamp Timestamp of the last fee update * @param feeRatio Fees that would currently be paid on the user's entire balance * @return Updated fee amount on the currentBalance */ function getNewCurrentFees( uint256 timeToWait, uint256 lastActionTimestamp, uint256 feeRatio ) public view returns (uint256) { uint256 timeElapsed = _getTime() - lastActionTimestamp; uint256 minFeePercentage = getMinWithdrawalFee(); if (timeElapsed >= timeToWait) { return minFeePercentage; } uint256 elapsedShare = timeElapsed.scaledDiv(timeToWait); return feeRatio - (feeRatio - minFeePercentage).scaledMul(elapsedShare); } function _rebalanceVault() internal { _rebalanceVault(0); } function _initialize( string memory name_, uint256 depositCap_, address vault_ ) internal initializer returns (bool) { name = name_; depositCap = depositCap_; _setConfig(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY, _INITIAL_FEE_DECREASE_PERIOD); _setConfig(_MAX_WITHDRAWAL_FEE_KEY, _INITIAL_MAX_WITHDRAWAL_FEE); _setConfig(_REQUIRED_RESERVES_KEY, ScaledMath.ONE); _setConfig(_RESERVE_DEVIATION_KEY, _INITIAL_RESERVE_DEVIATION); _setConfig(_VAULT_KEY, vault_); return true; } function _approveStakerVaultSpendingLpTokens() internal { address staker_ = address(staker); address lpToken_ = address(lpToken); if (staker_ == address(0) || lpToken_ == address(0)) return; IERC20(lpToken_).safeApprove(staker_, type(uint256).max); } function _doTransferIn(address from, uint256 amount) internal virtual; function _doTransferOut(address payable to, uint256 amount) internal virtual; /** * @dev Rebalances the pool's allocations to the vault * @param underlyingToWithdraw Amount of underlying to withdraw such that after the withdrawal the pool and vault allocations are correctly balanced. */ function _rebalanceVault(uint256 underlyingToWithdraw) internal { IVault vault = getVault(); if (address(vault) == address(0)) return; uint256 lockedLp = staker.getStakedByActions(); uint256 totalUnderlyingStaked = lockedLp.scaledMul(exchangeRate()); uint256 underlyingBalance = _getBalanceUnderlying(true); uint256 maximumDeviation = totalUnderlyingStaked.scaledMul(getMaxReserveDeviationRatio()); uint256 nextTargetBalance = totalUnderlyingStaked.scaledMul(getRequiredReserveRatio()); if ( underlyingToWithdraw > underlyingBalance || (underlyingBalance - underlyingToWithdraw) + maximumDeviation < nextTargetBalance ) { uint256 requiredDeposits = nextTargetBalance + underlyingToWithdraw - underlyingBalance; vault.withdraw(requiredDeposits); } else { uint256 nextBalance = underlyingBalance - underlyingToWithdraw; if (nextBalance > nextTargetBalance + maximumDeviation) { uint256 excessDeposits = nextBalance - nextTargetBalance; _doTransferOut(payable(address(vault)), excessDeposits); vault.deposit(); } } } function _updateUserFeesOnDeposit( address account, address from, uint256 amountAdded ) internal { WithdrawalFeeMeta storage meta = withdrawalFeeMetas[account]; uint256 balance = lpToken.balanceOf(account) + staker.stakedAndActionLockedBalanceOf(account); uint256 newCurrentFeeRatio = getNewCurrentFees( meta.timeToWait, meta.lastActionTimestamp, meta.feeRatio ); uint256 shareAdded = amountAdded.scaledDiv(amountAdded + balance); uint256 shareExisting = ScaledMath.ONE - shareAdded; uint256 feeOnDeposit; if (from == address(0)) { feeOnDeposit = getMaxWithdrawalFee(); } else { WithdrawalFeeMeta storage fromMeta = withdrawalFeeMetas[from]; feeOnDeposit = getNewCurrentFees( fromMeta.timeToWait, fromMeta.lastActionTimestamp, fromMeta.feeRatio ); } uint256 newFeeRatio = shareExisting.scaledMul(newCurrentFeeRatio) + shareAdded.scaledMul(feeOnDeposit); meta.feeRatio = uint64(newFeeRatio); meta.timeToWait = uint64(getWithdrawalFeeDecreasePeriod()); meta.lastActionTimestamp = uint64(_getTime()); } function _getBalanceUnderlying() internal view virtual returns (uint256); function _getBalanceUnderlying(bool transferInDone) internal view virtual returns (uint256); function _isAuthorizedToPause(address account) internal view override returns (bool) { return _roleManager().hasRole(Roles.GOVERNANCE, account); } /** * @dev Overriden for testing */ function _getTime() internal view virtual returns (uint256) { return block.timestamp; } function _checkFeeInvariants(uint256 minFee, uint256 maxFee) internal pure { require(maxFee >= minFee, Error.INVALID_AMOUNT); require(maxFee <= _MAX_WITHDRAWAL_FEE, Error.INVALID_AMOUNT); } } // File interfaces/pool/IErc20Pool.sol pragma solidity 0.8.9; interface IErc20Pool { function initialize( string memory name_, address underlying_, uint256 depositCap_, address vault_ ) external returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // File contracts/pool/Erc20Pool.sol pragma solidity 0.8.9; contract Erc20Pool is LiquidityPool, IErc20Pool { using SafeERC20 for IERC20; address private _underlying; constructor(IController _controller) LiquidityPool(_controller) {} function initialize( string memory name_, address underlying_, uint256 depositCap_, address vault_ ) public override returns (bool) { require(underlying_ != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); _underlying = underlying_; return _initialize(name_, depositCap_, vault_); } function getUnderlying() public view override returns (address) { return _underlying; } function _doTransferIn(address from, uint256 amount) internal override { require(msg.value == 0, Error.INVALID_VALUE); IERC20(_underlying).safeTransferFrom(from, address(this), amount); } function _doTransferOut(address payable to, uint256 amount) internal override { IERC20(_underlying).safeTransfer(to, amount); } function _getBalanceUnderlying() internal view override returns (uint256) { return IERC20(_underlying).balanceOf(address(this)); } function _getBalanceUnderlying(bool) internal view override returns (uint256) { return _getBalanceUnderlying(); } }
Pause the contract. return `true` if success./
function pause() external onlyAuthorizedToPause returns (bool) { isPaused = true; return true; }
10,436,053
./partial_match/4/0x6DA78f115dC013357Da953eB8b4cAba45ef777cC/sources/ATMSettings.sol
Returns the addition of two unsigned integers, reverting on overflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow./
@notice This interface defines the function to validate the interest to withdraw by lenders. @author [email protected] } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
8,543,916
./partial_match/1/0xa926231BE5a5364D50FBB18507DfD43Cb2eFFEB7/sources/TaxToken.sol
lpToken = factory.createPair(msg.sender, router.WETH()); emit CreatedLPToken(msg.sender, router.WETH(), lpToken); Camelot V2 fails upon LP creation during the constructor return zaero address to be updated after creation.
function createLPToken() external returns(address lpToken) { return address(0); }
4,151,936
./full_match/1/0x068d23dbc3A6Bddc0916205e15d841C6fD9B0fCB/sources/contracts/DoughV1Index.sol
========== VIEWS ========== /
function getDoughV1Dsa(address _owner) external view returns (address) { return _DoughV1DsaList[_owner]; }
3,211,132
/* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../abstract/MasterAware.sol"; import "../../interfaces/IPool.sol"; import "../cover/Quotation.sol"; import "../oracles/PriceFeedOracle.sol"; import "../token/NXMToken.sol"; import "../token/TokenController.sol"; import "./MCR.sol"; contract Pool is IPool, MasterAware, ReentrancyGuard { using Address for address; using SafeMath for uint; using SafeERC20 for IERC20; struct AssetData { uint112 minAmount; uint112 maxAmount; uint32 lastSwapTime; // 18 decimals of precision. 0.01% -> 0.0001 -> 1e14 uint maxSlippageRatio; } /* storage */ address[] public assets; mapping(address => AssetData) public assetData; // contracts Quotation public quotation; NXMToken public nxmToken; TokenController public tokenController; MCR public mcr; // parameters address public swapController; uint public minPoolEth; PriceFeedOracle public priceFeedOracle; address public swapOperator; /* constants */ address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant MCR_RATIO_DECIMALS = 4; uint public constant MAX_MCR_RATIO = 40000; // 400% uint public constant MAX_BUY_SELL_MCR_ETH_FRACTION = 500; // 5%. 4 decimal points uint internal constant CONSTANT_C = 5800000; uint internal constant CONSTANT_A = 1028 * 1e13; uint internal constant TOKEN_EXPONENT = 4; /* events */ event Payout(address indexed to, address indexed asset, uint amount); event NXMSold (address indexed member, uint nxmIn, uint ethOut); event NXMBought (address indexed member, uint ethIn, uint nxmOut); event Swapped(address indexed fromAsset, address indexed toAsset, uint amountIn, uint amountOut); /* logic */ modifier onlySwapOperator { require(msg.sender == swapOperator, "Pool: not swapOperator"); _; } constructor ( address[] memory _assets, uint112[] memory _minAmounts, uint112[] memory _maxAmounts, uint[] memory _maxSlippageRatios, address _master, address _priceOracle, address _swapOperator ) public { require(_assets.length == _minAmounts.length, "Pool: length mismatch"); require(_assets.length == _maxAmounts.length, "Pool: length mismatch"); require(_assets.length == _maxSlippageRatios.length, "Pool: length mismatch"); for (uint i = 0; i < _assets.length; i++) { address asset = _assets[i]; require(asset != address(0), "Pool: asset is zero address"); require(_maxAmounts[i] >= _minAmounts[i], "Pool: max < min"); require(_maxSlippageRatios[i] <= 1 ether, "Pool: max < min"); assets.push(asset); assetData[asset].minAmount = _minAmounts[i]; assetData[asset].maxAmount = _maxAmounts[i]; assetData[asset].maxSlippageRatio = _maxSlippageRatios[i]; } master = INXMMaster(_master); priceFeedOracle = PriceFeedOracle(_priceOracle); swapOperator = _swapOperator; } // fallback function function() external payable {} // for legacy Pool1 upgrade compatibility function sendEther() external payable {} /** * @dev Calculates total value of all pool assets in ether */ function getPoolValueInEth() public view returns (uint) { uint total = address(this).balance; for (uint i = 0; i < assets.length; i++) { address assetAddress = assets[i]; IERC20 token = IERC20(assetAddress); uint rate = priceFeedOracle.getAssetToEthRate(assetAddress); require(rate > 0, "Pool: zero rate"); uint assetBalance = token.balanceOf(address(this)); uint assetValue = assetBalance.mul(rate).div(1e18); total = total.add(assetValue); } return total; } /* asset related functions */ function getAssets() external view returns (address[] memory) { return assets; } function getAssetDetails(address _asset) external view returns ( uint112 min, uint112 max, uint32 lastAssetSwapTime, uint maxSlippageRatio ) { AssetData memory data = assetData[_asset]; return (data.minAmount, data.maxAmount, data.lastSwapTime, data.maxSlippageRatio); } function addAsset( address _asset, uint112 _min, uint112 _max, uint _maxSlippageRatio ) external onlyGovernance { require(_asset != address(0), "Pool: asset is zero address"); require(_max >= _min, "Pool: max < min"); require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1"); for (uint i = 0; i < assets.length; i++) { require(_asset != assets[i], "Pool: asset exists"); } assets.push(_asset); assetData[_asset] = AssetData(_min, _max, 0, _maxSlippageRatio); } function removeAsset(address _asset) external onlyGovernance { for (uint i = 0; i < assets.length; i++) { if (_asset != assets[i]) { continue; } delete assetData[_asset]; assets[i] = assets[assets.length - 1]; assets.pop(); return; } revert("Pool: asset not found"); } function setAssetDetails( address _asset, uint112 _min, uint112 _max, uint _maxSlippageRatio ) external onlyGovernance { require(_min <= _max, "Pool: min > max"); require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1"); for (uint i = 0; i < assets.length; i++) { if (_asset != assets[i]) { continue; } assetData[_asset].minAmount = _min; assetData[_asset].maxAmount = _max; assetData[_asset].maxSlippageRatio = _maxSlippageRatio; return; } revert("Pool: asset not found"); } /* claim related functions */ /** * @dev Execute the payout in case a claim is accepted * @param asset token address or 0xEee...EEeE for ether * @param payoutAddress send funds to this address * @param amount amount to send */ function sendClaimPayout ( address asset, address payable payoutAddress, uint amount ) external onlyInternal nonReentrant returns (bool success) { bool ok; if (asset == ETH) { // solhint-disable-next-line avoid-low-level-calls (ok, /* data */) = payoutAddress.call.value(amount)(""); } else { ok = _safeTokenTransfer(asset, payoutAddress, amount); } if (ok) { emit Payout(payoutAddress, asset, amount); } return ok; } /** * @dev safeTransfer implementation that does not revert * @param tokenAddress ERC20 address * @param to destination * @param value amount to send * @return success true if the transfer was successfull */ function _safeTokenTransfer ( address tokenAddress, address to, uint256 value ) internal returns (bool) { // token address is not a contract if (!tokenAddress.isContract()) { return false; } IERC20 token = IERC20(tokenAddress); bytes memory data = abi.encodeWithSelector(token.transfer.selector, to, value); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = tokenAddress.call(data); // low-level call failed/reverted if (!success) { return false; } // tokens that don't have return data if (returndata.length == 0) { return true; } // tokens that have return data will return a bool return abi.decode(returndata, (bool)); } /* pool lifecycle functions */ function transferAsset( address asset, address payable destination, uint amount ) external onlyGovernance nonReentrant { require(assetData[asset].maxAmount == 0, "Pool: max not zero"); require(destination != address(0), "Pool: dest zero"); IERC20 token = IERC20(asset); uint balance = token.balanceOf(address(this)); uint transferableAmount = amount > balance ? balance : amount; token.safeTransfer(destination, transferableAmount); } function upgradeCapitalPool(address payable newPoolAddress) external onlyMaster nonReentrant { // transfer ether uint ethBalance = address(this).balance; (bool ok, /* data */) = newPoolAddress.call.value(ethBalance)(""); require(ok, "Pool: transfer failed"); // transfer assets for (uint i = 0; i < assets.length; i++) { IERC20 token = IERC20(assets[i]); uint tokenBalance = token.balanceOf(address(this)); token.safeTransfer(newPoolAddress, tokenBalance); } } /** * @dev Update dependent contract address * @dev Implements MasterAware interface function */ function changeDependentContractAddress() public { nxmToken = NXMToken(master.tokenAddress()); tokenController = TokenController(master.getLatestAddress("TC")); quotation = Quotation(master.getLatestAddress("QT")); mcr = MCR(master.getLatestAddress("MC")); } /* cover purchase functions */ /// @dev Enables user to purchase cover with funding in ETH. /// @param smartCAdd Smart Contract Address function makeCoverBegin( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public payable onlyMember whenNotPaused { require(coverCurr == "ETH", "Pool: Unexpected asset type"); require(msg.value == coverDetails[1], "Pool: ETH amount does not match premium"); quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Enables user to purchase cover via currency asset eg DAI */ function makeCoverUsingCA( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyMember whenNotPaused { require(coverCurr != "ETH", "Pool: Unexpected asset type"); quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } function transferAssetFrom (address asset, address from, uint amount) public onlyInternal whenNotPaused { IERC20 token = IERC20(asset); token.safeTransferFrom(from, address(this), amount); } function transferAssetToSwapOperator (address asset, uint amount) public onlySwapOperator nonReentrant whenNotPaused { if (asset == ETH) { (bool ok, /* data */) = swapOperator.call.value(amount)(""); require(ok, "Pool: Eth transfer failed"); return; } IERC20 token = IERC20(asset); token.safeTransfer(swapOperator, amount); } function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) public onlySwapOperator whenNotPaused { assetData[asset].lastSwapTime = lastSwapTime; } /* token sale functions */ /** * @dev (DEPRECATED, use sellTokens function instead) Allows selling of NXM for ether. * Seller first needs to give this contract allowance to * transfer/burn tokens in the NXMToken contract * @param _amount Amount of NXM to sell * @return success returns true on successfull sale */ function sellNXMTokens(uint _amount) public onlyMember whenNotPaused returns (bool success) { sellNXM(_amount, 0); return true; } /** * @dev (DEPRECATED, use calculateNXMForEth function instead) Returns the amount of wei a seller will get for selling NXM * @param amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function getWei(uint amount) external view returns (uint weiToPay) { return getEthForNXM(amount); } /** * @dev Buys NXM tokens with ETH. * @param minTokensOut Minimum amount of tokens to be bought. Revert if boughtTokens falls below this number. * @return boughtTokens number of bought tokens. */ function buyNXM(uint minTokensOut) public payable onlyMember whenNotPaused { uint ethIn = msg.value; require(ethIn > 0, "Pool: ethIn > 0"); uint totalAssetValue = getPoolValueInEth().sub(ethIn); uint mcrEth = mcr.getMCR(); uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth); require(mcrRatio <= MAX_MCR_RATIO, "Pool: Cannot purchase if MCR% > 400%"); uint tokensOut = calculateNXMForEth(ethIn, totalAssetValue, mcrEth); require(tokensOut >= minTokensOut, "Pool: tokensOut is less than minTokensOut"); tokenController.mint(msg.sender, tokensOut); // evaluate the new MCR for the current asset value including the ETH paid in mcr.updateMCRInternal(totalAssetValue.add(ethIn), false); emit NXMBought(msg.sender, ethIn, tokensOut); } /** * @dev Sell NXM tokens and receive ETH. * @param tokenAmount Amount of tokens to sell. * @param minEthOut Minimum amount of ETH to be received. Revert if ethOut falls below this number. * @return ethOut amount of ETH received in exchange for the tokens. */ function sellNXM(uint tokenAmount, uint minEthOut) public onlyMember nonReentrant whenNotPaused { require(nxmToken.balanceOf(msg.sender) >= tokenAmount, "Pool: Not enough balance"); require(nxmToken.isLockedForMV(msg.sender) <= now, "Pool: NXM tokens are locked for voting"); uint currentTotalAssetValue = getPoolValueInEth(); uint mcrEth = mcr.getMCR(); uint ethOut = calculateEthForNXM(tokenAmount, currentTotalAssetValue, mcrEth); require(currentTotalAssetValue.sub(ethOut) >= mcrEth, "Pool: MCR% cannot fall below 100%"); require(ethOut >= minEthOut, "Pool: ethOut < minEthOut"); tokenController.burnFrom(msg.sender, tokenAmount); (bool ok, /* data */) = msg.sender.call.value(ethOut)(""); require(ok, "Pool: Sell transfer failed"); // evaluate the new MCR for the current asset value excluding the paid out ETH mcr.updateMCRInternal(currentTotalAssetValue.sub(ethOut), false); emit NXMSold(msg.sender, tokenAmount, ethOut); } /** * @dev Get value in tokens for an ethAmount purchase. * @param ethAmount amount of ETH used for buying. * @return tokenValue tokens obtained by buying worth of ethAmount */ function getNXMForEth( uint ethAmount ) public view returns (uint) { uint totalAssetValue = getPoolValueInEth(); uint mcrEth = mcr.getMCR(); return calculateNXMForEth(ethAmount, totalAssetValue, mcrEth); } function calculateNXMForEth( uint ethAmount, uint currentTotalAssetValue, uint mcrEth ) public pure returns (uint) { require( ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS), "Pool: Purchases worth higher than 5% of MCReth are not allowed" ); /* The price formula is: P(V) = A + MCReth / C * MCR% ^ 4 where MCR% = V / MCReth P(V) = A + 1 / (C * MCReth ^ 3) * V ^ 4 To compute the number of tokens issued we can integrate with respect to V the following: ΔT = ΔV / P(V) which assumes that for an infinitesimally small change in locked value V price is constant and we get an infinitesimally change in token supply ΔT. This is not computable on-chain, below we use an approximation that works well assuming * MCR% stays within [100%, 400%] * ethAmount <= 5% * MCReth Use a simplified formula excluding the constant A price offset to compute the amount of tokens to be minted. AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4 AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4 For a very small variation in tokens ΔT, we have, ΔT = ΔV / P(V), to get total T we integrate with respect to V. adjustedTokenAmount = ∫ (dV / AdjustedP(V)) from V0 (currentTotalAssetValue) to V1 (nextTotalAssetValue) adjustedTokenAmount = ∫ ((C * MCReth ^ 3) / V ^ 4 * dV) from V0 to V1 Evaluating the above using the antiderivative of the function we get: adjustedTokenAmount = - MCReth ^ 3 * C / (3 * V1 ^3) + MCReth * C /(3 * V0 ^ 3) */ if (currentTotalAssetValue == 0 || mcrEth.div(currentTotalAssetValue) > 1e12) { /* If the currentTotalAssetValue = 0, adjustedTokenPrice approaches 0. Therefore we can assume the price is A. If currentTotalAssetValue is far smaller than mcrEth, MCR% approaches 0, let the price be A (baseline price). This avoids overflow in the calculateIntegralAtPoint computation. This approximation is safe from arbitrage since at MCR% < 100% no sells are possible. */ uint tokenPrice = CONSTANT_A; return ethAmount.mul(1e18).div(tokenPrice); } // MCReth * C /(3 * V0 ^ 3) uint point0 = calculateIntegralAtPoint(currentTotalAssetValue, mcrEth); // MCReth * C / (3 * V1 ^3) uint nextTotalAssetValue = currentTotalAssetValue.add(ethAmount); uint point1 = calculateIntegralAtPoint(nextTotalAssetValue, mcrEth); uint adjustedTokenAmount = point0.sub(point1); /* Compute a preliminary adjustedTokenPrice for the minted tokens based on the adjustedTokenAmount above, and to that add the A constant (the price offset previously removed in the adjusted Price formula) to obtain the finalPrice and ultimately the tokenValue based on the finalPrice. adjustedPrice = ethAmount / adjustedTokenAmount finalPrice = adjustedPrice + A tokenValue = ethAmount / finalPrice */ // ethAmount is multiplied by 1e18 to cancel out the multiplication factor of 1e18 of the adjustedTokenAmount uint adjustedTokenPrice = ethAmount.mul(1e18).div(adjustedTokenAmount); uint tokenPrice = adjustedTokenPrice.add(CONSTANT_A); return ethAmount.mul(1e18).div(tokenPrice); } /** * @dev integral(V) = MCReth ^ 3 * C / (3 * V ^ 3) * 1e18 * computation result is multiplied by 1e18 to allow for a precision of 18 decimals. * NOTE: omits the minus sign of the correct integral to use a uint result type for simplicity * WARNING: this low-level function should be called from a contract which checks that * mcrEth / assetValue < 1e17 (no overflow) and assetValue != 0 */ function calculateIntegralAtPoint( uint assetValue, uint mcrEth ) internal pure returns (uint) { return CONSTANT_C .mul(1e18) .div(3) .mul(mcrEth).div(assetValue) .mul(mcrEth).div(assetValue) .mul(mcrEth).div(assetValue); } function getEthForNXM(uint nxmAmount) public view returns (uint ethAmount) { uint currentTotalAssetValue = getPoolValueInEth(); uint mcrEth = mcr.getMCR(); return calculateEthForNXM(nxmAmount, currentTotalAssetValue, mcrEth); } /** * @dev Computes token sell value for a tokenAmount in ETH with a sell spread of 2.5%. * for values in ETH of the sale <= 1% * MCReth the sell spread is very close to the exact value of 2.5%. * for values higher than that sell spread may exceed 2.5% * (The higher amount being sold at any given time the higher the spread) */ function calculateEthForNXM( uint nxmAmount, uint currentTotalAssetValue, uint mcrEth ) public pure returns (uint) { // Step 1. Calculate spot price at current values and amount of ETH if tokens are sold at that price uint spotPrice0 = calculateTokenSpotPrice(currentTotalAssetValue, mcrEth); uint spotEthAmount = nxmAmount.mul(spotPrice0).div(1e18); // Step 2. Calculate spot price using V = currentTotalAssetValue - spotEthAmount from step 1 uint totalValuePostSpotPriceSell = currentTotalAssetValue.sub(spotEthAmount); uint spotPrice1 = calculateTokenSpotPrice(totalValuePostSpotPriceSell, mcrEth); // Step 3. Min [average[Price(0), Price(1)] x ( 1 - Sell Spread), Price(1) ] // Sell Spread = 2.5% uint averagePriceWithSpread = spotPrice0.add(spotPrice1).div(2).mul(975).div(1000); uint finalPrice = averagePriceWithSpread < spotPrice1 ? averagePriceWithSpread : spotPrice1; uint ethAmount = finalPrice.mul(nxmAmount).div(1e18); require( ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS), "Pool: Sales worth more than 5% of MCReth are not allowed" ); return ethAmount; } function calculateMCRRatio(uint totalAssetValue, uint mcrEth) public pure returns (uint) { return totalAssetValue.mul(10 ** MCR_RATIO_DECIMALS).div(mcrEth); } /** * @dev Calculates token price in ETH 1 NXM token. TokenPrice = A + (MCReth / C) * MCR%^4 */ function calculateTokenSpotPrice(uint totalAssetValue, uint mcrEth) public pure returns (uint tokenPrice) { uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth); uint precisionDecimals = 10 ** TOKEN_EXPONENT.mul(MCR_RATIO_DECIMALS); return mcrEth .mul(mcrRatio ** TOKEN_EXPONENT) .div(CONSTANT_C) .div(precisionDecimals) .add(CONSTANT_A); } /** * @dev Returns the NXM price in a given asset * @param asset Asset name. */ function getTokenPrice(address asset) public view returns (uint tokenPrice) { uint totalAssetValue = getPoolValueInEth(); uint mcrEth = mcr.getMCR(); uint tokenSpotPriceEth = calculateTokenSpotPrice(totalAssetValue, mcrEth); return priceFeedOracle.getAssetForEth(asset, tokenSpotPriceEth); } function getMCRRatio() public view returns (uint) { uint totalAssetValue = getPoolValueInEth(); uint mcrEth = mcr.getMCR(); return calculateMCRRatio(totalAssetValue, mcrEth); } function updateUintParameters(bytes8 code, uint value) external onlyGovernance { if (code == "MIN_ETH") { minPoolEth = value; return; } revert("Pool: unknown parameter"); } function updateAddressParameters(bytes8 code, address value) external onlyGovernance { if (code == "SWP_OP") { swapOperator = value; return; } if (code == "PRC_FEED") { priceFeedOracle = PriceFeedOracle(value); return; } revert("Pool: unknown parameter"); } } 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; } } 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); } pragma solidity ^0.5.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 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"); } } } pragma solidity ^0.5.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } 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"); } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "./INXMMaster.sol"; contract MasterAware { INXMMaster public master; modifier onlyMember { require(master.isMember(msg.sender), "Caller is not a member"); _; } modifier onlyInternal { require(master.isInternal(msg.sender), "Caller is not an internal contract"); _; } modifier onlyMaster { if (address(master) != address(0)) { require(address(master) == msg.sender, "Not master"); } _; } modifier onlyGovernance { require( master.checkIsAuthToGoverned(msg.sender), "Caller is not authorized to govern" ); _; } modifier whenPaused { require(master.isPause(), "System is not paused"); _; } modifier whenNotPaused { require(!master.isPause(), "System is paused"); _; } function changeDependentContractAddress() external; function changeMasterAddress(address masterAddress) public onlyMaster { master = INXMMaster(masterAddress); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IPool { function transferAssetToSwapOperator(address asset, uint amount) external; function getAssetDetails(address _asset) external view returns ( uint112 min, uint112 max, uint32 lastAssetSwapTime, uint maxSlippageRatio ); function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) external; function minPoolEth() external returns (uint); } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../../abstract/MasterAware.sol"; import "../capital/Pool.sol"; import "../claims/ClaimsReward.sol"; import "../claims/Incidents.sol"; import "../token/TokenController.sol"; import "../token/TokenData.sol"; import "./QuotationData.sol"; contract Quotation is MasterAware, ReentrancyGuard { using SafeMath for uint; ClaimsReward public cr; Pool public pool; IPooledStaking public pooledStaking; QuotationData public qd; TokenController public tc; TokenData public td; Incidents public incidents; /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { cr = ClaimsReward(master.getLatestAddress("CR")); pool = Pool(master.getLatestAddress("P1")); pooledStaking = IPooledStaking(master.getLatestAddress("PS")); qd = QuotationData(master.getLatestAddress("QD")); tc = TokenController(master.getLatestAddress("TC")); td = TokenData(master.getLatestAddress("TD")); incidents = Incidents(master.getLatestAddress("IC")); } // solhint-disable-next-line no-empty-blocks function sendEther() public payable {} /** * @dev Expires a cover after a set period of time and changes the status of the cover * @dev Reduces the total and contract sum assured * @param coverId Cover Id. */ function expireCover(uint coverId) external { uint expirationDate = qd.getValidityOfCover(coverId); require(expirationDate < now, "Quotation: cover is not due to expire"); uint coverStatus = qd.getCoverStatusNo(coverId); require(coverStatus != uint(QuotationData.CoverStatus.CoverExpired), "Quotation: cover already expired"); (/* claim count */, bool hasOpenClaim, /* accepted */) = tc.coverInfo(coverId); require(!hasOpenClaim, "Quotation: cover has an open claim"); if (coverStatus != uint(QuotationData.CoverStatus.ClaimAccepted)) { (,, address contractAddress, bytes4 currency, uint amount,) = qd.getCoverDetailsByCoverID1(coverId); qd.subFromTotalSumAssured(currency, amount); qd.subFromTotalSumAssuredSC(contractAddress, currency, amount); } qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.CoverExpired)); } function withdrawCoverNote(address coverOwner, uint[] calldata coverIds, uint[] calldata reasonIndexes) external { uint gracePeriod = tc.claimSubmissionGracePeriod(); for (uint i = 0; i < coverIds.length; i++) { uint expirationDate = qd.getValidityOfCover(coverIds[i]); require(expirationDate.add(gracePeriod) < now, "Quotation: cannot withdraw before grace period expiration"); } tc.withdrawCoverNote(coverOwner, coverIds, reasonIndexes); } function getWithdrawableCoverNoteCoverIds( address coverOwner ) public view returns ( uint[] memory expiredCoverIds, bytes32[] memory lockReasons ) { uint[] memory coverIds = qd.getAllCoversOfUser(coverOwner); uint[] memory expiredIdsQueue = new uint[](coverIds.length); uint gracePeriod = tc.claimSubmissionGracePeriod(); uint expiredQueueLength = 0; for (uint i = 0; i < coverIds.length; i++) { uint coverExpirationDate = qd.getValidityOfCover(coverIds[i]); uint gracePeriodExpirationDate = coverExpirationDate.add(gracePeriod); (/* claimCount */, bool hasOpenClaim, /* hasAcceptedClaim */) = tc.coverInfo(coverIds[i]); if (!hasOpenClaim && gracePeriodExpirationDate < now) { expiredIdsQueue[expiredQueueLength] = coverIds[i]; expiredQueueLength++; } } expiredCoverIds = new uint[](expiredQueueLength); lockReasons = new bytes32[](expiredQueueLength); for (uint i = 0; i < expiredQueueLength; i++) { expiredCoverIds[i] = expiredIdsQueue[i]; lockReasons[i] = keccak256(abi.encodePacked("CN", coverOwner, expiredIdsQueue[i])); } } function getWithdrawableCoverNotesAmount(address coverOwner) external view returns (uint) { uint withdrawableAmount; bytes32[] memory lockReasons; (/*expiredCoverIds*/, lockReasons) = getWithdrawableCoverNoteCoverIds(coverOwner); for (uint i = 0; i < lockReasons.length; i++) { uint coverNoteAmount = tc.tokensLocked(coverOwner, lockReasons[i]); withdrawableAmount = withdrawableAmount.add(coverNoteAmount); } return withdrawableAmount; } /** * @dev Makes Cover funded via NXM tokens. * @param smartCAdd Smart Contract Address */ function makeCoverUsingNXMTokens( uint[] calldata coverDetails, uint16 coverPeriod, bytes4 coverCurr, address smartCAdd, uint8 _v, bytes32 _r, bytes32 _s ) external onlyMember whenNotPaused { tc.burnFrom(msg.sender, coverDetails[2]); // needs allowance _verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s, true); } /** * @dev Verifies cover details signed off chain. * @param from address of funder. * @param scAddress Smart Contract Address */ function verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyInternal { _verifyCoverDetails( from, scAddress, coverCurr, coverDetails, coverPeriod, _v, _r, _s, false ); } /** * @dev Verifies signature. * @param coverDetails details related to cover. * @param coverPeriod validity of cover. * @param contractAddress smart contract address. * @param _v argument from vrs hash. * @param _r argument from vrs hash. * @param _s argument from vrs hash. */ function verifySignature( uint[] memory coverDetails, uint16 coverPeriod, bytes4 currency, address contractAddress, uint8 _v, bytes32 _r, bytes32 _s ) public view returns (bool) { require(contractAddress != address(0)); bytes32 hash = getOrderHash(coverDetails, coverPeriod, currency, contractAddress); return isValidSignature(hash, _v, _r, _s); } /** * @dev Gets order hash for given cover details. * @param coverDetails details realted to cover. * @param coverPeriod validity of cover. * @param contractAddress smart contract address. */ function getOrderHash( uint[] memory coverDetails, uint16 coverPeriod, bytes4 currency, address contractAddress ) public view returns (bytes32) { return keccak256( abi.encodePacked( coverDetails[0], currency, coverPeriod, contractAddress, coverDetails[1], coverDetails[2], coverDetails[3], coverDetails[4], address(this) ) ); } /** * @dev Verifies signature. * @param hash order hash * @param v argument from vrs hash. * @param r argument from vrs hash. * @param s argument from vrs hash. */ function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns (bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == qd.getAuthQuoteEngine()); } /** * @dev Creates cover of the quotation, changes the status of the quotation , * updates the total sum assured and locks the tokens of the cover against a quote. * @param from Quote member Ethereum address. */ function _makeCover(//solhint-disable-line address payable from, address contractAddress, bytes4 coverCurrency, uint[] memory coverDetails, uint16 coverPeriod ) internal { address underlyingToken = incidents.underlyingToken(contractAddress); if (underlyingToken != address(0)) { address coverAsset = cr.getCurrencyAssetAddress(coverCurrency); require(coverAsset == underlyingToken, "Quotation: Unsupported cover asset for this product"); } uint cid = qd.getCoverLength(); qd.addCover( coverPeriod, coverDetails[0], from, coverCurrency, contractAddress, coverDetails[1], coverDetails[2] ); uint coverNoteAmount = coverDetails[2].mul(qd.tokensRetained()).div(100); if (underlyingToken == address(0)) { uint gracePeriod = tc.claimSubmissionGracePeriod(); uint claimSubmissionPeriod = uint(coverPeriod).mul(1 days).add(gracePeriod); bytes32 reason = keccak256(abi.encodePacked("CN", from, cid)); // mint and lock cover note td.setDepositCNAmount(cid, coverNoteAmount); tc.mintCoverNote(from, reason, coverNoteAmount, claimSubmissionPeriod); } else { // minted directly to member's wallet tc.mint(from, coverNoteAmount); } qd.addInTotalSumAssured(coverCurrency, coverDetails[0]); qd.addInTotalSumAssuredSC(contractAddress, coverCurrency, coverDetails[0]); uint coverPremiumInNXM = coverDetails[2]; uint stakersRewardPercentage = td.stakerCommissionPer(); uint rewardValue = coverPremiumInNXM.mul(stakersRewardPercentage).div(100); pooledStaking.accumulateReward(contractAddress, rewardValue); } /** * @dev Makes a cover. * @param from address of funder. * @param scAddress Smart Contract Address */ function _verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s, bool isNXM ) internal { require(coverDetails[3] > now, "Quotation: Quote has expired"); require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds"); require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used"); qd.setTimestampRepeated(coverDetails[4]); address asset = cr.getCurrencyAssetAddress(coverCurr); if (coverCurr != "ETH" && !isNXM) { pool.transferAssetFrom(asset, from, coverDetails[1]); } require(verifySignature(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s), "Quotation: signature mismatch"); _makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod); } function createCover( address payable from, address scAddress, bytes4 currency, uint[] calldata coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) external onlyInternal { require(coverDetails[3] > now, "Quotation: Quote has expired"); require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds"); require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used"); qd.setTimestampRepeated(coverDetails[4]); require(verifySignature(coverDetails, coverPeriod, currency, scAddress, _v, _r, _s), "Quotation: signature mismatch"); _makeCover(from, scAddress, currency, coverDetails, coverPeriod); } // referenced in master, keeping for now // solhint-disable-next-line no-empty-blocks function transferAssetsToNewContract(address) external pure {} function freeUpHeldCovers() external nonReentrant { IERC20 dai = IERC20(cr.getCurrencyAssetAddress("DAI")); uint membershipFee = td.joiningFee(); uint lastCoverId = 106; for (uint id = 1; id <= lastCoverId; id++) { if (qd.holdedCoverIDStatus(id) != uint(QuotationData.HCIDStatus.kycPending)) { continue; } (/*id*/, /*sc*/, bytes4 currency, /*period*/) = qd.getHoldedCoverDetailsByID1(id); (/*id*/, address payable userAddress, uint[] memory coverDetails) = qd.getHoldedCoverDetailsByID2(id); uint refundedETH = membershipFee; uint coverPremium = coverDetails[1]; if (qd.refundEligible(userAddress)) { qd.setRefundEligible(userAddress, false); } qd.setHoldedCoverIDStatus(id, uint(QuotationData.HCIDStatus.kycFailedOrRefunded)); if (currency == "ETH") { refundedETH = refundedETH.add(coverPremium); } else { require(dai.transfer(userAddress, coverPremium), "Quotation: DAI refund transfer failed"); } userAddress.transfer(refundedETH); } } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; interface Aggregator { function latestAnswer() external view returns (int); } contract PriceFeedOracle { using SafeMath for uint; mapping(address => address) public aggregators; address public daiAddress; address public stETH; address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; constructor ( address _daiAggregator, address _daiAddress, address _stEthAddress ) public { aggregators[_daiAddress] = _daiAggregator; daiAddress = _daiAddress; stETH = _stEthAddress; } /** * @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset * @param asset quoted currency * @return price in ether */ function getAssetToEthRate(address asset) public view returns (uint) { if (asset == ETH || asset == stETH) { return 1 ether; } address aggregatorAddress = aggregators[asset]; if (aggregatorAddress == address(0)) { revert("PriceFeedOracle: Oracle asset not found"); } int rate = Aggregator(aggregatorAddress).latestAnswer(); require(rate > 0, "PriceFeedOracle: Rate must be > 0"); return uint(rate); } /** * @dev Returns the amount of currency that is equivalent to ethIn amount of ether. * @param asset quoted Supported values: ["DAI", "ETH"] * @param ethIn amount of ether to be converted to the currency * @return price in ether */ function getAssetForEth(address asset, uint ethIn) external view returns (uint) { if (asset == daiAddress) { return ethIn.mul(1e18).div(getAssetToEthRate(daiAddress)); } if (asset == ETH || asset == stETH) { return ethIn; } revert("PriceFeedOracle: Unknown asset"); } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "./external/OZIERC20.sol"; import "./external/OZSafeMath.sol"; contract NXMToken is OZIERC20 { using OZSafeMath for uint256; event WhiteListed(address indexed member); event BlackListed(address indexed member); mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowed; mapping(address => bool) public whiteListed; mapping(address => uint) public isLockedForMV; uint256 private _totalSupply; string public name = "NXM"; string public symbol = "NXM"; uint8 public decimals = 18; address public operator; modifier canTransfer(address _to) { require(whiteListed[_to]); _; } modifier onlyOperator() { if (operator != address(0)) require(msg.sender == operator); _; } constructor(address _founderAddress, uint _initialSupply) public { _mint(_founderAddress, _initialSupply); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @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) public view returns (uint256) { return _balances[owner]; } /** * @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 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @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 increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _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 decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Adds a user to whitelist * @param _member address to add to whitelist */ function addToWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = true; emit WhiteListed(_member); return true; } /** * @dev removes a user from whitelist * @param _member address to remove from whitelist */ function removeFromWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = false; emit BlackListed(_member); return true; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public returns (bool) { _burn(msg.sender, amount); return true; } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public returns (bool) { _burnFrom(from, value); return true; } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator { _mint(account, amount); } /** * @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 canTransfer(to) returns (bool) { require(isLockedForMV[msg.sender] < now); // if not voted under governance require(value <= _balances[msg.sender]); _transfer(to, value); return true; } /** * @dev Transfer tokens to the operator from the specified address * @param from The address to transfer from. * @param value The amount to be transferred. */ function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) { require(value <= _balances[from]); _transferFrom(from, operator, 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 canTransfer(to) returns (bool) { require(isLockedForMV[from] < now); // if not voted under governance require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyOperator { if (_days.add(now) > isLockedForMV[_of]) isLockedForMV[_of] = _days.add(now); } /** * @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) internal { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } /** * @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 ) internal { _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); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ 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); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/Iupgradable.sol"; import "../../interfaces/IPooledStaking.sol"; import "../claims/ClaimsData.sol"; import "./NXMToken.sol"; import "./external/LockHandler.sol"; contract TokenController is LockHandler, Iupgradable { using SafeMath for uint256; struct CoverInfo { uint16 claimCount; bool hasOpenClaim; bool hasAcceptedClaim; // note: still 224 bits available here, can be used later } NXMToken public token; IPooledStaking public pooledStaking; uint public minCALockTime; uint public claimSubmissionGracePeriod; // coverId => CoverInfo mapping(uint => CoverInfo) public coverInfo; event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity); event Unlocked(address indexed _of, bytes32 indexed _reason, uint256 _amount); event Burned(address indexed member, bytes32 lockedUnder, uint256 amount); modifier onlyGovernance { require(msg.sender == ms.getLatestAddress("GV"), "TokenController: Caller is not governance"); _; } /** * @dev Just for interface */ function changeDependentContractAddress() public { token = NXMToken(ms.tokenAddress()); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } function markCoverClaimOpen(uint coverId) external onlyInternal { CoverInfo storage info = coverInfo[coverId]; uint16 claimCount; bool hasOpenClaim; bool hasAcceptedClaim; // reads all of them using a single SLOAD (claimCount, hasOpenClaim, hasAcceptedClaim) = (info.claimCount, info.hasOpenClaim, info.hasAcceptedClaim); // no safemath for uint16 but should be safe from // overflows as there're max 2 claims per cover claimCount = claimCount + 1; require(claimCount <= 2, "TokenController: Max claim count exceeded"); require(hasOpenClaim == false, "TokenController: Cover already has an open claim"); require(hasAcceptedClaim == false, "TokenController: Cover already has accepted claims"); // should use a single SSTORE for both (info.claimCount, info.hasOpenClaim) = (claimCount, true); } /** * @param coverId cover id (careful, not claim id!) * @param isAccepted claim verdict */ function markCoverClaimClosed(uint coverId, bool isAccepted) external onlyInternal { CoverInfo storage info = coverInfo[coverId]; require(info.hasOpenClaim == true, "TokenController: Cover claim is not marked as open"); // should use a single SSTORE for both (info.hasOpenClaim, info.hasAcceptedClaim) = (false, isAccepted); } /** * @dev to change the operator address * @param _newOperator is the new address of operator */ function changeOperator(address _newOperator) public onlyInternal { token.changeOperator(_newOperator); } /** * @dev Proxies token transfer through this contract to allow staking when members are locked for voting * @param _from Source address * @param _to Destination address * @param _value Amount to transfer */ function operatorTransfer(address _from, address _to, uint _value) external onlyInternal returns (bool) { require(msg.sender == address(pooledStaking), "TokenController: Call is only allowed from PooledStaking address"); token.operatorTransfer(_from, _value); token.transfer(_to, _value); return true; } /** * @dev Locks a specified amount of tokens, * for CLA reason and for a specified time * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lockClaimAssessmentTokens(uint256 _amount, uint256 _time) external checkPause { require(minCALockTime <= _time, "TokenController: Must lock for minimum time"); require(_time <= 180 days, "TokenController: Tokens can be locked for 180 days maximum"); // If tokens are already locked, then functions extendLock or // increaseClaimAssessmentLock should be used to make any changes _lock(msg.sender, "CLA", _amount, _time); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address whose tokens are to be locked */ function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) public onlyInternal returns (bool) { // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(_of, _reason, _amount, _time); return true; } /** * @dev Mints and locks a specified amount of tokens against an address, * for a CN reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function mintCoverNote( address _of, bytes32 _reason, uint256 _amount, uint256 _time ) external onlyInternal { require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked"); require(_amount != 0, "TokenController: Amount shouldn't be zero"); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } token.mint(address(this), _amount); uint256 lockedUntil = now.add(_time); locked[_of][_reason] = LockToken(_amount, lockedUntil, false); emit Locked(_of, _reason, _amount, lockedUntil); } /** * @dev Extends lock for reason CLA for a specified time * @param _time Lock extension time in seconds */ function extendClaimAssessmentLock(uint256 _time) external checkPause { uint256 validity = getLockedTokensValidity(msg.sender, "CLA"); require(validity.add(_time).sub(block.timestamp) <= 180 days, "TokenController: Tokens can be locked for 180 days maximum"); _extendLock(msg.sender, "CLA", _time); } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLockOf(address _of, bytes32 _reason, uint256 _time) public onlyInternal returns (bool) { _extendLock(_of, _reason, _time); return true; } /** * @dev Increase number of tokens locked for a CLA reason * @param _amount Number of tokens to be increased */ function increaseClaimAssessmentLock(uint256 _amount) external checkPause { require(_tokensLocked(msg.sender, "CLA") > 0, "TokenController: No tokens locked"); token.operatorTransfer(msg.sender, _amount); locked[msg.sender]["CLA"].amount = locked[msg.sender]["CLA"].amount.add(_amount); emit Locked(msg.sender, "CLA", _amount, locked[msg.sender]["CLA"].validity); } /** * @dev burns tokens of an address * @param _of is the address to burn tokens of * @param amount is the amount to burn * @return the boolean status of the burning process */ function burnFrom(address _of, uint amount) public onlyInternal returns (bool) { return token.burnFrom(_of, amount); } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _burnLockedTokens(_of, _reason, _amount); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal { _reduceLock(_of, _reason, _time); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _releaseLockedTokens(_of, _reason, _amount); } /** * @dev Adds an address to whitelist maintained in the contract * @param _member address to add to whitelist */ function addToWhitelist(address _member) public onlyInternal { token.addToWhiteList(_member); } /** * @dev Removes an address from the whitelist in the token * @param _member address to remove */ function removeFromWhitelist(address _member) public onlyInternal { token.removeFromWhiteList(_member); } /** * @dev Mints new token for an address * @param _member address to reward the minted tokens * @param _amount number of tokens to mint */ function mint(address _member, uint _amount) public onlyInternal { token.mint(_member, _amount); } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyInternal { token.lockForMemberVote(_of, _days); } /** * @dev Unlocks the withdrawable tokens against CLA of a specified address * @param _of Address of user, claiming back withdrawable tokens against CLA */ function withdrawClaimAssessmentTokens(address _of) external checkPause { uint256 withdrawableTokens = _tokensUnlockable(_of, "CLA"); if (withdrawableTokens > 0) { locked[_of]["CLA"].claimed = true; emit Unlocked(_of, "CLA", withdrawableTokens); token.transfer(_of, withdrawableTokens); } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param value value to set */ function updateUintParameters(bytes8 code, uint value) external onlyGovernance { if (code == "MNCLT") { minCALockTime = value; return; } if (code == "GRACEPER") { claimSubmissionGracePeriod = value; return; } revert("TokenController: invalid param code"); } function getLockReasons(address _of) external view returns (bytes32[] memory reasons) { return lockReason[_of]; } /** * @dev Gets the validity of locked tokens of a specified address * @param _of The address to query the validity * @param reason reason for which tokens were locked */ function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) { validity = locked[_of][reason].validity; } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensLocked(_of, _reason); } /** * @dev Returns tokens locked and validity for a specified address and reason * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLockedWithValidity(address _of, bytes32 _reason) public view returns (uint256 amount, uint256 validity) { bool claimed = locked[_of][_reason].claimed; amount = locked[_of][_reason].amount; validity = locked[_of][_reason].validity; if (claimed) { amount = 0; } } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensUnlockable(_of, _reason); } function totalSupply() public view returns (uint256) { return token.totalSupply(); } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { return _tokensLockedAtTime(_of, _reason, _time); } /** * @dev Returns the total amount of tokens held by an address: * transferable + locked + staked for pooled staking - pending burns. * Used by Claims and Governance in member voting to calculate the user's vote weight. * * @param _of The address to query the total balance of * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount) { amount = token.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } uint stakerReward = pooledStaking.stakerReward(_of); uint stakerDeposit = pooledStaking.stakerDeposit(_of); amount = amount.add(stakerDeposit).add(stakerReward); } /** * @dev Returns the total amount of locked and staked tokens. * Used by MemberRoles to check eligibility for withdraw / switch membership. * Includes tokens locked for claim assessment, tokens staked for risk assessment, and locked cover notes * Does not take into account pending burns. * @param _of member whose locked tokens are to be calculate */ function totalLockedBalance(address _of) public view returns (uint256 amount) { for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } amount = amount.add(pooledStaking.stakerDeposit(_of)); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal { require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked"); require(_amount != 0, "TokenController: Amount shouldn't be zero"); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } token.operatorTransfer(_of, _amount); uint256 validUntil = now.add(_time); locked[_of][_reason] = LockToken(_amount, validUntil, false); emit Locked(_of, _reason, _amount, validUntil); } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function _tokensLocked(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (!locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) internal view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) { amount = locked[_of][_reason].amount; } } /** * @dev Extends lock for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function _extendLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked"); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked"); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount"); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); // lock reason removal is skipped here: needs to be done from offchain token.burn(_amount); emit Burned(_of, _reason, _amount); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount"); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); // lock reason removal is skipped here: needs to be done from offchain token.transfer(_of, _amount); emit Unlocked(_of, _reason, _amount); } function withdrawCoverNote( address _of, uint[] calldata _coverIds, uint[] calldata _indexes ) external onlyInternal { uint reasonCount = lockReason[_of].length; uint lastReasonIndex = reasonCount.sub(1, "TokenController: No locked cover notes found"); uint totalAmount = 0; // The iteration is done from the last to first to prevent reason indexes from // changing due to the way we delete the items (copy last to current and pop last). // The provided indexes array must be ordered, otherwise reason index checks will fail. for (uint i = _coverIds.length; i > 0; i--) { bool hasOpenClaim = coverInfo[_coverIds[i - 1]].hasOpenClaim; require(hasOpenClaim == false, "TokenController: Cannot withdraw for cover with an open claim"); // note: cover owner is implicitly checked using the reason hash bytes32 _reason = keccak256(abi.encodePacked("CN", _of, _coverIds[i - 1])); uint _reasonIndex = _indexes[i - 1]; require(lockReason[_of][_reasonIndex] == _reason, "TokenController: Bad reason index"); uint amount = locked[_of][_reason].amount; totalAmount = totalAmount.add(amount); delete locked[_of][_reason]; if (lastReasonIndex != _reasonIndex) { lockReason[_of][_reasonIndex] = lockReason[_of][lastReasonIndex]; } lockReason[_of].pop(); emit Unlocked(_of, _reason, amount); if (lastReasonIndex > 0) { lastReasonIndex = lastReasonIndex.sub(1, "TokenController: Reason count mismatch"); } } token.transfer(_of, totalAmount); } function removeEmptyReason(address _of, bytes32 _reason, uint _index) external { _removeEmptyReason(_of, _reason, _index); } function removeMultipleEmptyReasons( address[] calldata _members, bytes32[] calldata _reasons, uint[] calldata _indexes ) external { require(_members.length == _reasons.length, "TokenController: members and reasons array lengths differ"); require(_reasons.length == _indexes.length, "TokenController: reasons and indexes array lengths differ"); for (uint i = _members.length; i > 0; i--) { uint idx = i - 1; _removeEmptyReason(_members[idx], _reasons[idx], _indexes[idx]); } } function _removeEmptyReason(address _of, bytes32 _reason, uint _index) internal { uint lastReasonIndex = lockReason[_of].length.sub(1, "TokenController: lockReason is empty"); require(lockReason[_of][_index] == _reason, "TokenController: bad reason index"); require(locked[_of][_reason].amount == 0, "TokenController: reason amount is not zero"); if (lastReasonIndex != _index) { lockReason[_of][_index] = lockReason[_of][lastReasonIndex]; } lockReason[_of].pop(); } function initialize() external { require(claimSubmissionGracePeriod == 0, "TokenController: Already initialized"); claimSubmissionGracePeriod = 120 days; migrate(); } function migrate() internal { ClaimsData cd = ClaimsData(ms.getLatestAddress("CD")); uint totalClaims = cd.actualClaimLength() - 1; // fix stuck claims 21 & 22 cd.changeFinalVerdict(20, -1); cd.setClaimStatus(20, 6); cd.changeFinalVerdict(21, -1); cd.setClaimStatus(21, 6); // reduce claim assessment lock period for members locked for more than 180 days // extracted using scripts/extract-ca-locked-more-than-180.js address payable[3] memory members = [ 0x4a9fA34da6d2378c8f3B9F6b83532B169beaEDFc, 0x6b5DCDA27b5c3d88e71867D6b10b35372208361F, 0x8B6D1e5b4db5B6f9aCcc659e2b9619B0Cd90D617 ]; for (uint i = 0; i < members.length; i++) { if (locked[members[i]]["CLA"].validity > now + 180 days) { locked[members[i]]["CLA"].validity = now + 180 days; } } for (uint i = 1; i <= totalClaims; i++) { (/*id*/, uint status) = cd.getClaimStatusNumber(i); (/*id*/, uint coverId) = cd.getClaimCoverId(i); int8 verdict = cd.getFinalVerdict(i); // SLOAD CoverInfo memory info = coverInfo[coverId]; info.claimCount = info.claimCount + 1; info.hasAcceptedClaim = (status == 14); info.hasOpenClaim = (verdict == 0); // SSTORE coverInfo[coverId] = info; } } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../abstract/MasterAware.sol"; import "../capital/Pool.sol"; import "../cover/QuotationData.sol"; import "../oracles/PriceFeedOracle.sol"; import "../token/NXMToken.sol"; import "../token/TokenData.sol"; import "./LegacyMCR.sol"; contract MCR is MasterAware { using SafeMath for uint; Pool public pool; QuotationData public qd; // sizeof(qd) + 96 = 160 + 96 = 256 (occupies entire slot) uint96 _unused; // the following values are expressed in basis points uint24 public mcrFloorIncrementThreshold = 13000; uint24 public maxMCRFloorIncrement = 100; uint24 public maxMCRIncrement = 500; uint24 public gearingFactor = 48000; // min update between MCR updates in seconds uint24 public minUpdateTime = 3600; uint112 public mcrFloor; uint112 public mcr; uint112 public desiredMCR; uint32 public lastUpdateTime; LegacyMCR public previousMCR; event MCRUpdated( uint mcr, uint desiredMCR, uint mcrFloor, uint mcrETHWithGear, uint totalSumAssured ); uint constant UINT24_MAX = ~uint24(0); uint constant MAX_MCR_ADJUSTMENT = 100; uint constant BASIS_PRECISION = 10000; constructor (address masterAddress) public { changeMasterAddress(masterAddress); if (masterAddress != address(0)) { previousMCR = LegacyMCR(master.getLatestAddress("MC")); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { qd = QuotationData(master.getLatestAddress("QD")); pool = Pool(master.getLatestAddress("P1")); initialize(); } function initialize() internal { address currentMCR = master.getLatestAddress("MC"); if (address(previousMCR) == address(0) || currentMCR != address(this)) { // already initialized or not ready for initialization return; } // fetch MCR parameters from previous contract uint112 minCap = 7000 * 1e18; mcrFloor = uint112(previousMCR.variableMincap()) + minCap; mcr = uint112(previousMCR.getLastMCREther()); desiredMCR = mcr; mcrFloorIncrementThreshold = uint24(previousMCR.dynamicMincapThresholdx100()); maxMCRFloorIncrement = uint24(previousMCR.dynamicMincapIncrementx100()); // set last updated time to now lastUpdateTime = uint32(block.timestamp); previousMCR = LegacyMCR(address(0)); } /** * @dev Gets total sum assured (in ETH). * @return amount of sum assured */ function getAllSumAssurance() public view returns (uint) { PriceFeedOracle priceFeed = pool.priceFeedOracle(); address daiAddress = priceFeed.daiAddress(); uint ethAmount = qd.getTotalSumAssured("ETH").mul(1e18); uint daiAmount = qd.getTotalSumAssured("DAI").mul(1e18); uint daiRate = priceFeed.getAssetToEthRate(daiAddress); uint daiAmountInEth = daiAmount.mul(daiRate).div(1e18); return ethAmount.add(daiAmountInEth); } /* * @dev trigger an MCR update. Current virtual MCR value is synced to storage, mcrFloor is potentially updated * and a new desiredMCR value to move towards is set. * */ function updateMCR() public { _updateMCR(pool.getPoolValueInEth(), false); } function updateMCRInternal(uint poolValueInEth, bool forceUpdate) public onlyInternal { _updateMCR(poolValueInEth, forceUpdate); } function _updateMCR(uint poolValueInEth, bool forceUpdate) internal { // read with 1 SLOAD uint _mcrFloorIncrementThreshold = mcrFloorIncrementThreshold; uint _maxMCRFloorIncrement = maxMCRFloorIncrement; uint _gearingFactor = gearingFactor; uint _minUpdateTime = minUpdateTime; uint _mcrFloor = mcrFloor; // read with 1 SLOAD uint112 _mcr = mcr; uint112 _desiredMCR = desiredMCR; uint32 _lastUpdateTime = lastUpdateTime; if (!forceUpdate && _lastUpdateTime + _minUpdateTime > block.timestamp) { return; } if (block.timestamp > _lastUpdateTime && pool.calculateMCRRatio(poolValueInEth, _mcr) >= _mcrFloorIncrementThreshold) { // MCR floor updates by up to maxMCRFloorIncrement percentage per day whenever the MCR ratio exceeds 1.3 // MCR floor is monotonically increasing. uint basisPointsAdjustment = min( _maxMCRFloorIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days), _maxMCRFloorIncrement ); uint newMCRFloor = _mcrFloor.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION); require(newMCRFloor <= uint112(~0), 'MCR: newMCRFloor overflow'); mcrFloor = uint112(newMCRFloor); } // sync the current virtual MCR value to storage uint112 newMCR = uint112(getMCR()); if (newMCR != _mcr) { mcr = newMCR; } // the desiredMCR cannot fall below the mcrFloor but may have a higher or lower target value based // on the changes in the totalSumAssured in the system. uint totalSumAssured = getAllSumAssurance(); uint gearedMCR = totalSumAssured.mul(BASIS_PRECISION).div(_gearingFactor); uint112 newDesiredMCR = uint112(max(gearedMCR, mcrFloor)); if (newDesiredMCR != _desiredMCR) { desiredMCR = newDesiredMCR; } lastUpdateTime = uint32(block.timestamp); emit MCRUpdated(mcr, desiredMCR, mcrFloor, gearedMCR, totalSumAssured); } /** * @dev Calculates the current virtual MCR value. The virtual MCR value moves towards the desiredMCR value away * from the stored mcr value at constant velocity based on how much time passed from the lastUpdateTime. * The total change in virtual MCR cannot exceed 1% of stored mcr. * * This approach allows for the MCR to change smoothly across time without sudden jumps between values, while * always progressing towards the desiredMCR goal. The desiredMCR can change subject to the call of _updateMCR * so the virtual MCR value may change direction and start decreasing instead of increasing or vice-versa. * * @return mcr */ function getMCR() public view returns (uint) { // read with 1 SLOAD uint _mcr = mcr; uint _desiredMCR = desiredMCR; uint _lastUpdateTime = lastUpdateTime; if (block.timestamp == _lastUpdateTime) { return _mcr; } uint _maxMCRIncrement = maxMCRIncrement; uint basisPointsAdjustment = _maxMCRIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days); basisPointsAdjustment = min(basisPointsAdjustment, MAX_MCR_ADJUSTMENT); if (_desiredMCR > _mcr) { return min(_mcr.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION), _desiredMCR); } // in case desiredMCR <= mcr return max(_mcr.mul(BASIS_PRECISION - basisPointsAdjustment).div(BASIS_PRECISION), _desiredMCR); } function getGearedMCR() external view returns (uint) { return getAllSumAssurance().mul(BASIS_PRECISION).div(gearingFactor); } function min(uint x, uint y) pure internal returns (uint) { return x < y ? x : y; } function max(uint x, uint y) pure internal returns (uint) { return x > y ? x : y; } /** * @dev Updates Uint Parameters * @param code parameter code * @param val new value */ function updateUintParameters(bytes8 code, uint val) public { require(master.checkIsAuthToGoverned(msg.sender)); if (code == "DMCT") { require(val <= UINT24_MAX, "MCR: value too large"); mcrFloorIncrementThreshold = uint24(val); } else if (code == "DMCI") { require(val <= UINT24_MAX, "MCR: value too large"); maxMCRFloorIncrement = uint24(val); } else if (code == "MMIC") { require(val <= UINT24_MAX, "MCR: value too large"); maxMCRIncrement = uint24(val); } else if (code == "GEAR") { require(val <= UINT24_MAX, "MCR: value too large"); gearingFactor = uint24(val); } else if (code == "MUTI") { require(val <= UINT24_MAX, "MCR: value too large"); minUpdateTime = uint24(val); } else { revert("Invalid param code"); } } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; contract INXMMaster { address public tokenAddress; address public owner; uint public pauseTime; function delegateCallBack(bytes32 myid) external; function masterInitialized() public view returns (bool); function isInternal(address _add) public view returns (bool); function isPause() public view returns (bool check); function isOwner(address _add) public view returns (bool); function isMember(address _add) public view returns (bool); function checkIsAuthToGoverned(address _add) public view returns (bool); function updatePauseTime(uint _time) public; function dAppLocker() public view returns (address _add); function dAppToken() public view returns (address _add); function getLatestAddress(bytes2 _contractName) public view returns (address payable contractAddress); } /* Copyright (C) 2020 NexusMutual.io 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/ */ //Claims Reward Contract contains the functions for calculating number of tokens // that will get rewarded, unlocked or burned depending upon the status of claim. pragma solidity ^0.5.0; import "../../interfaces/IPooledStaking.sol"; import "../capital/Pool.sol"; import "../cover/QuotationData.sol"; import "../governance/Governance.sol"; import "../token/TokenData.sol"; import "../token/TokenFunctions.sol"; import "./Claims.sol"; import "./ClaimsData.sol"; import "../capital/MCR.sol"; contract ClaimsReward is Iupgradable { using SafeMath for uint; NXMToken internal tk; TokenController internal tc; TokenData internal td; QuotationData internal qd; Claims internal c1; ClaimsData internal cd; Pool internal pool; Governance internal gv; IPooledStaking internal pooledStaking; MemberRoles internal memberRoles; MCR public mcr; // assigned in constructor address public DAI; // constants address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint private constant DECIMAL1E18 = uint(10) ** 18; constructor (address masterAddress, address _daiAddress) public { changeMasterAddress(masterAddress); DAI = _daiAddress; } function changeDependentContractAddress() public onlyInternal { c1 = Claims(ms.getLatestAddress("CL")); cd = ClaimsData(ms.getLatestAddress("CD")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); memberRoles = MemberRoles(ms.getLatestAddress("MR")); pool = Pool(ms.getLatestAddress("P1")); mcr = MCR(ms.getLatestAddress("MC")); } /// @dev Decides the next course of action for a given claim. function changeClaimStatus(uint claimid) public checkPause onlyInternal { (, uint coverid) = cd.getClaimCoverId(claimid); (, uint status) = cd.getClaimStatusNumber(claimid); // when current status is "Pending-Claim Assessor Vote" if (status == 0) { _changeClaimStatusCA(claimid, coverid, status); } else if (status >= 1 && status <= 5) { _changeClaimStatusMV(claimid, coverid, status); } else if (status == 12) {// when current status is "Claim Accepted Payout Pending" bool payoutSucceeded = attemptClaimPayout(coverid); if (payoutSucceeded) { c1.setClaimStatus(claimid, 14); } else { c1.setClaimStatus(claimid, 12); } } } function getCurrencyAssetAddress(bytes4 currency) public view returns (address) { if (currency == "ETH") { return ETH; } if (currency == "DAI") { return DAI; } revert("ClaimsReward: unknown asset"); } function attemptClaimPayout(uint coverId) internal returns (bool success) { uint sumAssured = qd.getCoverSumAssured(coverId); // TODO: when adding new cover currencies, fetch the correct decimals for this multiplication uint sumAssuredWei = sumAssured.mul(1e18); // get asset address bytes4 coverCurrency = qd.getCurrencyOfCover(coverId); address asset = getCurrencyAssetAddress(coverCurrency); // get payout address address payable coverHolder = qd.getCoverMemberAddress(coverId); address payable payoutAddress = memberRoles.getClaimPayoutAddress(coverHolder); // execute the payout bool payoutSucceeded = pool.sendClaimPayout(asset, payoutAddress, sumAssuredWei); if (payoutSucceeded) { // burn staked tokens (, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = pool.getTokenPrice(asset); // note: for new assets "18" needs to be replaced with target asset decimals uint burnNXMAmount = sumAssuredWei.mul(1e18).div(tokenPrice); pooledStaking.pushBurn(scAddress, burnNXMAmount); // adjust total sum assured (, address coverContract) = qd.getscAddressOfCover(coverId); qd.subFromTotalSumAssured(coverCurrency, sumAssured); qd.subFromTotalSumAssuredSC(coverContract, coverCurrency, sumAssured); // update MCR since total sum assured and MCR% change mcr.updateMCRInternal(pool.getPoolValueInEth(), true); return true; } return false; } /// @dev Amount of tokens to be rewarded to a user for a particular vote id. /// @param check 1 -> CA vote, else member vote /// @param voteid vote id for which reward has to be Calculated /// @param flag if 1 calculate even if claimed,else don't calculate if already claimed /// @return tokenCalculated reward to be given for vote id /// @return lastClaimedCheck true if final verdict is still pending for that voteid /// @return tokens number of tokens locked under that voteid /// @return perc percentage of reward to be given. function getRewardToBeGiven( uint check, uint voteid, uint flag ) public view returns ( uint tokenCalculated, bool lastClaimedCheck, uint tokens, uint perc ) { uint claimId; int8 verdict; bool claimed; uint tokensToBeDist; uint totalTokens; (tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid); lastClaimedCheck = false; int8 claimVerdict = cd.getFinalVerdict(claimId); if (claimVerdict == 0) { lastClaimedCheck = true; } if (claimVerdict == verdict && (claimed == false || flag == 1)) { if (check == 1) { (perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId); } else { (, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId); } if (perc > 0) { if (check == 1) { if (verdict == 1) { (, totalTokens,) = cd.getClaimsTokenCA(claimId); } else { (,, totalTokens) = cd.getClaimsTokenCA(claimId); } } else { if (verdict == 1) { (, totalTokens,) = cd.getClaimsTokenMV(claimId); } else { (,, totalTokens) = cd.getClaimsTokenMV(claimId); } } tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100)); } } } /// @dev Transfers all tokens held by contract to a new contract in case of upgrade. function upgrade(address _newAdd) public onlyInternal { uint amount = tk.balanceOf(address(this)); if (amount > 0) { require(tk.transfer(_newAdd, amount)); } } /// @dev Total reward in token due for claim by a user. /// @return total total number of tokens function getRewardToBeDistributedByUser(address _add) public view returns (uint total) { uint lengthVote = cd.getVoteAddressCALength(_add); uint lastIndexCA; uint lastIndexMV; uint tokenForVoteId; uint voteId; (lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add); for (uint i = lastIndexCA; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(_add, i); (tokenForVoteId,,,) = getRewardToBeGiven(1, voteId, 0); total = total.add(tokenForVoteId); } lengthVote = cd.getVoteAddressMemberLength(_add); for (uint j = lastIndexMV; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(_add, j); (tokenForVoteId,,,) = getRewardToBeGiven(0, voteId, 0); total = total.add(tokenForVoteId); } return (total); } /// @dev Gets reward amount and claiming status for a given claim id. /// @return reward amount of tokens to user. /// @return claimed true if already claimed false if yet to be claimed. function getRewardAndClaimedStatus(uint check, uint claimId) public view returns (uint reward, bool claimed) { uint voteId; uint claimid; uint lengthVote; if (check == 1) { lengthVote = cd.getVoteAddressCALength(msg.sender); for (uint i = 0; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(msg.sender, i); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) {break;} } } else { lengthVote = cd.getVoteAddressMemberLength(msg.sender); for (uint j = 0; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(msg.sender, j); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) {break;} } } (reward,,,) = getRewardToBeGiven(check, voteId, 1); } /** * @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance * Claim assesment, Risk assesment, Governance rewards */ function claimAllPendingReward(uint records) public isMemberAndcheckPause { _claimRewardToBeDistributed(records); pooledStaking.withdrawReward(msg.sender); uint governanceRewards = gv.claimReward(msg.sender, records); if (governanceRewards > 0) { require(tk.transfer(msg.sender, governanceRewards)); } } /** * @dev Function used to get pending rewards of a particular user address. * @param _add user address. * @return total reward amount of the user */ function getAllPendingRewardOfUser(address _add) public view returns (uint) { uint caReward = getRewardToBeDistributedByUser(_add); uint pooledStakingReward = pooledStaking.stakerReward(_add); uint governanceReward = gv.getPendingReward(_add); return caReward.add(pooledStakingReward).add(governanceReward); } /// @dev Rewards/Punishes users who participated in Claims assessment. // Unlocking and burning of the tokens will also depend upon the status of claim. /// @param claimid Claim Id. function _rewardAgainstClaim(uint claimid, uint coverid, uint status) internal { uint premiumNXM = qd.getCoverPremiumNXM(coverid); uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100); // 20% of premium uint percCA; uint percMV; (percCA, percMV) = cd.getRewardStatus(status); cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens); if (percCA > 0 || percMV > 0) { tc.mint(address(this), distributableTokens); } // denied if (status == 6 || status == 9 || status == 11) { cd.changeFinalVerdict(claimid, -1); tc.markCoverClaimClosed(coverid, false); _burnCoverNoteDeposit(coverid); // accepted } else if (status == 7 || status == 8 || status == 10) { cd.changeFinalVerdict(claimid, 1); tc.markCoverClaimClosed(coverid, true); _unlockCoverNote(coverid); bool payoutSucceeded = attemptClaimPayout(coverid); // 12 = payout pending, 14 = payout succeeded uint nextStatus = payoutSucceeded ? 14 : 12; c1.setClaimStatus(claimid, nextStatus); } } function _burnCoverNoteDeposit(uint coverId) internal { address _of = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); uint lockedAmount = tc.tokensLocked(_of, reason); (uint amount,) = td.depositedCN(coverId); amount = amount.div(2); // limit burn amount to actual amount locked uint burnAmount = lockedAmount < amount ? lockedAmount : amount; if (burnAmount != 0) { tc.burnLockedTokens(_of, reason, amount); } } function _unlockCoverNote(uint coverId) internal { address coverHolder = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId)); uint lockedCN = tc.tokensLocked(coverHolder, reason); if (lockedCN != 0) { tc.releaseLockedTokens(coverHolder, reason, lockedCN); } } /// @dev Computes the result of Claim Assessors Voting for a given claim id. function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency. uint accept; uint deny; uint acceptAndDeny; bool rewardOrPunish; uint sumAssured; (, accept) = cd.getClaimVote(claimid, 1); (, deny) = cd.getClaimVote(claimid, - 1); acceptAndDeny = accept.add(deny); accept = accept.mul(100); deny = deny.mul(100); if (caTokens == 0) { status = 3; } else { sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); // Min threshold reached tokens used for voting > 5* sum assured if (caTokens > sumAssured.mul(5)) { if (accept.div(acceptAndDeny) > 70) { status = 7; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted)); rewardOrPunish = true; } else if (deny.div(acceptAndDeny) > 70) { status = 6; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied)); rewardOrPunish = true; } else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 4; } else { status = 5; } } else { if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 2; } else { status = 3; } } } c1.setClaimStatus(claimid, status); if (rewardOrPunish) { _rewardAgainstClaim(claimid, coverid, status); } } } /// @dev Computes the result of Member Voting for a given claim id. function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint8 coverStatus; uint statusOrig = status; uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency. // If tokens used for acceptance >50%, claim is accepted uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); uint thresholdUnreached = 0; // Minimum threshold for member voting is reached only when // value of tokens used for voting > 5* sum assured of claim id if (mvTokens < sumAssured.mul(5)) { thresholdUnreached = 1; } uint accept; (, accept) = cd.getClaimMVote(claimid, 1); uint deny; (, deny) = cd.getClaimMVote(claimid, - 1); if (accept.add(deny) > 0) { if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 8; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 9; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } } if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) { status = 10; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) { status = 11; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } c1.setClaimStatus(claimid, status); qd.changeCoverStatusNo(coverid, uint8(coverStatus)); // Reward/Punish Claim Assessors and Members who participated in Claims assessment _rewardAgainstClaim(claimid, coverid, status); } } /// @dev Allows a user to claim all pending Claims assessment rewards. function _claimRewardToBeDistributed(uint _records) internal { uint lengthVote = cd.getVoteAddressCALength(msg.sender); uint voteid; uint lastIndex; (lastIndex,) = cd.getRewardDistributedIndex(msg.sender); uint total = 0; uint tokenForVoteId = 0; bool lastClaimedCheck; uint _days = td.lockCADays(); bool claimed; uint counter = 0; uint claimId; uint perc; uint i; uint lastClaimed = lengthVote; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressCA(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (perc > 0 && !claimed) { counter++; cd.setRewardClaimed(voteid, true); } else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) { (perc,,) = cd.getClaimRewardDetail(claimId); if (perc == 0) { counter++; } cd.setRewardClaimed(voteid, true); } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexCA(msg.sender, i); } else { cd.setRewardDistributedIndexCA(msg.sender, lastClaimed); } lengthVote = cd.getVoteAddressMemberLength(msg.sender); lastClaimed = lengthVote; _days = _days.mul(counter); if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) { tc.reduceLock(msg.sender, "CLA", _days); } (, lastIndex) = cd.getRewardDistributedIndex(msg.sender); lastClaimed = lengthVote; counter = 0; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressMember(msg.sender, i); (tokenForVoteId, lastClaimedCheck,,) = getRewardToBeGiven(0, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (claimed == false && cd.getFinalVerdict(claimId) != 0) { cd.setRewardClaimed(voteid, true); counter++; } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (total > 0) { require(tk.transfer(msg.sender, total)); } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexMV(msg.sender, i); } else { cd.setRewardDistributedIndexMV(msg.sender, lastClaimed); } } /** * @dev Function used to claim the commission earned by the staker. */ function _claimStakeCommission(uint _records, address _user) external onlyInternal { uint total = 0; uint len = td.getStakerStakedContractLength(_user); uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user); uint commissionEarned; uint commissionRedeemed; uint maxCommission; uint lastCommisionRedeemed = len; uint counter; uint i; for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) { commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i); commissionEarned = td.getStakerEarnedStakeCommission(_user, i); maxCommission = td.getStakerInitialStakedAmountOnContract( _user, i).mul(td.stakerMaxCommissionPer()).div(100); if (lastCommisionRedeemed == len && maxCommission != commissionEarned) lastCommisionRedeemed = i; td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed)); total = total.add(commissionEarned.sub(commissionRedeemed)); counter++; } if (lastCommisionRedeemed == len) { td.setLastCompletedStakeCommissionIndex(_user, i); } else { td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed); } if (total > 0) require(tk.transfer(_user, total)); // solhint-disable-line } } /* Copyright (C) 2021 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../abstract/MasterAware.sol"; import "../../interfaces/IPooledStaking.sol"; import "../capital/Pool.sol"; import "../claims/ClaimsData.sol"; import "../claims/ClaimsReward.sol"; import "../cover/QuotationData.sol"; import "../governance/MemberRoles.sol"; import "../token/TokenController.sol"; import "../capital/MCR.sol"; contract Incidents is MasterAware { using SafeERC20 for IERC20; using SafeMath for uint; struct Incident { address productId; uint32 date; uint priceBefore; } // contract identifiers enum ID {CD, CR, QD, TC, MR, P1, PS, MC} mapping(uint => address payable) public internalContracts; Incident[] public incidents; // product id => underlying token (ex. yDAI -> DAI) mapping(address => address) public underlyingToken; // product id => covered token (ex. 0xc7ed.....1 -> yDAI) mapping(address => address) public coveredToken; // claim id => payout amount mapping(uint => uint) public claimPayout; // product id => accumulated burn amount mapping(address => uint) public accumulatedBurn; // burn ratio in bps, ex 2000 for 20% uint public BURN_RATIO; // burn ratio in bps uint public DEDUCTIBLE_RATIO; uint constant BASIS_PRECISION = 10000; event ProductAdded( address indexed productId, address indexed coveredToken, address indexed underlyingToken ); event IncidentAdded( address indexed productId, uint incidentDate, uint priceBefore ); modifier onlyAdvisoryBoard { uint abRole = uint(MemberRoles.Role.AdvisoryBoard); require( memberRoles().checkRole(msg.sender, abRole), "Incidents: Caller is not an advisory board member" ); _; } function initialize() external { require(BURN_RATIO == 0, "Already initialized"); BURN_RATIO = 2000; DEDUCTIBLE_RATIO = 9000; } function addProducts( address[] calldata _productIds, address[] calldata _coveredTokens, address[] calldata _underlyingTokens ) external onlyAdvisoryBoard { require( _productIds.length == _coveredTokens.length, "Incidents: Protocols and covered tokens lengths differ" ); require( _productIds.length == _underlyingTokens.length, "Incidents: Protocols and underyling tokens lengths differ" ); for (uint i = 0; i < _productIds.length; i++) { address id = _productIds[i]; require(coveredToken[id] == address(0), "Incidents: covered token is already set"); require(underlyingToken[id] == address(0), "Incidents: underlying token is already set"); coveredToken[id] = _coveredTokens[i]; underlyingToken[id] = _underlyingTokens[i]; emit ProductAdded(id, _coveredTokens[i], _underlyingTokens[i]); } } function incidentCount() external view returns (uint) { return incidents.length; } function addIncident( address productId, uint incidentDate, uint priceBefore ) external onlyGovernance { address underlying = underlyingToken[productId]; require(underlying != address(0), "Incidents: Unsupported product"); Incident memory incident = Incident(productId, uint32(incidentDate), priceBefore); incidents.push(incident); emit IncidentAdded(productId, incidentDate, priceBefore); } function redeemPayoutForMember( uint coverId, uint incidentId, uint coveredTokenAmount, address member ) external onlyInternal returns (uint claimId, uint payoutAmount, address payoutToken) { (claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, member); } function redeemPayout( uint coverId, uint incidentId, uint coveredTokenAmount ) external returns (uint claimId, uint payoutAmount, address payoutToken) { (claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, msg.sender); } function _redeemPayout( uint coverId, uint incidentId, uint coveredTokenAmount, address coverOwner ) internal returns (uint claimId, uint payoutAmount, address coverAsset) { QuotationData qd = quotationData(); Incident memory incident = incidents[incidentId]; uint sumAssured; bytes4 currency; { address productId; address _coverOwner; (/* id */, _coverOwner, productId, currency, sumAssured, /* premiumNXM */ ) = qd.getCoverDetailsByCoverID1(coverId); // check ownership and covered protocol require(coverOwner == _coverOwner, "Incidents: Not cover owner"); require(productId == incident.productId, "Incidents: Bad incident id"); } { uint coverPeriod = uint(qd.getCoverPeriod(coverId)).mul(1 days); uint coverExpirationDate = qd.getValidityOfCover(coverId); uint coverStartDate = coverExpirationDate.sub(coverPeriod); // check cover validity require(coverStartDate <= incident.date, "Incidents: Cover start date is after the incident"); require(coverExpirationDate >= incident.date, "Incidents: Cover end date is before the incident"); // check grace period uint gracePeriod = tokenController().claimSubmissionGracePeriod(); require(coverExpirationDate.add(gracePeriod) >= block.timestamp, "Incidents: Grace period has expired"); } { // assumes 18 decimals (eth & dai) uint decimalPrecision = 1e18; uint maxAmount; // sumAssured is currently stored without decimals uint coverAmount = sumAssured.mul(decimalPrecision); { // max amount check uint deductiblePriceBefore = incident.priceBefore.mul(DEDUCTIBLE_RATIO).div(BASIS_PRECISION); maxAmount = coverAmount.mul(decimalPrecision).div(deductiblePriceBefore); require(coveredTokenAmount <= maxAmount, "Incidents: Amount exceeds sum assured"); } // payoutAmount = coveredTokenAmount / maxAmount * coverAmount // = coveredTokenAmount * coverAmount / maxAmount payoutAmount = coveredTokenAmount.mul(coverAmount).div(maxAmount); } { TokenController tc = tokenController(); // mark cover as having a successful claim tc.markCoverClaimOpen(coverId); tc.markCoverClaimClosed(coverId, true); // create the claim ClaimsData cd = claimsData(); claimId = cd.actualClaimLength(); cd.addClaim(claimId, coverId, coverOwner, now); cd.callClaimEvent(coverId, coverOwner, claimId, now); cd.setClaimStatus(claimId, 14); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimAccepted)); claimPayout[claimId] = payoutAmount; } coverAsset = claimsReward().getCurrencyAssetAddress(currency); _sendPayoutAndPushBurn( incident.productId, address(uint160(coverOwner)), coveredTokenAmount, coverAsset, payoutAmount ); qd.subFromTotalSumAssured(currency, sumAssured); qd.subFromTotalSumAssuredSC(incident.productId, currency, sumAssured); mcr().updateMCRInternal(pool().getPoolValueInEth(), true); } function pushBurns(address productId, uint maxIterations) external { uint burnAmount = accumulatedBurn[productId]; delete accumulatedBurn[productId]; require(burnAmount > 0, "Incidents: No burns to push"); require(maxIterations >= 30, "Incidents: Pass at least 30 iterations"); IPooledStaking ps = pooledStaking(); ps.pushBurn(productId, burnAmount); ps.processPendingActions(maxIterations); } function withdrawAsset(address asset, address destination, uint amount) external onlyGovernance { IERC20 token = IERC20(asset); uint balance = token.balanceOf(address(this)); uint transferAmount = amount > balance ? balance : amount; token.safeTransfer(destination, transferAmount); } function _sendPayoutAndPushBurn( address productId, address payable coverOwner, uint coveredTokenAmount, address coverAsset, uint payoutAmount ) internal { address _coveredToken = coveredToken[productId]; // pull depegged tokens IERC20(_coveredToken).safeTransferFrom(msg.sender, address(this), coveredTokenAmount); Pool p1 = pool(); // send the payoutAmount { address payable payoutAddress = memberRoles().getClaimPayoutAddress(coverOwner); bool success = p1.sendClaimPayout(coverAsset, payoutAddress, payoutAmount); require(success, "Incidents: Payout failed"); } { // burn uint decimalPrecision = 1e18; uint assetPerNxm = p1.getTokenPrice(coverAsset); uint maxBurnAmount = payoutAmount.mul(decimalPrecision).div(assetPerNxm); uint burnAmount = maxBurnAmount.mul(BURN_RATIO).div(BASIS_PRECISION); accumulatedBurn[productId] = accumulatedBurn[productId].add(burnAmount); } } function claimsData() internal view returns (ClaimsData) { return ClaimsData(internalContracts[uint(ID.CD)]); } function claimsReward() internal view returns (ClaimsReward) { return ClaimsReward(internalContracts[uint(ID.CR)]); } function quotationData() internal view returns (QuotationData) { return QuotationData(internalContracts[uint(ID.QD)]); } function tokenController() internal view returns (TokenController) { return TokenController(internalContracts[uint(ID.TC)]); } function memberRoles() internal view returns (MemberRoles) { return MemberRoles(internalContracts[uint(ID.MR)]); } function pool() internal view returns (Pool) { return Pool(internalContracts[uint(ID.P1)]); } function pooledStaking() internal view returns (IPooledStaking) { return IPooledStaking(internalContracts[uint(ID.PS)]); } function mcr() internal view returns (MCR) { return MCR(internalContracts[uint(ID.MC)]); } function updateUintParameters(bytes8 code, uint value) external onlyGovernance { if (code == "BURNRATE") { require(value <= BASIS_PRECISION, "Incidents: Burn ratio cannot exceed 10000"); BURN_RATIO = value; return; } if (code == "DEDUCTIB") { require(value <= BASIS_PRECISION, "Incidents: Deductible ratio cannot exceed 10000"); DEDUCTIBLE_RATIO = value; return; } revert("Incidents: Invalid parameter"); } function changeDependentContractAddress() external { INXMMaster master = INXMMaster(master); internalContracts[uint(ID.CD)] = master.getLatestAddress("CD"); internalContracts[uint(ID.CR)] = master.getLatestAddress("CR"); internalContracts[uint(ID.QD)] = master.getLatestAddress("QD"); internalContracts[uint(ID.TC)] = master.getLatestAddress("TC"); internalContracts[uint(ID.MR)] = master.getLatestAddress("MR"); internalContracts[uint(ID.P1)] = master.getLatestAddress("P1"); internalContracts[uint(ID.PS)] = master.getLatestAddress("PS"); internalContracts[uint(ID.MC)] = master.getLatestAddress("MC"); } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/Iupgradable.sol"; contract TokenData is Iupgradable { using SafeMath for uint; address payable public walletAddress; uint public lockTokenTimeAfterCoverExp; uint public bookTime; uint public lockCADays; uint public lockMVDays; uint public scValidDays; uint public joiningFee; uint public stakerCommissionPer; uint public stakerMaxCommissionPer; uint public tokenExponent; uint public priceStep; struct StakeCommission { uint commissionEarned; uint commissionRedeemed; } struct Stake { address stakedContractAddress; uint stakedContractIndex; uint dateAdd; uint stakeAmount; uint unlockedAmount; uint burnedAmount; uint unLockableBeforeLastBurn; } struct Staker { address stakerAddress; uint stakerIndex; } struct CoverNote { uint amount; bool isDeposited; } /** * @dev mapping of uw address to array of sc address to fetch * all staked contract address of underwriter, pushing * data into this array of Stake returns stakerIndex */ mapping(address => Stake[]) public stakerStakedContracts; /** * @dev mapping of sc address to array of UW address to fetch * all underwritters of the staked smart contract * pushing data into this mapped array returns scIndex */ mapping(address => Staker[]) public stakedContractStakers; /** * @dev mapping of staked contract Address to the array of StakeCommission * here index of this array is stakedContractIndex */ mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission; mapping(address => uint) public lastCompletedStakeCommission; /** * @dev mapping of the staked contract address to the current * staker index who will receive commission. */ mapping(address => uint) public stakedContractCurrentCommissionIndex; /** * @dev mapping of the staked contract address to the * current staker index to burn token from. */ mapping(address => uint) public stakedContractCurrentBurnIndex; /** * @dev mapping to return true if Cover Note deposited against coverId */ mapping(uint => CoverNote) public depositedCN; mapping(address => uint) internal isBookedTokens; event Commission( address indexed stakedContractAddress, address indexed stakerAddress, uint indexed scIndex, uint commissionAmount ); constructor(address payable _walletAdd) public { walletAddress = _walletAdd; bookTime = 12 hours; joiningFee = 2000000000000000; // 0.002 Ether lockTokenTimeAfterCoverExp = 35 days; scValidDays = 250; lockCADays = 7 days; lockMVDays = 2 days; stakerCommissionPer = 20; stakerMaxCommissionPer = 50; tokenExponent = 4; priceStep = 1000; } /** * @dev Change the wallet address which receive Joining Fee */ function changeWalletAddress(address payable _address) external onlyInternal { walletAddress = _address; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "TOKEXP") { val = tokenExponent; } else if (code == "TOKSTEP") { val = priceStep; } else if (code == "RALOCKT") { val = scValidDays; } else if (code == "RACOMM") { val = stakerCommissionPer; } else if (code == "RAMAXC") { val = stakerMaxCommissionPer; } else if (code == "CABOOKT") { val = bookTime / (1 hours); } else if (code == "CALOCKT") { val = lockCADays / (1 days); } else if (code == "MVLOCKT") { val = lockMVDays / (1 days); } else if (code == "QUOLOCKT") { val = lockTokenTimeAfterCoverExp / (1 days); } else if (code == "JOINFEE") { val = joiningFee; } } /** * @dev Just for interface */ function changeDependentContractAddress() public {//solhint-disable-line } /** * @dev to get the contract staked by a staker * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return the address of staked contract */ function getStakerStakedContractByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (address stakedContractAddress) { stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; } /** * @dev to get the staker's staked burned * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount burned */ function getStakerStakedBurnedByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint burnedAmount) { burnedAmount = stakerStakedContracts[ _stakerAddress][_stakerIndex].burnedAmount; } /** * @dev to get the staker's staked unlockable before the last burn * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return unlockable staked tokens */ function getStakerStakedUnlockableBeforeLastBurnByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint unlockable) { unlockable = stakerStakedContracts[ _stakerAddress][_stakerIndex].unLockableBeforeLastBurn; } /** * @dev to get the staker's staked contract index * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return is the index of the smart contract address */ function getStakerStakedContractIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint scIndex) { scIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; } /** * @dev to get the staker index of the staked contract * @param _stakedContractAddress is the address of the staked contract * @param _stakedContractIndex is the index of staked contract * @return is the index of the staker */ function getStakedContractStakerIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint sIndex) { sIndex = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerIndex; } /** * @dev to get the staker's initial staked amount on the contract * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return staked amount */ function getStakerInitialStakedAmountOnContract( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakeAmount; } /** * @dev to get the staker's staked contract length * @param _stakerAddress is the address of the staker * @return length of staked contract */ function getStakerStakedContractLength( address _stakerAddress ) public view returns (uint length) { length = stakerStakedContracts[_stakerAddress].length; } /** * @dev to get the staker's unlocked tokens which were staked * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount */ function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].unlockedAmount; } /** * @dev pushes the unlocked staked tokens by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount.add(_amount); } /** * @dev pushes the Burned tokens for a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be burned. */ function pushBurnedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount.add(_amount); } /** * @dev pushes the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function pushUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn.add(_amount); } /** * @dev sets the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function setUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = _amount; } /** * @dev pushes the earned commission earned by a staker. * @param _stakerAddress address of staker. * @param _stakedContractAddress address of smart contract. * @param _stakedContractIndex index of the staker to distribute commission. * @param _commissionAmount amount to be given as commission. */ function pushEarnedStakeCommissions( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _commissionAmount ) public onlyInternal { stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex]. commissionEarned = stakedContractStakeCommission[_stakedContractAddress][ _stakedContractIndex].commissionEarned.add(_commissionAmount); emit Commission( _stakerAddress, _stakedContractAddress, _stakedContractIndex, _commissionAmount ); } /** * @dev pushes the redeemed commission redeemed by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushRedeemedStakeCommissions( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { uint stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; address stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; stakedContractStakeCommission[stakedContractAddress][stakedContractIndex]. commissionRedeemed = stakedContractStakeCommission[ stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); } /** * @dev Gets stake commission given to an underwriter * for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets stake commission redeemed by an underwriter * for particular staked contract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. * @return commissionEarned total amount given to staker. */ function getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalEarnedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionEarned) { totalCommissionEarned = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionEarned = totalCommissionEarned. add(_getStakerEarnedStakeCommission(_stakerAddress, i)); } } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalReedmedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionRedeemed) { totalCommissionRedeemed = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionRedeemed = totalCommissionRedeemed.add( _getStakerRedeemedStakeCommission(_stakerAddress, i)); } } /** * @dev set flag to deposit/ undeposit cover note * against a cover Id * @param coverId coverId of Cover * @param flag true/false for deposit/undeposit */ function setDepositCN(uint coverId, bool flag) public onlyInternal { if (flag == true) { require(!depositedCN[coverId].isDeposited, "Cover note already deposited"); } depositedCN[coverId].isDeposited = flag; } /** * @dev set locked cover note amount * against a cover Id * @param coverId coverId of Cover * @param amount amount of nxm to be locked */ function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; } /** * @dev to get the staker address on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @param _stakedContractIndex is the index of staked contract's index * @return address of staker */ function getStakedContractStakerByIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (address stakerAddress) { stakerAddress = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerAddress; } /** * @dev to get the length of stakers on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @return length in concern */ function getStakedContractStakersLength( address _stakedContractAddress ) public view returns (uint length) { length = stakedContractStakers[_stakedContractAddress].length; } /** * @dev Adds a new stake record. * @param _stakerAddress staker address. * @param _stakedContractAddress smart contract address. * @param _amount amountof NXM to be staked. */ function addStake( address _stakerAddress, address _stakedContractAddress, uint _amount ) public onlyInternal returns (uint scIndex) { scIndex = (stakedContractStakers[_stakedContractAddress].push( Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1); stakerStakedContracts[_stakerAddress].push( Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0)); } /** * @dev books the user's tokens for maintaining Assessor Velocity, * i.e. once a token is used to cast a vote as a Claims assessor, * @param _of user's address. */ function bookCATokens(address _of) public onlyInternal { require(!isCATokensBooked(_of), "Tokens already booked"); isBookedTokens[_of] = now.add(bookTime); } /** * @dev to know if claim assessor's tokens are booked or not * @param _of is the claim assessor's address in concern * @return boolean representing the status of tokens booked */ function isCATokensBooked(address _of) public view returns (bool res) { if (now < isBookedTokens[_of]) res = true; } /** * @dev Sets the index which will receive commission. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentCommissionIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index; } /** * @dev Sets the last complete commission index * @param _stakerAddress smart contract address. * @param _index current index. */ function setLastCompletedStakeCommissionIndex( address _stakerAddress, uint _index ) public onlyInternal { lastCompletedStakeCommission[_stakerAddress] = _index; } /** * @dev Sets the index till which commission is distrubuted. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentBurnIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentBurnIndex[_stakedContractAddress] = _index; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "TOKEXP") { _setTokenExponent(val); } else if (code == "TOKSTEP") { _setPriceStep(val); } else if (code == "RALOCKT") { _changeSCValidDays(val); } else if (code == "RACOMM") { _setStakerCommissionPer(val); } else if (code == "RAMAXC") { _setStakerMaxCommissionPer(val); } else if (code == "CABOOKT") { _changeBookTime(val * 1 hours); } else if (code == "CALOCKT") { _changelockCADays(val * 1 days); } else if (code == "MVLOCKT") { _changelockMVDays(val * 1 days); } else if (code == "QUOLOCKT") { _setLockTokenTimeAfterCoverExp(val * 1 days); } else if (code == "JOINFEE") { _setJoiningFee(val); } else { revert("Invalid param code"); } } /** * @dev Internal function to get stake commission given to an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionEarned; } /** * @dev Internal function to get stake commission redeemed by an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionRedeemed; } /** * @dev to set the percentage of staker commission * @param _val is new percentage value */ function _setStakerCommissionPer(uint _val) internal { stakerCommissionPer = _val; } /** * @dev to set the max percentage of staker commission * @param _val is new percentage value */ function _setStakerMaxCommissionPer(uint _val) internal { stakerMaxCommissionPer = _val; } /** * @dev to set the token exponent value * @param _val is new value */ function _setTokenExponent(uint _val) internal { tokenExponent = _val; } /** * @dev to set the price step * @param _val is new value */ function _setPriceStep(uint _val) internal { priceStep = _val; } /** * @dev Changes number of days for which NXM needs to staked in case of underwriting */ function _changeSCValidDays(uint _days) internal { scValidDays = _days; } /** * @dev Changes the time period up to which tokens will be locked. * Used to generate the validity period of tokens booked by * a user for participating in claim's assessment/claim's voting. */ function _changeBookTime(uint _time) internal { bookTime = _time; } /** * @dev Changes lock CA days - number of days for which tokens * are locked while submitting a vote. */ function _changelockCADays(uint _val) internal { lockCADays = _val; } /** * @dev Changes lock MV days - number of days for which tokens are locked * while submitting a vote. */ function _changelockMVDays(uint _val) internal { lockMVDays = _val; } /** * @dev Changes extra lock period for a cover, post its expiry. */ function _setLockTokenTimeAfterCoverExp(uint time) internal { lockTokenTimeAfterCoverExp = time; } /** * @dev Set the joining fee for membership */ function _setJoiningFee(uint _amount) internal { joiningFee = _amount; } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/Iupgradable.sol"; contract QuotationData is Iupgradable { using SafeMath for uint; enum HCIDStatus {NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover} enum CoverStatus {Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested} struct Cover { address payable memberAddress; bytes4 currencyCode; uint sumAssured; uint16 coverPeriod; uint validUntil; address scAddress; uint premiumNXM; } struct HoldCover { uint holdCoverId; address payable userAddress; address scAddress; bytes4 coverCurr; uint[] coverDetails; uint16 coverPeriod; } address public authQuoteEngine; mapping(bytes4 => uint) internal currencyCSA; mapping(address => uint[]) internal userCover; mapping(address => uint[]) public userHoldedCover; mapping(address => bool) public refundEligible; mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd; mapping(uint => uint8) public coverStatus; mapping(uint => uint) public holdedCoverIDStatus; mapping(uint => bool) public timestampRepeated; Cover[] internal allCovers; HoldCover[] internal allCoverHolded; uint public stlp; uint public stl; uint public pm; uint public minDays; uint public tokensRetained; address public kycAuthAddress; event CoverDetailsEvent( uint indexed cid, address scAdd, uint sumAssured, uint expiry, uint premium, uint premiumNXM, bytes4 curr ); event CoverStatusEvent(uint indexed cid, uint8 statusNum); constructor(address _authQuoteAdd, address _kycAuthAdd) public { authQuoteEngine = _authQuoteAdd; kycAuthAddress = _kycAuthAdd; stlp = 90; stl = 100; pm = 30; minDays = 30; tokensRetained = 10; allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0)); uint[] memory arr = new uint[](1); allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0)); } /// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be added. function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be subtracted. function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be subtracted. function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); } /// @dev Adds the amount in Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be added. function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].add(_amount); } /// @dev sets bit for timestamp to avoid replay attacks. function setTimestampRepeated(uint _timestamp) external onlyInternal { timestampRepeated[_timestamp] = true; } /// @dev Creates a blank new cover. function addCover( uint16 _coverPeriod, uint _sumAssured, address payable _userAddress, bytes4 _currencyCode, address _scAddress, uint premium, uint premiumNXM ) external onlyInternal { uint expiryDate = now.add(uint(_coverPeriod).mul(1 days)); allCovers.push(Cover(_userAddress, _currencyCode, _sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM)); uint cid = allCovers.length.sub(1); userCover[_userAddress].push(cid); emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode); } /// @dev create holded cover which will process after verdict of KYC. function addHoldCover( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod ) external onlyInternal { uint holdedCoverLen = allCoverHolded.length; holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending); allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress, coverCurr, coverDetails, coverPeriod)); userHoldedCover[from].push(allCoverHolded.length.sub(1)); } ///@dev sets refund eligible bit. ///@param _add user address. ///@param status indicates if user have pending kyc. function setRefundEligible(address _add, bool status) external onlyInternal { refundEligible[_add] = status; } /// @dev to set current status of particular holded coverID (1 for not completed KYC, /// 2 for KYC passed, 3 for failed KYC or full refunded, /// 4 for KYC completed but cover not processed) function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal { holdedCoverIDStatus[holdedCoverID] = status; } /** * @dev to set address of kyc authentication * @param _add is the new address */ function setKycAuthAddress(address _add) external onlyInternal { kycAuthAddress = _add; } /// @dev Changes authorised address for generating quote off chain. function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "STLP") { val = stlp; } else if (code == "STL") { val = stl; } else if (code == "PM") { val = pm; } else if (code == "QUOMIND") { val = minDays; } else if (code == "QUOTOK") { val = tokensRetained; } } /// @dev Gets Product details. /// @return _minDays minimum cover period. /// @return _PM Profit margin. /// @return _STL short term Load. /// @return _STLP short term load period. function getProductDetails() external view returns ( uint _minDays, uint _pm, uint _stl, uint _stlp ) { _minDays = minDays; _pm = pm; _stl = stl; _stlp = stlp; } /// @dev Gets total number covers created till date. function getCoverLength() external view returns (uint len) { return (allCovers.length); } /// @dev Gets Authorised Engine address. function getAuthQuoteEngine() external view returns (address _add) { _add = authQuoteEngine; } /// @dev Gets the Total Sum Assured amount of a given currency. function getTotalSumAssured(bytes4 _curr) external view returns (uint amount) { amount = currencyCSA[_curr]; } /// @dev Gets all the Cover ids generated by a given address. /// @param _add User's address. /// @return allCover array of covers. function getAllCoversOfUser(address _add) external view returns (uint[] memory allCover) { return (userCover[_add]); } /// @dev Gets total number of covers generated by a given address function getUserCoverLength(address _add) external view returns (uint len) { len = userCover[_add].length; } /// @dev Gets the status of a given cover. function getCoverStatusNo(uint _cid) external view returns (uint8) { return coverStatus[_cid]; } /// @dev Gets the Cover Period (in days) of a given cover. function getCoverPeriod(uint _cid) external view returns (uint32 cp) { cp = allCovers[_cid].coverPeriod; } /// @dev Gets the Sum Assured Amount of a given cover. function getCoverSumAssured(uint _cid) external view returns (uint sa) { sa = allCovers[_cid].sumAssured; } /// @dev Gets the Currency Name in which a given cover is assured. function getCurrencyOfCover(uint _cid) external view returns (bytes4 curr) { curr = allCovers[_cid].currencyCode; } /// @dev Gets the validity date (timestamp) of a given cover. function getValidityOfCover(uint _cid) external view returns (uint date) { date = allCovers[_cid].validUntil; } /// @dev Gets Smart contract address of cover. function getscAddressOfCover(uint _cid) external view returns (uint, address) { return (_cid, allCovers[_cid].scAddress); } /// @dev Gets the owner address of a given cover. function getCoverMemberAddress(uint _cid) external view returns (address payable _add) { _add = allCovers[_cid].memberAddress; } /// @dev Gets the premium amount of a given cover in NXM. function getCoverPremiumNXM(uint _cid) external view returns (uint _premiumNXM) { _premiumNXM = allCovers[_cid].premiumNXM; } /// @dev Provides the details of a cover Id /// @param _cid cover Id /// @return memberAddress cover user address. /// @return scAddress smart contract Address /// @return currencyCode currency of cover /// @return sumAssured sum assured of cover /// @return premiumNXM premium in NXM function getCoverDetailsByCoverID1( uint _cid ) external view returns ( uint cid, address _memberAddress, address _scAddress, bytes4 _currencyCode, uint _sumAssured, uint premiumNXM ) { return ( _cid, allCovers[_cid].memberAddress, allCovers[_cid].scAddress, allCovers[_cid].currencyCode, allCovers[_cid].sumAssured, allCovers[_cid].premiumNXM ); } /// @dev Provides details of a cover Id /// @param _cid cover Id /// @return status status of cover. /// @return sumAssured Sum assurance of cover. /// @return coverPeriod Cover Period of cover (in days). /// @return validUntil is validity of cover. function getCoverDetailsByCoverID2( uint _cid ) external view returns ( uint cid, uint8 status, uint sumAssured, uint16 coverPeriod, uint validUntil ) { return ( _cid, coverStatus[_cid], allCovers[_cid].sumAssured, allCovers[_cid].coverPeriod, allCovers[_cid].validUntil ); } /// @dev Provides details of a holded cover Id /// @param _hcid holded cover Id /// @return scAddress SmartCover address of cover. /// @return coverCurr currency of cover. /// @return coverPeriod Cover Period of cover (in days). function getHoldedCoverDetailsByID1( uint _hcid ) external view returns ( uint hcid, address scAddress, bytes4 coverCurr, uint16 coverPeriod ) { return ( _hcid, allCoverHolded[_hcid].scAddress, allCoverHolded[_hcid].coverCurr, allCoverHolded[_hcid].coverPeriod ); } /// @dev Gets total number holded covers created till date. function getUserHoldedCoverLength(address _add) external view returns (uint) { return userHoldedCover[_add].length; } /// @dev Gets holded cover index by index of user holded covers. function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) { return userHoldedCover[_add][index]; } /// @dev Provides the details of a holded cover Id /// @param _hcid holded cover Id /// @return memberAddress holded cover user address. /// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute. function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails ) { return ( _hcid, allCoverHolded[_hcid].userAddress, allCoverHolded[_hcid].coverDetails ); } /// @dev Gets the Total Sum Assured amount of a given currency and smart contract address. function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; } //solhint-disable-next-line function changeDependentContractAddress() public {} /// @dev Changes the status of a given cover. /// @param _cid cover Id. /// @param _stat New status. function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal { coverStatus[_cid] = _stat; emit CoverStatusEvent(_cid, _stat); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "STLP") { _changeSTLP(val); } else if (code == "STL") { _changeSTL(val); } else if (code == "PM") { _changePM(val); } else if (code == "QUOMIND") { _changeMinDays(val); } else if (code == "QUOTOK") { _setTokensRetained(val); } else { revert("Invalid param code"); } } /// @dev Changes the existing Profit Margin value function _changePM(uint _pm) internal { pm = _pm; } /// @dev Changes the existing Short Term Load Period (STLP) value. function _changeSTLP(uint _stlp) internal { stlp = _stlp; } /// @dev Changes the existing Short Term Load (STL) value. function _changeSTL(uint _stl) internal { stl = _stl; } /// @dev Changes the existing Minimum cover period (in days) function _changeMinDays(uint _days) internal { minDays = _days; } /** * @dev to set the the amount of tokens retained * @param val is the amount retained */ function _setTokensRetained(uint val) internal { tokensRetained = val; } } pragma solidity ^0.5.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface OZIERC20 { 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 ); } pragma solidity ^0.5.0; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library OZSafeMath { /** * @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; } } pragma solidity ^0.5.0; import "./INXMMaster.sol"; contract Iupgradable { INXMMaster public ms; address public nxMasterAddress; modifier onlyInternal { require(ms.isInternal(msg.sender)); _; } modifier isMemberAndcheckPause { require(ms.isPause() == false && ms.isMember(msg.sender) == true); _; } modifier onlyOwner { require(ms.isOwner(msg.sender)); _; } modifier checkPause { require(ms.isPause() == false); _; } modifier isMember { require(ms.isMember(msg.sender), "Not member"); _; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public; /** * @dev change master address * @param _masterAddress is the new address */ function changeMasterAddress(address _masterAddress) public { if (address(ms) != address(0)) { require(address(ms) == msg.sender, "Not master"); } ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } } pragma solidity ^0.5.0; interface IPooledStaking { function accumulateReward(address contractAddress, uint amount) external; function pushBurn(address contractAddress, uint amount) external; function hasPendingActions() external view returns (bool); function processPendingActions(uint maxIterations) external returns (bool finished); function contractStake(address contractAddress) external view returns (uint); function stakerReward(address staker) external view returns (uint); function stakerDeposit(address staker) external view returns (uint); function stakerContractStake(address staker, address contractAddress) external view returns (uint); function withdraw(uint amount) external; function stakerMaxWithdrawable(address stakerAddress) external view returns (uint); function withdrawReward(address stakerAddress) external; } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/Iupgradable.sol"; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); if (_vote == - 1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); if (_vote == - 1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns ( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns ( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns (uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns (uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns (uint voteCount) { return allvotes.length.sub(1); // Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns (uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns (uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns (uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns (uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns (uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns ( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns ( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns (uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns (uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns ( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns (address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns ( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns (uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns (int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns (uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns (address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns (uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns (uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns (uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns ( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns ( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns ( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns ( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns ( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns ( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns (uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns (uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns (uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns (uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns (uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns (int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns (uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns (uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns (uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns ( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns (uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); // 0 Pending-Claim Assessor Vote _pushStatus(0, 0); // 1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); // 2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); // 3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); // 4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); // 5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); // 6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); // 7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); // 8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); // 9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); // 10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); // 11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); // 12 Claim Accepted Payout Pending _pushStatus(0, 0); // 13 Claim Accepted No Payout _pushStatus(0, 0); // 14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } pragma solidity ^0.5.0; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract LockHandler { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; } pragma solidity ^0.5.0; interface LegacyMCR { function addMCRData(uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate) external; function addLastMCRData(uint64 date) external; function changeDependentContractAddress() external; function getAllSumAssurance() external view returns (uint amount); function _calVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp); function calculateStepTokenPrice(bytes4 curr, uint mcrtp) external view returns (uint tokenPrice); function calculateTokenPrice(bytes4 curr) external view returns (uint tokenPrice); function calVtpAndMCRtp() external view returns (uint vtp, uint mcrtp); function calculateVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp); function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) external view returns (uint lowerThreshold, uint upperThreshold); function getMaxSellTokens() external view returns (uint maxTokens); function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val); function updateUintParameters(bytes8 code, uint val) external; function variableMincap() external view returns (uint); function dynamicMincapThresholdx100() external view returns (uint); function dynamicMincapIncrementx100() external view returns (uint); function getLastMCREther() external view returns (uint); } // /* Copyright (C) 2017 GovBlocks.io // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../token/TokenController.sol"; import "./MemberRoles.sol"; import "./ProposalCategory.sol"; import "./external/IGovernance.sol"; contract Governance is IGovernance, Iupgradable { using SafeMath for uint; enum ProposalStatus { Draft, AwaitingSolution, VotingStarted, Accepted, Rejected, Majority_Not_Reached_But_Accepted, Denied } struct ProposalData { uint propStatus; uint finalVerdict; uint category; uint commonIncentive; uint dateUpd; address owner; } struct ProposalVote { address voter; uint proposalId; uint dateAdd; } struct VoteTally { mapping(uint => uint) memberVoteValue; mapping(uint => uint) abVoteValue; uint voters; } struct DelegateVote { address follower; address leader; uint lastUpd; } ProposalVote[] internal allVotes; DelegateVote[] public allDelegation; mapping(uint => ProposalData) internal allProposalData; mapping(uint => bytes[]) internal allProposalSolutions; mapping(address => uint[]) internal allVotesByMember; mapping(uint => mapping(address => bool)) public rewardClaimed; mapping(address => mapping(uint => uint)) public memberProposalVote; mapping(address => uint) public followerDelegation; mapping(address => uint) internal followerCount; mapping(address => uint[]) internal leaderDelegation; mapping(uint => VoteTally) public proposalVoteTally; mapping(address => bool) public isOpenForDelegation; mapping(address => uint) public lastRewardClaimed; bool internal constructorCheck; uint public tokenHoldingTime; uint internal roleIdAllowedToCatgorize; uint internal maxVoteWeigthPer; uint internal specialResolutionMajPerc; uint internal maxFollowers; uint internal totalProposals; uint internal maxDraftTime; MemberRoles internal memberRole; ProposalCategory internal proposalCategory; TokenController internal tokenInstance; mapping(uint => uint) public proposalActionStatus; mapping(uint => uint) internal proposalExecutionTime; mapping(uint => mapping(address => bool)) public proposalRejectedByAB; mapping(uint => uint) internal actionRejectedCount; bool internal actionParamsInitialised; uint internal actionWaitingTime; uint constant internal AB_MAJ_TO_REJECT_ACTION = 3; enum ActionStatus { Pending, Accepted, Rejected, Executed, NoAction } /** * @dev Called whenever an action execution is failed. */ event ActionFailed ( uint256 proposalId ); /** * @dev Called whenever an AB member rejects the action execution. */ event ActionRejected ( uint256 indexed proposalId, address rejectedBy ); /** * @dev Checks if msg.sender is proposal owner */ modifier onlyProposalOwner(uint _proposalId) { require(msg.sender == allProposalData[_proposalId].owner, "Not allowed"); _; } /** * @dev Checks if proposal is opened for voting */ modifier voteNotStarted(uint _proposalId) { require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)); _; } /** * @dev Checks if msg.sender is allowed to create proposal under given category */ modifier isAllowed(uint _categoryId) { require(allowedToCreateProposal(_categoryId), "Not allowed"); _; } /** * @dev Checks if msg.sender is allowed categorize proposal under given category */ modifier isAllowedToCategorize() { require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed"); _; } /** * @dev Checks if msg.sender had any pending rewards to be claimed */ modifier checkPendingRewards { require(getPendingReward(msg.sender) == 0, "Claim reward"); _; } /** * @dev Event emitted whenever a proposal is categorized */ event ProposalCategorized( uint indexed proposalId, address indexed categorizedBy, uint categoryId ); /** * @dev Removes delegation of an address. * @param _add address to undelegate. */ function removeDelegation(address _add) external onlyInternal { _unDelegate(_add); } /** * @dev Creates a new proposal * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective */ function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external isAllowed(_categoryId) { require(ms.isMember(msg.sender), "Not Member"); _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); } /** * @dev Edits the details of an existing proposal * @param _proposalId Proposal id that details needs to be updated * @param _proposalDescHash Proposal description hash having long and short description of proposal. */ function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external onlyProposalOwner(_proposalId) { require( allProposalSolutions[_proposalId].length < 2, "Not allowed" ); allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft); allProposalData[_proposalId].category = 0; allProposalData[_proposalId].commonIncentive = 0; emit Proposal( allProposalData[_proposalId].owner, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); } /** * @dev Categorizes proposal to proceed further. Categories shows the proposal objective. */ function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) external voteNotStarted(_proposalId) isAllowedToCategorize { _categorizeProposal(_proposalId, _categoryId, _incentive); } /** * @dev Submit proposal with solution * @param _proposalId Proposal id * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external onlyProposalOwner(_proposalId) { require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution)); _proposalSubmission(_proposalId, _solutionHash, _action); } /** * @dev Creates a new proposal with solution * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external isAllowed(_categoryId) { uint proposalId = totalProposals; _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); require(_categoryId > 0); _proposalSubmission( proposalId, _solutionHash, _action ); } /** * @dev Submit a vote on the proposal. * @param _proposalId to vote upon. * @param _solutionChosen is the chosen vote. */ function submitVote(uint _proposalId, uint _solutionChosen) external { require(allProposalData[_proposalId].propStatus == uint(Governance.ProposalStatus.VotingStarted), "Not allowed"); require(_solutionChosen < allProposalSolutions[_proposalId].length); _submitVote(_proposalId, _solutionChosen); } /** * @dev Closes the proposal. * @param _proposalId of proposal to be closed. */ function closeProposal(uint _proposalId) external { uint category = allProposalData[_proposalId].category; uint _memberRole; if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now && allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } else { require(canCloseProposal(_proposalId) == 1); (, _memberRole,,,,,) = proposalCategory.category(allProposalData[_proposalId].category); if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) { _closeAdvisoryBoardVote(_proposalId, category); } else { _closeMemberVote(_proposalId, category); } } } /** * @dev Claims reward for member. * @param _memberAddress to claim reward of. * @param _maxRecords maximum number of records to claim reward for. _proposals list of proposals of which reward will be claimed. * @return amount of pending reward. */ function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward) { uint voteId; address leader; uint lastUpd; require(msg.sender == ms.getLatestAddress("CR")); uint delegationId = followerDelegation[_memberAddress]; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; uint totalVotes = allVotesByMember[leader].length; uint lastClaimed = totalVotes; uint j; uint i; for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) { voteId = allVotesByMember[leader][i]; proposalId = allVotes[voteId].proposalId; if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) { if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { if (!rewardClaimed[voteId][_memberAddress]) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); rewardClaimed[voteId][_memberAddress] = true; j++; } } else { if (lastClaimed == totalVotes) { lastClaimed = i; } } } } if (lastClaimed == totalVotes) { lastRewardClaimed[_memberAddress] = i; } else { lastRewardClaimed[_memberAddress] = lastClaimed; } if (j > 0) { emit RewardClaimed( _memberAddress, pendingDAppReward ); } } /** * @dev Sets delegation acceptance status of individual user * @param _status delegation acceptance status */ function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards { isOpenForDelegation[msg.sender] = _status; } /** * @dev Delegates vote to an address. * @param _add is the address to delegate vote to. */ function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards { require(ms.masterInitialized()); require(allDelegation[followerDelegation[_add]].leader == address(0)); if (followerDelegation[msg.sender] > 0) { require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now); } require(!alreadyDelegated(msg.sender)); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner))); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard))); require(followerCount[_add] < maxFollowers); if (allVotesByMember[msg.sender].length > 0) { require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime) < now); } require(ms.isMember(_add)); require(isOpenForDelegation[_add]); allDelegation.push(DelegateVote(msg.sender, _add, now)); followerDelegation[msg.sender] = allDelegation.length - 1; leaderDelegation[_add].push(allDelegation.length - 1); followerCount[_add]++; lastRewardClaimed[msg.sender] = allVotesByMember[_add].length; } /** * @dev Undelegates the sender */ function unDelegate() external isMemberAndcheckPause checkPendingRewards { _unDelegate(msg.sender); } /** * @dev Triggers action of accepted proposal after waiting time is finished */ function triggerAction(uint _proposalId) external { require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger"); _triggerAction(_proposalId, allProposalData[_proposalId].category); } /** * @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious */ function rejectAction(uint _proposalId) external { require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now); require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted)); require(!proposalRejectedByAB[_proposalId][msg.sender]); require( keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category)) != keccak256(abi.encodeWithSignature("swapABMember(address,address)")) ); proposalRejectedByAB[_proposalId][msg.sender] = true; actionRejectedCount[_proposalId]++; emit ActionRejected(_proposalId, msg.sender); if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) { proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected); } } /** * @dev Sets intial actionWaitingTime value * To be called after governance implementation has been updated */ function setInitialActionParameters() external onlyOwner { require(!actionParamsInitialised); actionParamsInitialised = true; actionWaitingTime = 24 * 1 hours; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "GOVHOLD") { val = tokenHoldingTime / (1 days); } else if (code == "MAXFOL") { val = maxFollowers; } else if (code == "MAXDRFT") { val = maxDraftTime / (1 days); } else if (code == "EPTIME") { val = ms.pauseTime() / (1 days); } else if (code == "ACWT") { val = actionWaitingTime / (1 hours); } } /** * @dev Gets all details of a propsal * @param _proposalId whose details we want * @return proposalId * @return category * @return status * @return finalVerdict * @return totalReward */ function proposal(uint _proposalId) external view returns ( uint proposalId, uint category, uint status, uint finalVerdict, uint totalRewar ) { return ( _proposalId, allProposalData[_proposalId].category, allProposalData[_proposalId].propStatus, allProposalData[_proposalId].finalVerdict, allProposalData[_proposalId].commonIncentive ); } /** * @dev Gets some details of a propsal * @param _proposalId whose details we want * @return proposalId * @return number of all proposal solutions * @return amount of votes */ function proposalDetails(uint _proposalId) external view returns (uint, uint, uint) { return ( _proposalId, allProposalSolutions[_proposalId].length, proposalVoteTally[_proposalId].voters ); } /** * @dev Gets solution action on a proposal * @param _proposalId whose details we want * @param _solution whose details we want * @return action of a solution on a proposal */ function getSolutionAction(uint _proposalId, uint _solution) external view returns (uint, bytes memory) { return ( _solution, allProposalSolutions[_proposalId][_solution] ); } /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns (uint) { return totalProposals; } /** * @dev Get followers of an address * @return get followers of an address */ function getFollowers(address _add) external view returns (uint[] memory) { return leaderDelegation[_add]; } /** * @dev Gets pending rewards of a member * @param _memberAddress in concern * @return amount of pending reward */ function getPendingReward(address _memberAddress) public view returns (uint pendingDAppReward) { uint delegationId = followerDelegation[_memberAddress]; address leader; uint lastUpd; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) { if (allVotes[allVotesByMember[leader][i]].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) { if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) { proposalId = allVotes[allVotesByMember[leader][i]].proposalId; if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); } } } } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "GOVHOLD") { tokenHoldingTime = val * 1 days; } else if (code == "MAXFOL") { maxFollowers = val; } else if (code == "MAXDRFT") { maxDraftTime = val * 1 days; } else if (code == "EPTIME") { ms.updatePauseTime(val * 1 days); } else if (code == "ACWT") { actionWaitingTime = val * 1 hours; } else { revert("Invalid code"); } } /** * @dev Updates all dependency addresses to latest ones from Master */ function changeDependentContractAddress() public { tokenInstance = TokenController(ms.dAppLocker()); memberRole = MemberRoles(ms.getLatestAddress("MR")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Checks if msg.sender is allowed to create a proposal under given category */ function allowedToCreateProposal(uint category) public view returns (bool check) { if (category == 0) return true; uint[] memory mrAllowed; (,,,, mrAllowed,,) = proposalCategory.category(category); for (uint i = 0; i < mrAllowed.length; i++) { if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i])) return true; } } /** * @dev Checks if an address is already delegated * @param _add in concern * @return bool value if the address is delegated or not */ function alreadyDelegated(address _add) public view returns (bool delegated) { for (uint i = 0; i < leaderDelegation[_add].length; i++) { if (allDelegation[leaderDelegation[_add][i]].leader == _add) { return true; } } } /** * @dev Checks If the proposal voting time is up and it's ready to close * i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise! * @param _proposalId Proposal id to which closing value is being checked */ function canCloseProposal(uint _proposalId) public view returns (uint) { uint dateUpdate; uint pStatus; uint _closingTime; uint _roleId; uint majority; pStatus = allProposalData[_proposalId].propStatus; dateUpdate = allProposalData[_proposalId].dateUpd; (, _roleId, majority, , , _closingTime,) = proposalCategory.category(allProposalData[_proposalId].category); if ( pStatus == uint(ProposalStatus.VotingStarted) ) { uint numberOfMembers = memberRole.numberOfMembers(_roleId); if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers || dateUpdate.add(_closingTime) <= now) { return 1; } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters || dateUpdate.add(_closingTime) <= now) return 1; } } else if (pStatus > uint(ProposalStatus.VotingStarted)) { return 2; } else { return 0; } } /** * @dev Gets Id of member role allowed to categorize the proposal * @return roleId allowed to categorize the proposal */ function allowedToCatgorize() public view returns (uint roleId) { return roleIdAllowedToCatgorize; } /** * @dev Gets vote tally data * @param _proposalId in concern * @param _solution of a proposal id * @return member vote value * @return advisory board vote value * @return amount of votes */ function voteTallyData(uint _proposalId, uint _solution) public view returns (uint, uint, uint) { return (proposalVoteTally[_proposalId].memberVoteValue[_solution], proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters); } /** * @dev Internal call to create proposal * @param _proposalTitle of proposal * @param _proposalSD is short description of proposal * @param _proposalDescHash IPFS hash value of propsal * @param _categoryId of proposal */ function _createProposal( string memory _proposalTitle, string memory _proposalSD, string memory _proposalDescHash, uint _categoryId ) internal { require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0); uint _proposalId = totalProposals; allProposalData[_proposalId].owner = msg.sender; allProposalData[_proposalId].dateUpd = now; allProposalSolutions[_proposalId].push(""); totalProposals++; emit Proposal( msg.sender, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); if (_categoryId > 0) _categorizeProposal(_proposalId, _categoryId, 0); } /** * @dev Internal call to categorize a proposal * @param _proposalId of proposal * @param _categoryId of proposal * @param _incentive is commonIncentive */ function _categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) internal { require( _categoryId > 0 && _categoryId < proposalCategory.totalCategories(), "Invalid category" ); allProposalData[_proposalId].category = _categoryId; allProposalData[_proposalId].commonIncentive = _incentive; allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution); emit ProposalCategorized(_proposalId, msg.sender, _categoryId); } /** * @dev Internal call to add solution to a proposal * @param _proposalId in concern * @param _action on that solution * @param _solutionHash string value */ function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash) internal { allProposalSolutions[_proposalId].push(_action); emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now); } /** * @dev Internal call to add solution and open proposal for voting */ function _proposalSubmission( uint _proposalId, string memory _solutionHash, bytes memory _action ) internal { uint _categoryId = allProposalData[_proposalId].category; if (proposalCategory.categoryActionHashes(_categoryId).length == 0) { require(keccak256(_action) == keccak256("")); proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } _addSolution( _proposalId, _action, _solutionHash ); _updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted)); (, , , , , uint closingTime,) = proposalCategory.category(_categoryId); emit CloseProposalOnTime(_proposalId, closingTime.add(now)); } /** * @dev Internal call to submit vote * @param _proposalId of proposal in concern * @param _solution for that proposal */ function _submitVote(uint _proposalId, uint _solution) internal { uint delegationId = followerDelegation[msg.sender]; uint mrSequence; uint majority; uint closingTime; (, mrSequence, majority, , , closingTime,) = proposalCategory.category(allProposalData[_proposalId].category); require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed"); require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed"); require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) && _checkLastUpd(allDelegation[delegationId].lastUpd))); require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized"); uint totalVotes = allVotes.length; allVotesByMember[msg.sender].push(totalVotes); memberProposalVote[msg.sender][_proposalId] = totalVotes; allVotes.push(ProposalVote(msg.sender, _proposalId, now)); emit Vote(msg.sender, _proposalId, totalVotes, now, _solution); if (mrSequence == uint(MemberRoles.Role.Owner)) { if (_solution == 1) _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner); else _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } else { uint numberOfMembers = memberRole.numberOfMembers(mrSequence); _setVoteTally(_proposalId, _solution, mrSequence); if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) { emit VoteCast(_proposalId); } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters) emit VoteCast(_proposalId); } } } /** * @dev Internal call to set vote tally of a proposal * @param _proposalId of proposal in concern * @param _solution of proposal in concern * @param mrSequence number of members for a role */ function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal { uint categoryABReq; uint isSpecialResolution; (, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category); if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) || mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { proposalVoteTally[_proposalId].abVoteValue[_solution]++; } tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime); if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) { uint voteWeight; uint voters = 1; uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender); uint totalSupply = tokenInstance.totalSupply(); if (isSpecialResolution == 1) { voteWeight = tokenBalance.add(10 ** 18); } else { voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18); } DelegateVote memory delegationData; for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) { delegationData = allDelegation[leaderDelegation[msg.sender][i]]; if (delegationData.leader == msg.sender && _checkLastUpd(delegationData.lastUpd)) { if (memberRole.checkRole(delegationData.follower, mrSequence)) { tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower); tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime); voters++; if (isSpecialResolution == 1) { voteWeight = voteWeight.add(tokenBalance.add(10 ** 18)); } else { voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18)); } } } } proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight); proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters; } } /** * @dev Gets minimum of two numbers * @param a one of the two numbers * @param b one of the two numbers * @return minimum number out of the two */ function _minOf(uint a, uint b) internal pure returns (uint res) { res = a; if (res > b) res = b; } /** * @dev Check the time since last update has exceeded token holding time or not * @param _lastUpd is last update time * @return the bool which tells if the time since last update has exceeded token holding time or not */ function _checkLastUpd(uint _lastUpd) internal view returns (bool) { return (now - _lastUpd) > tokenHoldingTime; } /** * @dev Checks if the vote count against any solution passes the threshold value or not. */ function _checkForThreshold(uint _proposalId, uint _category) internal view returns (bool check) { uint categoryQuorumPerc; uint roleAuthorized; (, roleAuthorized, , categoryQuorumPerc, , ,) = proposalCategory.category(_category); check = ((proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1])) .mul(100)) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18) ) ) >= categoryQuorumPerc; } /** * @dev Called when vote majority is reached * @param _proposalId of proposal in concern * @param _status of proposal in concern * @param category of proposal in concern * @param max vote value of proposal in concern */ function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal { allProposalData[_proposalId].finalVerdict = max; _updateProposalStatus(_proposalId, _status); emit ProposalAccepted(_proposalId); if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) { if (role == MemberRoles.Role.AdvisoryBoard) { _triggerAction(_proposalId, category); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); proposalExecutionTime[_proposalId] = actionWaitingTime.add(now); } } } /** * @dev Internal function to trigger action of accepted proposal */ function _triggerAction(uint _proposalId, uint _categoryId) internal { proposalActionStatus[_proposalId] = uint(ActionStatus.Executed); bytes2 contractName; address actionAddress; bytes memory _functionHash; (, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId); if (contractName == "MS") { actionAddress = address(ms); } else if (contractName != "EX") { actionAddress = ms.getLatestAddress(contractName); } // solhint-disable-next-line avoid-low-level-calls (bool actionStatus,) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1])); if (actionStatus) { emit ActionSuccess(_proposalId); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); emit ActionFailed(_proposalId); } } /** * @dev Internal call to update proposal status * @param _proposalId of proposal in concern * @param _status of proposal to set */ function _updateProposalStatus(uint _proposalId, uint _status) internal { if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) { proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } allProposalData[_proposalId].dateUpd = now; allProposalData[_proposalId].propStatus = _status; } /** * @dev Internal call to undelegate a follower * @param _follower is address of follower to undelegate */ function _unDelegate(address _follower) internal { uint followerId = followerDelegation[_follower]; if (followerId > 0) { followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1); allDelegation[followerId].leader = address(0); allDelegation[followerId].lastUpd = now; lastRewardClaimed[_follower] = allVotesByMember[_follower].length; } } /** * @dev Internal call to close member voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeMemberVote(uint _proposalId, uint category) internal { uint isSpecialResolution; uint abMaj; (, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category); if (isSpecialResolution == 1) { uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18) )); if (acceptedVotePerc >= specialResolutionMajPerc) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } else { if (_checkForThreshold(_proposalId, category)) { uint majorityVote; (,, majorityVote,,,,) = proposalCategory.category(category); if ( ((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)) .div(proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1]) )) >= majorityVote ) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } } else { if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } if (proposalVoteTally[_proposalId].voters > 0) { tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive); } } /** * @dev Internal call to close advisory board voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard; (,, _majorityVote,,,,) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/MasterAware.sol"; import "../cover/QuotationData.sol"; import "./NXMToken.sol"; import "./TokenController.sol"; import "./TokenData.sol"; contract TokenFunctions is MasterAware { using SafeMath for uint; TokenController public tc; NXMToken public tk; QuotationData public qd; event BurnCATokens(uint claimId, address addr, uint amount); /** * @dev to get the all the cover locked tokens of a user * @param _of is the user address in concern * @return amount locked */ function getUserAllLockedCNTokens(address _of) external view returns (uint) { uint[] memory coverIds = qd.getAllCoversOfUser(_of); uint total; for (uint i = 0; i < coverIds.length; i++) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverIds[i])); uint coverNote = tc.tokensLocked(_of, reason); total = total.add(coverNote); } return total; } /** * @dev Change Dependent Contract Address */ function changeDependentContractAddress() public { tc = TokenController(master.getLatestAddress("TC")); tk = NXMToken(master.tokenAddress()); qd = QuotationData(master.getLatestAddress("QD")); } /** * @dev Burns tokens used for fraudulent voting against a claim * @param claimid Claim Id. * @param _value number of tokens to be burned * @param _of Claim Assessor's address. */ function burnCAToken(uint claimid, uint _value, address _of) external onlyGovernance { tc.burnLockedTokens(_of, "CLA", _value); emit BurnCATokens(claimid, _of, _value); } /** * @dev to check if a member is locked for member vote * @param _of is the member address in concern * @return the boolean status */ function isLockedForMemberVote(address _of) public view returns (bool) { return now < tk.isLockedForMV(_of); } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "../capital/Pool.sol"; import "../claims/ClaimsReward.sol"; import "../token/NXMToken.sol"; import "../token/TokenController.sol"; import "../token/TokenFunctions.sol"; import "./ClaimsData.sol"; import "./Incidents.sol"; contract Claims is Iupgradable { using SafeMath for uint; TokenController internal tc; ClaimsReward internal cr; Pool internal p1; ClaimsData internal cd; TokenData internal td; QuotationData internal qd; Incidents internal incidents; uint private constant DECIMAL1E18 = uint(10) ** 18; /** * @dev Sets the status of claim using claim id. * @param claimId claim id. * @param stat status to be set. */ function setClaimStatus(uint claimId, uint stat) external onlyInternal { _setClaimStatus(claimId, stat); } /** * @dev Calculates total amount that has been used to assess a claim. * Computaion:Adds acceptCA(tokens used for voting in favor of a claim) * denyCA(tokens used for voting against a claim) * current token price. * @param claimId Claim Id. * @param member Member type 0 -> Claim Assessors, else members. * @return tokens Total Amount used in Claims assessment. */ function getCATokens(uint claimId, uint member) external view returns (uint tokens) { uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 currency = qd.getCurrencyOfCover(coverId); address asset = cr.getCurrencyAssetAddress(currency); uint tokenx1e18 = p1.getTokenPrice(asset); uint accept; uint deny; if (member == 0) { (, accept, deny) = cd.getClaimsTokenCA(claimId); } else { (, accept, deny) = cd.getClaimsTokenMV(claimId); } tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens) } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); p1 = Pool(ms.getLatestAddress("P1")); cr = ClaimsReward(ms.getLatestAddress("CR")); cd = ClaimsData(ms.getLatestAddress("CD")); qd = QuotationData(ms.getLatestAddress("QD")); incidents = Incidents(ms.getLatestAddress("IC")); } /** * @dev Submits a claim for a given cover note. * Adds claim to queue incase of emergency pause else directly submits the claim. * @param coverId Cover Id. */ function submitClaim(uint coverId) external { _submitClaim(coverId, msg.sender); } function submitClaimForMember(uint coverId, address member) external onlyInternal { _submitClaim(coverId, member); } function _submitClaim(uint coverId, address member) internal { require(!ms.isPause(), "Claims: System is paused"); (/* id */, address contractAddress) = qd.getscAddressOfCover(coverId); address token = incidents.coveredToken(contractAddress); require(token == address(0), "Claims: Product type does not allow claims"); address coverOwner = qd.getCoverMemberAddress(coverId); require(coverOwner == member, "Claims: Not cover owner"); uint expirationDate = qd.getValidityOfCover(coverId); uint gracePeriod = tc.claimSubmissionGracePeriod(); require(expirationDate.add(gracePeriod) > now, "Claims: Grace period has expired"); tc.markCoverClaimOpen(coverId); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted)); uint claimId = cd.actualClaimLength(); cd.addClaim(claimId, coverId, coverOwner, now); cd.callClaimEvent(coverId, coverOwner, claimId, now); } // solhint-disable-next-line no-empty-blocks function submitClaimAfterEPOff() external pure {} /** * @dev Castes vote for members who have tokens locked under Claims Assessment * @param claimId claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict); uint voteLength = cd.getAllVoteLength(); cd.addClaimVoteCA(claimId, voteLength); cd.setUserClaimVoteCA(msg.sender, claimId, voteLength); cd.setClaimTokensCA(claimId, verdict, tokens); tc.extendLockOf(msg.sender, "CLA", td.lockCADays()); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Submits a member vote for assessing a claim. * Tokens other than those locked under Claims * Assessment can be used to cast a vote for a given claim id. * @param claimId Selected claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); uint stat; uint tokens = tc.totalBalanceOf(msg.sender); (, stat) = cd.getClaimStatusNumber(claimId); require(stat >= 1 && stat <= 5); require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict); tc.lockForMemberVote(msg.sender, td.lockMVDays()); uint voteLength = cd.getAllVoteLength(); cd.addClaimVotemember(claimId, voteLength); cd.setUserClaimVoteMember(msg.sender, claimId, voteLength); cd.setClaimTokensMV(claimId, verdict, tokens); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } // solhint-disable-next-line no-empty-blocks function pauseAllPendingClaimsVoting() external pure {} // solhint-disable-next-line no-empty-blocks function startAllPendingClaimsVoting() external pure {} /** * @dev Checks if voting of a claim should be closed or not. * @param claimId Claim Id. * @return close 1 -> voting should be closed, 0 -> if voting should not be closed, * -1 -> voting has already been closed. */ function checkVoteClosing(uint claimId) public view returns (int8 close) { close = 0; uint status; (, status) = cd.getClaimStatusNumber(claimId); uint dateUpd = cd.getClaimDateUpd(claimId); if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) { if (cd.getClaimState12Count(claimId) < 60) close = 1; } if (status > 5 && status != 12) { close = - 1; } else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) { close = 1; } else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) { close = 0; } else if (status == 0 || (status >= 1 && status <= 5)) { close = _checkVoteClosingFinal(claimId, status); } } /** * @dev Checks if voting of a claim should be closed or not. * Internally called by checkVoteClosing method * for Claims whose status number is 0 or status number lie between 2 and 6. * @param claimId Claim Id. * @param status Current status of claim. * @return close 1 if voting should be closed,0 in case voting should not be closed, * -1 if voting has already been closed. */ function _checkVoteClosingFinal(uint claimId, uint status) internal view returns (int8 close) { close = 0; uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 currency = qd.getCurrencyOfCover(coverId); address asset = cr.getCurrencyAssetAddress(currency); uint tokenx1e18 = p1.getTokenPrice(asset); uint accept; uint deny; (, accept, deny) = cd.getClaimsTokenCA(claimId); uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); (, accept, deny) = cd.getClaimsTokenMV(claimId); uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); if (status == 0 && caTokens >= sumassured.mul(10)) { close = 1; } else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) { close = 1; } } /** * @dev Changes the status of an existing claim id, based on current * status and current conditions of the system * @param claimId Claim Id. * @param stat status number. */ function _setClaimStatus(uint claimId, uint stat) internal { uint origstat; uint state12Count; uint dateUpd; uint coverId; (, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId); (, origstat) = cd.getClaimStatusNumber(claimId); if (stat == 12 && origstat == 12) { cd.updateState12Count(claimId, 1); } cd.setClaimStatus(claimId, stat); if (state12Count >= 60 && stat == 12) { cd.setClaimStatus(claimId, 13); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied)); } cd.setClaimdateUpd(claimId, now); } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "../claims/ClaimsReward.sol"; import "../cover/QuotationData.sol"; import "../token/TokenController.sol"; import "../token/TokenData.sol"; import "../token/TokenFunctions.sol"; import "./Governance.sol"; import "./external/Governed.sol"; contract MemberRoles is Governed, Iupgradable { TokenController public tc; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; TokenFunctions internal tf; NXMToken public tk; struct MemberRoleDetails { uint memberCounter; mapping(address => bool) memberActive; address[] memberAddress; address authorized; } enum Role {UnAssigned, AdvisoryBoard, Member, Owner} event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription); event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp); event ClaimPayoutAddressSet(address indexed member, address indexed payoutAddress); MemberRoleDetails[] internal memberRoleData; bool internal constructorCheck; uint public maxABCount; bool public launched; uint public launchedOn; mapping (address => address payable) internal claimPayoutAddress; modifier checkRoleAuthority(uint _memberRoleId) { if (memberRoleData[_memberRoleId].authorized != address(0)) require(msg.sender == memberRoleData[_memberRoleId].authorized); else require(isAuthorizedToGovern(msg.sender), "Not Authorized"); _; } /** * @dev to swap advisory board member * @param _newABAddress is address of new AB member * @param _removeAB is advisory board member to be removed */ function swapABMember( address _newABAddress, address _removeAB ) external checkRoleAuthority(uint(Role.AdvisoryBoard)) { _updateRole(_newABAddress, uint(Role.AdvisoryBoard), true); _updateRole(_removeAB, uint(Role.AdvisoryBoard), false); } /** * @dev to swap the owner address * @param _newOwnerAddress is the new owner address */ function swapOwner( address _newOwnerAddress ) external { require(msg.sender == address(ms)); _updateRole(ms.owner(), uint(Role.Owner), false); _updateRole(_newOwnerAddress, uint(Role.Owner), true); } /** * @dev is used to add initital advisory board members * @param abArray is the list of initial advisory board members */ function addInitialABMembers(address[] calldata abArray) external onlyOwner { //Ensure that NXMaster has initialized. require(ms.masterInitialized()); require(maxABCount >= SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length) ); //AB count can't exceed maxABCount for (uint i = 0; i < abArray.length; i++) { require(checkRole(abArray[i], uint(MemberRoles.Role.Member))); _updateRole(abArray[i], uint(Role.AdvisoryBoard), true); } } /** * @dev to change max number of AB members allowed * @param _val is the new value to be set */ function changeMaxABCount(uint _val) external onlyInternal { maxABCount = _val; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { td = TokenData(ms.getLatestAddress("TD")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); tf = TokenFunctions(ms.getLatestAddress("TF")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); } /** * @dev to change the master address * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) { require(masterAddress == msg.sender); } masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev to initiate the member roles * @param _firstAB is the address of the first AB member * @param memberAuthority is the authority (role) of the member */ function memberRolesInitiate(address _firstAB, address memberAuthority) public { require(!constructorCheck); _addInitialMemberRoles(_firstAB, memberAuthority); constructorCheck = true; } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole(//solhint-disable-line bytes32 _roleName, string memory _roleDescription, address _authorized ) public onlyAuthorizedToGovern { _addRole(_roleName, _roleDescription, _authorized); } /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole(//solhint-disable-line address _memberAddress, uint _roleId, bool _active ) public checkRoleAuthority(_roleId) { _updateRole(_memberAddress, _roleId, _active); } /** * @dev to add members before launch * @param userArray is list of addresses of members * @param tokens is list of tokens minted for each array element */ function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner { require(!launched); for (uint i = 0; i < userArray.length; i++) { require(!ms.isMember(userArray[i])); tc.addToWhitelist(userArray[i]); _updateRole(userArray[i], uint(Role.Member), true); tc.mint(userArray[i], tokens[i]); } launched = true; launchedOn = now; } /** * @dev Called by user to pay joining membership fee */ function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); tc.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } } /** * @dev to perform kyc verdict * @param _userAddress whose kyc is being performed * @param verdict of kyc process */ function kycVerdict(address payable _userAddress, bool verdict) public { require(msg.sender == qd.kycAuthAddress()); require(!ms.isPause()); require(_userAddress != address(0)); require(!ms.isMember(_userAddress)); require(qd.refundEligible(_userAddress)); if (verdict) { qd.setRefundEligible(_userAddress, false); uint fee = td.joiningFee(); tc.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(fee); // solhint-disable-line } else { qd.setRefundEligible(_userAddress, false); _userAddress.transfer(td.joiningFee()); // solhint-disable-line } } /** * @dev withdraws membership for msg.sender if currently a member. */ function withdrawMembership() public { require(!ms.isPause() && ms.isMember(msg.sender)); require(tc.totalLockedBalance(msg.sender) == 0); // solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). gv.removeDelegation(msg.sender); tc.burnFrom(msg.sender, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); tc.removeFromWhitelist(msg.sender); // need clarification on whitelist if (claimPayoutAddress[msg.sender] != address(0)) { claimPayoutAddress[msg.sender] = address(0); emit ClaimPayoutAddressSet(msg.sender, address(0)); } } /** * @dev switches membership for msg.sender to the specified address. * @param newAddress address of user to forward membership. */ function switchMembership(address newAddress) external { _switchMembership(msg.sender, newAddress); tk.transferFrom(msg.sender, newAddress, tk.balanceOf(msg.sender)); } function switchMembershipOf(address member, address newAddress) external onlyInternal { _switchMembership(member, newAddress); } /** * @dev switches membership for member to the specified address. * @param newAddress address of user to forward membership. */ function _switchMembership(address member, address newAddress) internal { require(!ms.isPause() && ms.isMember(member) && !ms.isMember(newAddress)); require(tc.totalLockedBalance(member) == 0); // solhint-disable-line require(!tf.isLockedForMemberVote(member)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(member) == 0); // No pending reward to be claimed(claim assesment). gv.removeDelegation(member); tc.addToWhitelist(newAddress); _updateRole(newAddress, uint(Role.Member), true); _updateRole(member, uint(Role.Member), false); tc.removeFromWhitelist(member); address payable previousPayoutAddress = claimPayoutAddress[member]; if (previousPayoutAddress != address(0)) { address payable storedAddress = previousPayoutAddress == newAddress ? address(0) : previousPayoutAddress; claimPayoutAddress[member] = address(0); claimPayoutAddress[newAddress] = storedAddress; // emit event for old address reset emit ClaimPayoutAddressSet(member, address(0)); if (storedAddress != address(0)) { // emit event for setting the payout address on the new member address if it's non zero emit ClaimPayoutAddressSet(newAddress, storedAddress); } } emit switchedMembership(member, newAddress, now); } function getClaimPayoutAddress(address payable _member) external view returns (address payable) { address payable payoutAddress = claimPayoutAddress[_member]; return payoutAddress != address(0) ? payoutAddress : _member; } function setClaimPayoutAddress(address payable _address) external { require(!ms.isPause(), "system is paused"); require(ms.isMember(msg.sender), "sender is not a member"); require(_address != msg.sender, "should be different than the member address"); claimPayoutAddress[msg.sender] = _address; emit ClaimPayoutAddressSet(msg.sender, _address); } /// @dev Return number of member roles function totalRoles() public view returns (uint256) {//solhint-disable-line return memberRoleData.length; } /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _newAuthorized New authorized address against role id function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) {//solhint-disable-line memberRoleData[_roleId].authorized = _newAuthorized; } /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line uint length = memberRoleData[_memberRoleId].memberAddress.length; uint i; uint j = 0; memberArray = new address[](memberRoleData[_memberRoleId].memberCounter); for (i = 0; i < length; i++) { address member = memberRoleData[_memberRoleId].memberAddress[i]; if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) {//solhint-disable-line memberArray[j] = member; j++; } } return (_memberRoleId, memberArray); } /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberCounter Member length function numberOfMembers(uint _memberRoleId) public view returns (uint) {//solhint-disable-line return memberRoleData[_memberRoleId].memberCounter; } /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns (address) {//solhint-disable-line return memberRoleData[_memberRoleId].authorized; } /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line uint length = memberRoleData.length; uint[] memory assignedRoles = new uint[](length); uint counter = 0; for (uint i = 1; i < length; i++) { if (memberRoleData[i].memberActive[_memberAddress]) { assignedRoles[counter] = i; counter++; } } return assignedRoles; } /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns (bool) {//solhint-disable-line if (_roleId == uint(Role.UnAssigned)) return true; else if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line return true; else return false; } /// @dev Return total number of members assigned against each role id. /// @return totalMembers Total members in particular role id function getMemberLengthForAllRoles() public view returns (uint[] memory totalMembers) {//solhint-disable-line totalMembers = new uint[](memberRoleData.length); for (uint i = 0; i < memberRoleData.length; i++) { totalMembers[i] = numberOfMembers(i); } } /** * @dev to update the member roles * @param _memberAddress in concern * @param _roleId the id of role * @param _active if active is true, add the member, else remove it */ function _updateRole(address _memberAddress, uint _roleId, bool _active) internal { // require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically"); if (_active) { require(!memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1); memberRoleData[_roleId].memberActive[_memberAddress] = true; memberRoleData[_roleId].memberAddress.push(_memberAddress); } else { require(memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1); delete memberRoleData[_roleId].memberActive[_memberAddress]; } } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function _addRole( bytes32 _roleName, string memory _roleDescription, address _authorized ) internal { emit MemberRole(memberRoleData.length, _roleName, _roleDescription); memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized)); } /** * @dev to check if member is in the given member array * @param _memberAddress in concern * @param memberArray in concern * @return boolean to represent the presence */ function _checkMemberInArray( address _memberAddress, address[] memory memberArray ) internal pure returns (bool memberExists) { uint i; for (i = 0; i < memberArray.length; i++) { if (memberArray[i] == _memberAddress) { memberExists = true; break; } } } /** * @dev to add initial member roles * @param _firstAB is the member address to be added * @param memberAuthority is the member authority(role) to be added for */ function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal { maxABCount = 5; _addRole("Unassigned", "Unassigned", address(0)); _addRole( "Advisory Board", "Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line address(0) ); _addRole( "Member", "Represents all users of Mutual.", //solhint-disable-line memberAuthority ); _addRole( "Owner", "Represents Owner of Mutual.", //solhint-disable-line address(0) ); // _updateRole(_firstAB, uint(Role.AdvisoryBoard), true); _updateRole(_firstAB, uint(Role.Owner), true); // _updateRole(_firstAB, uint(Role.Member), true); launchedOn = 0; } function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) { address memberAddress = memberRoleData[_memberRoleId].memberAddress[index]; return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]); } function membersLength(uint _memberRoleId) external view returns (uint) { return memberRoleData[_memberRoleId].memberAddress.length; } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "../../abstract/Iupgradable.sol"; import "./MemberRoles.sol"; import "./external/Governed.sol"; import "./external/IProposalCategory.sol"; contract ProposalCategory is Governed, IProposalCategory, Iupgradable { bool public constructorCheck; MemberRoles internal mr; struct CategoryStruct { uint memberRoleToVote; uint majorityVotePerc; uint quorumPerc; uint[] allowedToCreateProposal; uint closingTime; uint minStake; } struct CategoryAction { uint defaultIncentive; address contractAddress; bytes2 contractName; } CategoryStruct[] internal allCategory; mapping(uint => CategoryAction) internal categoryActionData; mapping(uint => uint) public categoryABReq; mapping(uint => uint) public isSpecialResolution; mapping(uint => bytes) public categoryActionHashes; bool public categoryActionHashUpdated; /** * @dev Adds new category (Discontinued, moved functionality to newCategory) * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external {} /** * @dev Initiates Default settings for Proposal Category contract (Adding default categories) */ function proposalCategoryInitiate() external {} /** * @dev Initiates Default action function hashes for existing categories * To be called after the contract has been upgraded by governance */ function updateCategoryActionHashes() external onlyOwner { require(!categoryActionHashUpdated, "Category action hashes already updated"); categoryActionHashUpdated = true; categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)"); categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)"); categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)"); categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()"); categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)"); categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)"); categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)"); categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)"); categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)"); // solhint-disable-line categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)"); categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)"); categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)"); categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)"); categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)"); categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)"); categoryActionHashes[29] = abi.encodeWithSignature("upgradeMultipleContracts(bytes2[],address[])"); categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)"); categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)"); categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)"); // solhint-disable-line categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()"); } /** * @dev Gets Total number of categories added till now */ function totalCategories() external view returns (uint) { return allCategory.length; } /** * @dev Gets category details */ function category(uint _categoryId) external view returns (uint, uint, uint, uint, uint[] memory, uint, uint) { return ( _categoryId, allCategory[_categoryId].memberRoleToVote, allCategory[_categoryId].majorityVotePerc, allCategory[_categoryId].quorumPerc, allCategory[_categoryId].allowedToCreateProposal, allCategory[_categoryId].closingTime, allCategory[_categoryId].minStake ); } /** * @dev Gets category ab required and isSpecialResolution * @return the category id * @return if AB voting is required * @return is category a special resolution */ function categoryExtendedData(uint _categoryId) external view returns (uint, uint, uint) { return ( _categoryId, categoryABReq[_categoryId], isSpecialResolution[_categoryId] ); } /** * @dev Gets the category acion details * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive */ function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) { return ( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); } /** * @dev Gets the category acion details of a category id * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive * @return action function hash */ function categoryActionDetails(uint _categoryId) external view returns (uint, address, bytes2, uint, bytes memory) { return ( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive, categoryActionHashes[_categoryId] ); } /** * @dev Updates dependant contract addresses */ function changeDependentContractAddress() public { mr = MemberRoles(ms.getLatestAddress("MR")); } /** * @dev Adds new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function newCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } _addCategory( _name, _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _actionHash, _contractAddress, _contractName, _incentives ); if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash); } } /** * @dev Changes the master address and update it's instance * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev Updates category details (Discontinued, moved functionality to editCategory) * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public {} /** * @dev Updates category details * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function editCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } delete categoryActionHashes[_categoryId]; if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash); } allCategory[_categoryId].memberRoleToVote = _memberRoleToVote; allCategory[_categoryId].majorityVotePerc = _majorityVotePerc; allCategory[_categoryId].closingTime = _closingTime; allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal; allCategory[_categoryId].minStake = _incentives[0]; allCategory[_categoryId].quorumPerc = _quorumPerc; categoryActionData[_categoryId].defaultIncentive = _incentives[1]; categoryActionData[_categoryId].contractName = _contractName; categoryActionData[_categoryId].contractAddress = _contractAddress; categoryABReq[_categoryId] = _incentives[2]; isSpecialResolution[_categoryId] = _incentives[3]; emit Category(_categoryId, _name, _actionHash); } /** * @dev Internal call to add new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function _addCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) internal { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); allCategory.push( CategoryStruct( _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _incentives[0] ) ); uint categoryId = allCategory.length - 1; categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName); categoryABReq[categoryId] = _incentives[2]; isSpecialResolution[categoryId] = _incentives[3]; emit Category(categoryId, _name, _actionHash); } /** * @dev Internal call to check if given roles are valid or not */ function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal) internal view returns (uint) { uint totalRoles = mr.totalRoles(); if (_memberRoleToVote >= totalRoles) { return 0; } for (uint i = 0; i < _allowedToCreateProposal.length; i++) { if (_allowedToCreateProposal[i] >= totalRoles) { return 0; } } return 1; } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Edits the details of an existing proposal and creates new version /// @param _proposalId Proposal id that details needs to be updated /// @param _proposalDescHash Proposal description hash having long and short description of proposal. function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward); function proposal(uint _proposalId) external view returns ( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns (uint closeValue); function allowedToCatgorize() public view returns (uint roleId); } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; interface IMaster { function getLatestAddress(bytes2 _module) external view returns (address); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns (bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; contract IProposalCategory { event Category( uint indexed categoryId, string categoryName, string actionHash ); /// @dev Adds new category /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external; /// @dev gets category details function category(uint _categoryId) external view returns ( uint categoryId, uint memberRoleToVote, uint majorityVotePerc, uint quorumPerc, uint[] memory allowedToCreateProposal, uint closingTime, uint minStake ); ///@dev gets category action details function categoryAction(uint _categoryId) external view returns ( uint categoryId, address contractAddress, bytes2 contractName, uint defaultIncentive ); /// @dev Gets Total number of categories added till now function totalCategories() external view returns (uint numberOfCategories); /// @dev Updates category details /// @param _categoryId Category id that needs to be updated /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public; }
Called by user to pay joining membership fee/
function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); tc.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } }
2,578,509
/** *Submitted for verification at Etherscan.io on 2021-07-23 */ // Sources flattened with hardhat v2.4.1 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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.0.0, only sets of type `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]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File contracts/badger-core/BadgerRegistry.sol pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; // Data from Vault struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } interface VaultView { function name() external view returns (string memory); function symbol() external view returns (string memory); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pendingGovernance() external view returns (address); function governance() external view returns (address); function management() external view returns (address); function guardian() external view returns (address); function rewards() external view returns (address); function withdrawalQueue(uint256 index) external view returns (address); } interface StratView { function name() external view returns (string memory); function strategist() external view returns (address); function rewards() external view returns (address); function keeper() external view returns (address); } contract BadgerRegistryV1 is Initializable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; //@dev Multisig. Vaults from here are considered Production ready address public governance; //@dev Given an Author Address, and Token, Return the Vault mapping(address => EnumerableSetUpgradeable.AddressSet) private vaults; event NewVault(address author, address vault); event RemoveVault(address author, address vault); event PromoteVault(address author, address vault); //@dev View Data for each strat we will return struct StratInfo { address at; string name; address strategist; address rewards; address keeper; uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } /// Vault data we will return for each Vault struct VaultInfo { address at; string name; string symbol; address token; address pendingGovernance; // If this is non zero, this is an attack from the deployer address governance; address rewards; address guardian; address management; StratInfo[] strategies; } function initialize(address _governance) public initializer { governance = _governance; } function setGovernance(address _newGov) public { require(msg.sender == governance, "!gov"); governance = _newGov; } /// Anyone can add a vault to here, it will be indexed by their address function add(address vault) public { bool added = vaults[msg.sender].add(vault); if (added) { emit NewVault(msg.sender, vault); } } /// Remove the vault from your index function remove(address vault) public { bool removed = vaults[msg.sender].remove(vault); if (removed) { emit RemoveVault(msg.sender, vault); } } //@dev Retrieve a list of all Vault Addresses from the given author function fromAuthor(address author) public view returns (address[] memory) { uint256 length = vaults[author].length(); address[] memory list = new address[](length); for (uint256 i = 0; i < length; i++) { list[i] = vaults[author].at(i); } return list; } //@dev Retrieve a list of all Vaults and the basic Vault info function fromAuthorVaults(address author) public view returns (VaultInfo[] memory) { uint256 length = vaults[author].length(); VaultInfo[] memory vaultData = new VaultInfo[](length); for(uint x = 0; x < length; x++){ VaultView vault = VaultView(vaults[author].at(x)); StratInfo[] memory allStrats = new StratInfo[](0); VaultInfo memory data = VaultInfo({ at: vaults[author].at(x), name: vault.name(), symbol: vault.symbol(), token: vault.token(), pendingGovernance: vault.pendingGovernance(), governance: vault.governance(), rewards: vault.rewards(), guardian: vault.guardian(), management: vault.management(), strategies: allStrats }); vaultData[x] = data; } return vaultData; } //@dev Given the Vault, retrieve all the data as well as all data related to the strategies function fromAuthorWithDetails(address author) public view returns (VaultInfo[] memory) { uint256 length = vaults[author].length(); VaultInfo[] memory vaultData = new VaultInfo[](length); for(uint x = 0; x < length; x++){ VaultView vault = VaultView(vaults[author].at(x)); // TODO: Strat Info with real data uint stratCount = 0; for(uint y = 0; y < 20; y++){ if(vault.withdrawalQueue(y) != address(0)){ stratCount++; } } StratInfo[] memory allStrats = new StratInfo[](stratCount); for(uint z = 0; z < stratCount; z++){ StratView strat = StratView(vault.withdrawalQueue(z)); StrategyParams memory params = vault.strategies(vault.withdrawalQueue(z)); StratInfo memory stratData = StratInfo({ at: vault.withdrawalQueue(z), name: strat.name(), strategist: strat.strategist(), rewards: strat.rewards(), keeper: strat.keeper(), performanceFee: params.performanceFee, activation: params.activation, debtRatio: params.debtRatio, minDebtPerHarvest: params.minDebtPerHarvest, maxDebtPerHarvest: params.maxDebtPerHarvest, lastReport: params.lastReport, totalDebt: params.totalDebt, totalGain: params.totalGain, totalLoss: params.totalLoss }); allStrats[z] = stratData; } VaultInfo memory data = VaultInfo({ at: vaults[author].at(x), name: vault.name(), symbol: vault.symbol(), token: vault.token(), pendingGovernance: vault.pendingGovernance(), governance: vault.governance(), rewards: vault.rewards(), guardian: vault.guardian(), management: vault.management(), strategies: allStrats }); vaultData[x] = data; } return vaultData; } //@dev Promote a vault to Production //@dev Promote just means indexed by the Governance Address function promote(address vault) public { require(msg.sender == governance, "!gov"); bool promoted = vaults[msg.sender].add(vault); if (promoted) { emit PromoteVault(msg.sender, vault); } } }
Retrieve a list of all Vaults and the basic Vault info
function fromAuthorVaults(address author) public view returns (VaultInfo[] memory) { uint256 length = vaults[author].length(); VaultInfo[] memory vaultData = new VaultInfo[](length); for(uint x = 0; x < length; x++){ VaultView vault = VaultView(vaults[author].at(x)); StratInfo[] memory allStrats = new StratInfo[](0); VaultInfo memory data = VaultInfo({ at: vaults[author].at(x), name: vault.name(), symbol: vault.symbol(), token: vault.token(), pendingGovernance: vault.pendingGovernance(), governance: vault.governance(), rewards: vault.rewards(), guardian: vault.guardian(), management: vault.management(), strategies: allStrats }); vaultData[x] = data; } return vaultData; }
10,569,618
./full_match/4/0x3CFBBDf1a8CFe8A6fEbD3210DE14A292856b6336/sources/contracts/ExponentialNoError.sol
Checks if left Exp <= right Exp./
function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; }
717,883
// File: contracts/Owned.sol pragma solidity ^0.7.0; /// @notice Ownership // SPDX-License-Identifier: GPLv2 contract Owned { bool initialised; address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); modifier onlyOwner { require(msg.sender == owner, "Not owner"); _; } function initOwned(address _owner) internal { require(!initialised, "Already initialised"); owner = address(uint160(_owner)); initialised = true; } function transferOwnership(address _newOwner) public onlyOwner { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/SafeMath.sol pragma solidity ^0.7.0; /// @notice Safe maths // SPDX-License-Identifier: GPLv2 library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a, "Add overflow"); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a, "Sub underflow"); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "Mul overflow"); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0, "Divide by 0"); c = a / b; } } // File: contracts/Permissioned.sol pragma solidity ^0.7.0; /// @notice Permissioned // SPDX-License-Identifier: GPLv2 contract Permissioned is Owned { using SafeMath for uint; struct Permission { bool active; uint maximum; uint processed; } uint public constant ROLE_MINTER = 1; // Don't need ROLE_BURNER at the moment // uint public constant ROLE_BURNER = 2; mapping(address => mapping(uint => Permission)) public permissions; modifier permitted(uint role, uint tokens) { Permission storage permission = permissions[msg.sender][role]; require(permission.active && (permission.maximum == 0 || permission.processed + tokens < permission.maximum), "Not permissioned"); permission.processed = permission.processed.add(tokens); _; } function initPermissioned(address _owner) internal { initOwned(_owner); setPermission(_owner, ROLE_MINTER, true, 0); // setPermission(_owner, ROLE_BURNER, true, 0); } function setPermission(address account, uint role, bool active, uint maximum) public onlyOwner { uint processed = permissions[account][role].processed; permissions[account][role] = Permission({ active: active, maximum: maximum, processed: processed }); } function processed(uint role, uint tokens) internal { permissions[msg.sender][role].processed = permissions[msg.sender][role].processed.add(tokens); } } // File: contracts/ERC20.sol pragma solidity ^0.7.0; /// @notice ERC20 https://eips.ethereum.org/EIPS/eip-20 with optional symbol, name and decimals // SPDX-License-Identifier: GPLv2 interface ERC20 { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); function symbol() external view returns (string memory); function name() external view returns (string memory); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // File: contracts/OGDTokenInterface.sol pragma solidity ^0.7.0; /// @notice OGDTokenInterface = ERC20 + mint + burn (+ dividend payment) // SPDX-License-Identifier: GPLv2 interface OGDTokenInterface is ERC20 { function mint(address tokenOwner, uint tokens) external returns (bool success); function burn(uint tokens) external returns (bool success); // function burnFrom(address tokenOwner, uint tokens) external returns (bool success); } // File: contracts/DividendTokens.sol pragma solidity ^0.7.0; /// @notice DividendTokens to map [token] => [enabled] // SPDX-License-Identifier: GPLv2 library DividendTokens { struct DividendToken { uint timestamp; uint index; address token; bool enabled; } struct Data { bool initialised; mapping(address => DividendToken) entries; address[] index; } event DividendTokenAdded(address indexed token, bool enabled); event DividendTokenRemoved(address indexed token); event DividendTokenUpdated(address indexed token, bool enabled); function init(Data storage self) internal { require(!self.initialised); self.initialised = true; } function add(Data storage self, address token, bool enabled) internal { require(self.entries[token].timestamp == 0, "DividendToken.add: Cannot add duplicate"); self.index.push(token); self.entries[token] = DividendToken(block.timestamp, self.index.length - 1, token, enabled); emit DividendTokenAdded(token, enabled); } function remove(Data storage self, address token) internal { require(self.entries[token].timestamp > 0, "DividendToken.update: Address not registered"); uint removeIndex = self.entries[token].index; emit DividendTokenRemoved(token); uint lastIndex = self.index.length - 1; address lastIndexKey = self.index[lastIndex]; self.index[removeIndex] = lastIndexKey; self.entries[lastIndexKey].index = removeIndex; delete self.entries[token]; if (self.index.length > 0) { self.index.pop(); } } function update(Data storage self, address token, bool enabled) internal { DividendToken storage entry = self.entries[token]; require(entry.timestamp > 0, "DividendToken.update: Address not registered"); entry.timestamp = block.timestamp; entry.enabled = enabled; emit DividendTokenUpdated(token, enabled); } function length(Data storage self) internal view returns (uint) { return self.index.length; } } // File: contracts/OGDToken.sol pragma solidity ^0.7.0; // pragma experimental ABIEncoderV2; // import "https://github.com/ogDAO/Governance/blob/master/contracts/Permissioned.sol"; // import "https://github.com/ogDAO/Governance/blob/master/contracts/OGDTokenInterface.sol"; // import "https://github.com/ogDAO/Governance/blob/master/contracts/DividendTokens.sol"; /// @notice Optino Governance Dividend Token = ERC20 + mint + burn + dividend payments. (c) The Optino Project 2020 // SPDX-License-Identifier: GPLv2 contract OGDToken is OGDTokenInterface, Permissioned { using SafeMath for uint; using DividendTokens for DividendTokens.Data; using DividendTokens for DividendTokens.DividendToken; struct Account { uint balance; mapping(address => uint) lastDividendPoints; mapping(address => uint) owing; } string _symbol; string _name; uint8 _decimals; uint _totalSupply; mapping(address => Account) accounts; mapping(address => mapping(address => uint)) allowed; DividendTokens.Data private dividendTokens; uint public constant pointMultiplier = 10e27; mapping(address => uint) public totalDividendPoints; mapping(address => uint) public unclaimedDividends; event UpdateAccountInfo(address dividendToken, address account, uint owing, uint totalOwing, uint lastDividendPoints, uint totalDividendPoints, uint unclaimedDividends); event DividendDeposited(address indexed token, uint tokens); event DividendWithdrawn(address indexed account, address indexed token, uint tokens); // CHECK: Duplicated from the library for ABI generation // event DividendTokenAdded(address indexed token, bool enabled); // event DividendTokenRemoved(address indexed token); // event DividendTokenUpdated(address indexed token, bool enabled); constructor(string memory symbol, string memory name, uint8 decimals, address tokenOwner, uint initialSupply) { initPermissioned(msg.sender); _symbol = symbol; _name = name; _decimals = decimals; accounts[tokenOwner].balance = initialSupply; _totalSupply = initialSupply; emit Transfer(address(0), tokenOwner, _totalSupply); } function symbol() override external view returns (string memory) { return _symbol; } function name() override external view returns (string memory) { return _name; } function decimals() override external view returns (uint8) { return _decimals; } function totalSupply() override external view returns (uint) { return _totalSupply.sub(accounts[address(0)].balance); } function balanceOf(address tokenOwner) override external view returns (uint balance) { return accounts[tokenOwner].balance; } function transfer(address to, uint tokens) override external returns (bool success) { updateAccounts(msg.sender, to); accounts[msg.sender].balance = accounts[msg.sender].balance.sub(tokens); accounts[to].balance = accounts[to].balance.add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) override external returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) override external returns (bool success) { updateAccounts(msg.sender, to); accounts[from].balance = accounts[from].balance.sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); accounts[to].balance = accounts[to].balance.add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) override external view returns (uint remaining) { return allowed[tokenOwner][spender]; } function addDividendToken(address _dividendToken) external onlyOwner { if (!dividendTokens.initialised) { dividendTokens.init(); } dividendTokens.add(_dividendToken, true); } function updateDividendToken(address token, bool enabled) public onlyOwner { require(dividendTokens.initialised); dividendTokens.update(token, enabled); } function removeDividendToken(address token) public onlyOwner { require(dividendTokens.initialised); dividendTokens.remove(token); } function getDividendTokenByIndex(uint i) public view returns (address, bool) { require(i < dividendTokens.length(), "Invalid dividend token index"); DividendTokens.DividendToken memory dividendToken = dividendTokens.entries[dividendTokens.index[i]]; return (dividendToken.token, dividendToken.enabled); } function dividendTokensLength() public view returns (uint) { return dividendTokens.length(); } /// @notice New dividends owing since the last updateAccount(...) function newDividendsOwing(address dividendToken, address account) internal view returns (uint) { uint newDividendPoints = totalDividendPoints[dividendToken].sub(accounts[account].lastDividendPoints[dividendToken]); return accounts[account].balance.mul(newDividendPoints).div(pointMultiplier); } /// @notice Dividends owning since the last updateAccount(...) + new dividends owing since the last updateAccount(...) function dividendsOwing(address account) public view returns (address[] memory tokenList, uint[] memory owingList) { tokenList = new address[](dividendTokens.index.length); owingList = new uint[](dividendTokens.index.length); for (uint i = 0; i < dividendTokens.index.length; i++) { DividendTokens.DividendToken memory dividendToken = dividendTokens.entries[dividendTokens.index[i]]; uint owing = accounts[account].owing[dividendToken.token].add(newDividendsOwing(dividendToken.token, account)); tokenList[i] = dividendToken.token; owingList[i] = owing; } } function updateAccounts(address account1, address account2) internal { for (uint i = 0; i < dividendTokens.index.length; i++) { DividendTokens.DividendToken memory dividendToken = dividendTokens.entries[dividendTokens.index[i]]; if (dividendToken.enabled) { uint owing = newDividendsOwing(dividendToken.token, account1); if (owing > 0) { unclaimedDividends[dividendToken.token] = unclaimedDividends[dividendToken.token].sub(owing); accounts[account1].lastDividendPoints[dividendToken.token] = totalDividendPoints[dividendToken.token]; accounts[account1].owing[dividendToken.token] = accounts[account1].owing[dividendToken.token].add(owing); } if (account1 != account2) { owing = newDividendsOwing(dividendToken.token, account2); if (owing > 0) { unclaimedDividends[dividendToken.token] = unclaimedDividends[dividendToken.token].sub(owing); accounts[account2].lastDividendPoints[dividendToken.token] = totalDividendPoints[dividendToken.token]; accounts[account2].owing[dividendToken.token] = accounts[account2].owing[dividendToken.token].add(owing); } } } } } /// @notice Deposit enabled dividend token function depositDividend(address token, uint tokens) public payable { DividendTokens.DividendToken memory _dividendToken = dividendTokens.entries[token]; require(_dividendToken.enabled, "Dividend token is not enabled"); totalDividendPoints[token] = totalDividendPoints[token].add(tokens.mul(pointMultiplier).div(_totalSupply)); unclaimedDividends[token] = unclaimedDividends[token].add(tokens); if (token == address(0)) { require(msg.value >= tokens, "Insufficient ETH sent"); uint refund = msg.value.sub(tokens); if (refund > 0) { require(msg.sender.send(refund), "ETH refund failure"); } } else { require(ERC20(token).transferFrom(msg.sender, address(this), tokens), "ERC20 transferFrom failure"); } emit DividendDeposited(token, tokens); } /// @notice Received ETH as dividends receive () external payable { depositDividend(address(0), msg.value); } function withdrawDividendsFor(address account) internal { updateAccounts(account, account); for (uint i = 0; i < dividendTokens.index.length; i++) { DividendTokens.DividendToken memory dividendToken = dividendTokens.entries[dividendTokens.index[i]]; if (dividendToken.enabled) { uint tokens = accounts[account].owing[dividendToken.token]; if (tokens > 0) { accounts[account].owing[dividendToken.token] = 0; if (dividendToken.token == address(0)) { require(payable(account).send(tokens), "ETH send failure"); } else { require(ERC20(dividendToken.token).transfer(account, tokens), "ERC20 transfer failure"); } } emit DividendWithdrawn(account, dividendToken.token, tokens); } } } /// @notice Withdraw enabled dividends tokens function withdrawDividends() public { withdrawDividendsFor(msg.sender); } /// @notice Withdraw enabled and disabled dividends tokens. Does not include new dividends since last updateAccount(...) triggered by transfer(...) and transferFrom(...) function withdrawDividend(address token) public { uint tokens = accounts[msg.sender].owing[token]; if (tokens > 0) { accounts[msg.sender].owing[token] = 0; if (token == address(0)) { require(payable(msg.sender).send(tokens), "ETH send failure"); } else { require(ERC20(token).transfer(msg.sender, tokens), "ERC20 transfer failure"); } } emit DividendWithdrawn(msg.sender, token, tokens); } /// @notice Mint tokens function mint(address tokenOwner, uint tokens) override external permitted(ROLE_MINTER, tokens) returns (bool success) { processed(ROLE_MINTER, tokens); accounts[tokenOwner].balance = accounts[tokenOwner].balance.add(tokens); _totalSupply = _totalSupply.add(tokens); emit Transfer(address(0), tokenOwner, tokens); updateAccounts(tokenOwner, tokenOwner); return true; } /// @notice Withdraw dividends and then burn tokens function burn(uint tokens) override external returns (bool success) { updateAccounts(msg.sender, msg.sender); withdrawDividendsFor(msg.sender); accounts[msg.sender].balance = accounts[msg.sender].balance.sub(tokens); _totalSupply = _totalSupply.sub(tokens); emit Transfer(msg.sender, address(0), tokens); return true; } /// @notice Recover tokens for non enabled dividend tokens function recoverTokens(address token, uint tokens) public onlyOwner { DividendTokens.DividendToken memory dividendToken = dividendTokens.entries[token]; require(dividendToken.timestamp == 0 || !dividendToken.enabled, "Cannot recover tokens for enabled dividend token"); if (token == address(0)) { require(payable(owner).send((tokens == 0 ? address(this).balance : tokens)), "ETH send failure"); } else { require(ERC20(token).transfer(owner, tokens == 0 ? ERC20(token).balanceOf(address(this)) : tokens), "ERC20 transfer failure"); } } }
OGDTokenInterface = ERC20 + mint + burn (+ dividend payment) SPDX-License-Identifier: GPLv2 function burnFrom(address tokenOwner, uint tokens) external returns (bool success);
interface OGDTokenInterface is ERC20 { function mint(address tokenOwner, uint tokens) external returns (bool success); function burn(uint tokens) external returns (bool success); }
14,097,915
./full_match/1/0xAc64fCaB932382005e6d6F13a88Dc5455ECC85a2/sources/contracts/ChainbackSign.sol
Message hash for 'sign', could also be generated off-chain, e.g. with web3j./
function getSignMessageHash( address sender, string calldata chainbackHash, string calldata cid, string calldata name, string calldata comment, uint256 salt ) public pure returns (bytes32) { return keccak256(abi.encode(sender, chainbackHash, cid, name, comment, salt)); }
9,631,998
./full_match/3/0xe3E78C43980456568eE5902C155079e725dcBB99/sources/browser/ERC1400ERC20.sol
[NOT MANDATORY FOR ERC1400 STANDARD] Set validator contract address. The validator contract needs to verify "ERC1400TokensValidator" interface. Once setup, the validator will be called everytime a transfer is executed. validatorAddress Address of the validator contract. interfaceLabel Interface label of hook contract./
function setHookContract(address validatorAddress, string calldata interfaceLabel) external onlyOwner { ERC1400Raw._setHookContract(validatorAddress, interfaceLabel); }
14,141,629
./full_match/4/0xf2acF9d120221Ec8ff76888441110C0a25AF0211/sources/Manwithkey.sol
tokens are numbered from 1 to 10
function tokenId() internal returns(uint256) { numberOfTokens += 1; return numberOfTokens; }
756,054
./partial_match/80001/0x129DDF2b913464608EE14f810243949B71F9626E/sources/contracts/libs/WitnetErrorsLib.sol
Extract error codes from a Witnet.Result value. result An instance of `Witnet.Result`. return The `uint[]` error parameters as decoded from the `Witnet.Result`.
function _errorsFromResult(Witnet.Result memory result) private pure returns (WitnetCBOR.CBOR[] memory) { require(!result.success, "no errors"); return result.value.readArray(); }
8,816,293
pragma solidity 0.7.6; pragma abicoder v2; contract Message { address public owner; string public author; enum Language {PT, EN, ES} mapping (Language => string[]) public messages; constructor() { owner = msg.sender; author = "Solange Gueiros"; } event MessageChange(string language, string message); modifier onlyOwner { require(msg.sender == owner,"Only owner"); _; } function setMessage(Language _language, string memory _message) public onlyOwner returns (uint index) { messages[_language].push(_message); string memory lang = getLanguage (_language); emit MessageChange(lang, _message); index = lengthMessage(_language); } function setMessage(string memory _language, string memory _message) public onlyOwner returns (uint index) { Language lang = toLanguage (_language); messages[lang].push(_message); emit MessageChange(_language, _message); index = lengthMessage(lang); } function getMessage(Language _language) public view returns (string memory) { uint index = lengthMessage(_language); return (messages[_language][index]); } function getMessage(string memory _language) public view returns (string memory) { Language lang = toLanguage (_language); uint index = lengthMessage(lang); return (messages[lang][index]); } function allMessages(Language _language) public view returns (string[] memory) { return (messages[_language]); } function allMessages(string memory _language) public view returns (string[] memory) { Language lang = toLanguage (_language); return (messages[lang]); } function lengthMessage(Language _language) public view returns (uint) { return messages[_language].length - 1; } function lengthMessage(string memory _language) public view returns (uint) { Language lang = toLanguage (_language); return messages[lang].length - 1; } function toLanguage(string memory _language) internal pure returns (Language) { // keccak256() only accept bytes as arguments, so we need explicit conversion bytes memory lang = bytes(_language); bytes32 hash = keccak256(lang); // Loop to check if (hash == keccak256("PT") || hash == keccak256("pt") || hash == keccak256("Pt") ) return Language.PT; if (hash == keccak256("EN") || hash == keccak256("en") || hash == keccak256("En") ) return Language.EN; if (hash == keccak256("ES") || hash == keccak256("es") || hash == keccak256("Es") ) return Language.ES; revert("Invalid language"); } function getLanguage(Language _language) public pure returns (string memory) { //require(uint8(_language) <= 2, "Invalid language"); // Loop through possible options if (Language.PT == _language) return "Portugues"; if (Language.EN == _language) return "English"; if (Language.ES == _language) return "Espanol"; revert("Invalid language"); } }
require(uint8(_language) <= 2, "Invalid language"); Loop through possible options
function getLanguage(Language _language) public pure returns (string memory) { if (Language.PT == _language) return "Portugues"; if (Language.EN == _language) return "English"; if (Language.ES == _language) return "Espanol"; revert("Invalid language"); }
13,003,494
./partial_match/1/0xEAc299004Ca13F63dF818A737B39DfA16714B347/sources/Token.sol
Updates token symbol _symbol New token name/
function updateSymbol(string _symbol) public onlyOwner { require(bytes(_symbol).length != 0); symbol = _symbol; }
9,169,907
// SPDX-License-Identifier: GPL-3.0-or-later // 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/>. // // XXX for changes // XXX: 0.8.10; removed requires for overflow checks pragma solidity 0.8.10; import "./LogExpMath.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant TWO = 2 * ONE; uint256 internal constant FOUR = 4 * ONE; uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a - b; return c; } /// @notice a - b but floors to zero if a <= b /// XXX: subFloor implementation function subFloor(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a > b ? a - b : 0; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. * The result is guaranteed to not be above the true value (that is, * the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { // Optimize for when y equals 1.0, 2.0 or 4.0, as those are very simple // to implement and occur often in 50/50 and 80/20 Weighted Pools // XXX: checks for y == 0, x == ONE, x == 0 if (0 == y || x == ONE) { return ONE; } else if (x == 0) { return 0; } else if (y == ONE) { return x; } else if (y == TWO) { return mulDown(x, x); } else if (y == FOUR) { uint256 square = mulDown(x, x); return mulDown(square, square); } else { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. * The result is guaranteed to not be below the true value (that is, * the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { // Optimize for when y equals 1.0, 2.0 or 4.0, as those are very simple // to implement and occur often in 50/50 and 80/20 Weighted Pools // XXX: checks for y == 0, x == ONE, x == 0 if (0 == y || x == ONE) { return ONE; } else if (x == 0) { return 0; } else if (y == ONE) { return x; } else if (y == TWO) { return mulUp(x, x); } else if (y == FOUR) { uint256 square = mulUp(x, x); return mulUp(square, square); } else { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } } /** * @dev Returns e^x, assuming x is a fixed point number, rounding down. * The result is guaranteed to not be above the true value (that is, * the error function expected - actual is always positive). * XXX: expDown implementation */ function expDown(uint256 x) internal pure returns (uint256) { if (x == 0) { return ONE; } require(x < 2**255, "FixedPoint: x out of bounds"); int256 x_int256 = int256(x); uint256 raw = uint256(LogExpMath.exp(x_int256)); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } /** * @dev Returns e^x, assuming x is a fixed point number, rounding up. * The result is guaranteed to not be below the true value (that is, * the error function expected - actual is always negative). * XXX: expUp implementation */ function expUp(uint256 x) internal pure returns (uint256) { if (x == 0) { return ONE; } require(x < 2**255, "FixedPoint: x out of bounds"); int256 x_int256 = int256(x); uint256 raw = uint256(LogExpMath.exp(x_int256)); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, * as it strips this error and prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } }
a - b but floors to zero if a <= b XXX: subFloor implementation
function subFloor(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a > b ? a - b : 0; return c; }
12,998,425
./full_match/4/0xC1c61f48c6926ea770BBAeb9432D1F390B1d05B1/sources/RoyaleV1/Pool/RoyaleLP.sol
For claiming withdrawal after user added to the reserve recipient.
function claimTokens() external nonReentrant{ require(reserveRecipients[msg.sender] , "request withdraw first"); uint totalBurnt; uint decimal; for(uint8 i=0; i<3; i++) { if(amountWithdraw[msg.sender][i] > 0) { decimal=tokens[i].decimals(); uint temp = amountWithdraw[msg.sender][i].sub((amountWithdraw[msg.sender][i].mul(fees)).div(DENOMINATOR)); reserveAmount[i] =reserveAmount[i].sub(amountWithdraw[msg.sender][i]); selfBalance = selfBalance.sub(temp.mul(1e18).div(10**decimal)); totalBurnt =totalBurnt.add(amountBurnt[msg.sender][i]); amountWithdraw[msg.sender][i] = 0; amountBurnt[msg.sender][i]=0; tokens[i].safeTransfer(msg.sender, temp); emit userRecieved(msg.sender,temp); } } updateLockedRPT(msg.sender,totalBurnt); reserveRecipients[msg.sender] = false; }
679,413
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./ReactPool.sol"; contract PoolFactory is Ownable { event NewPool(address indexed at); address[] public poolAddresses; constructor() { // } /* * @notice Deploy the pool * @param _stakedToken: staked token address * @param _rewardToken: reward token address * @param _rewardPerBlock: reward per block (in rewardToken) * @param _startBlock: start block * @param _endBlock: end block * @param _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0) * @param _admin: admin address with ownership * @return address of new smart chef contract */ function deployPool( IERC20d _stakedToken, IERC20d _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _poolLimitPerUser, address _admin ) external onlyOwner { require(_stakedToken.totalSupply() >= 0); require(_rewardToken.totalSupply() >= 0); require(_stakedToken != _rewardToken, "PoolFactory: tokens must be different"); bytes memory bytecode = type(ReactPool).creationCode; bytes32 salt = keccak256(abi.encodePacked(_stakedToken, _rewardToken, _startBlock)); address newContractAddress; assembly { newContractAddress := create2(0, add(bytecode, 32), mload(bytecode), salt) } ReactPool(newContractAddress).initialize( _stakedToken, _rewardToken, _rewardPerBlock, _startBlock, _bonusEndBlock, _poolLimitPerUser, _admin ); poolAddresses.push(newContractAddress); emit NewPool(newContractAddress); } }
Deploy the pool _stakedToken: staked token address _rewardToken: reward token address _rewardPerBlock: reward per block (in rewardToken) _startBlock: start block _endBlock: end block _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0) _admin: admin address with ownership return address of new smart chef contract/
function deployPool( IERC20d _stakedToken, IERC20d _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _poolLimitPerUser, address _admin ) external onlyOwner { require(_stakedToken.totalSupply() >= 0); require(_rewardToken.totalSupply() >= 0); require(_stakedToken != _rewardToken, "PoolFactory: tokens must be different"); bytes memory bytecode = type(ReactPool).creationCode; bytes32 salt = keccak256(abi.encodePacked(_stakedToken, _rewardToken, _startBlock)); address newContractAddress; assembly { newContractAddress := create2(0, add(bytecode, 32), mload(bytecode), salt) } ReactPool(newContractAddress).initialize( _stakedToken, _rewardToken, _rewardPerBlock, _startBlock, _bonusEndBlock, _poolLimitPerUser, _admin ); poolAddresses.push(newContractAddress); emit NewPool(newContractAddress); }
7,221,499
./full_match/5/0x8a44aF939D25C17f55088ea06bFCD43A80dB4f85/sources/src/MSSC.sol
Make deposits (Native coin or ERC20 tokens) to a existent instruction, {msg.sender} will become the {sender} of the instruction hence will be the only account which is able to withdraw those allocated funds. instructionId Instruction to allocate funds./
function deposit(bytes32 cycleId, bytes32 instructionId) external payable cycleExists(cycleId) { _instructions[instructionId].deposit(); if (_isHybrid(cycleId)) { if (_allInstructionsFulfilled(cycleId)) { _cycles[cycleId].lock.init(cycleId); } } }
7,090,369
./full_match/42/0x2B4562D92845e05b8Db39C82E887b7Ce71b1e4f5/sources/ERC721/LNKDNS.sol
可以通过 `_blindedBid` = keccak256(value, fake, secret) 设置一个秘密竞拍。 只有在出价披露阶段被正确披露,已发送的代币才会被退还。 如果与出价一起发送的代币至少为 “value” 且 “fake” 不为真,则出价有效。 将 “fake” 设置为 true ,然后发送满足订金金额但又不与出价相同的金额是隐藏实际出价的方法。 同一个地址可以放置多个出价。
function toBid( address _bidder,bytes32 _blindedBid,uint value ) public onlyBefore(biddingEnd) onlyWhitelisted nonReentrant returns(bool){ _token.safeTransferFrom(_bidder,address(this),value); bids[_bidder].push(Bid({ blindedBid: _blindedBid, deposit: value })); return true; }
16,278,324
./full_match/1/0x86b17741C4B62d40F0824e1cC8A41Bad4B71d7cf/sources/contracts/presale-pool/PreSalePool02.sol
Emergency Mode: Owner can withdraw token Can withdraw token in emergency mode _wallet Address wallet who receive token/
function emergencyWithdraw(address _wallet, uint256 _amount) external onlyOwner { require( token.balanceOf(address(this)) >= _amount, "POOL::INSUFFICIENT_BALANCE" ); _deliverTokens(_wallet, _amount); emit EmergencyWithdraw(_wallet, _amount); } userPurchased = 1400
8,472,568
// SPDX-License-Identifier: Unlicense pragma solidity >=0.8.0; import "ds-test/test.sol"; import "./Cheats.sol"; contract Foo { function f() external view returns(uint256) { return 1; } } contract SetNonceTest is DSTest { Cheats constant cheats = Cheats(HEVM_ADDRESS); Foo public foo; function setUp() public { foo = new Foo(); } function testSetNonce() public { cheats.setNonce(address(foo), 10); // makes sure working correctly after mutating nonce. foo.f(); assertEq(cheats.getNonce(address(foo)), 10); foo.f(); } function testFailInvalidNonce() public { cheats.setNonce(address(foo), 10); // set lower nonce should fail cheats.setNonce(address(foo), 5); } }
set lower nonce should fail
function testFailInvalidNonce() public { cheats.setNonce(address(foo), 10); cheats.setNonce(address(foo), 5); }
15,882,911
./partial_match/3/0x1B0E0eCa53FB8EbFcBc6071d081961A37628Ca83/sources/Betting.sol
Specify min bet for ERC20. _token address of the erc20 token. _amount min amount to create a bet with the _token/_amount = _amount.mul(1e18);
function setMinBetForERC20(address _token, uint256 _amount) public onlyAdmin { require(_token != address(0)); require(_amount > 0); minBetERC20[_token] = _amount; }
5,189,627
//SPDX-License-Identifier: Unlicense // *****+=:. .=*****+-. -#@@#-. .+*****=:. .****+: :*****+=:. -***: -+**= =***. // ...:=*#%%#*=:.. .+%@*. @@@@%@@@@* .#@@@%%@@@*. [email protected]@@@%@@@- :%@@@%%@@@- [email protected]@@@@# [email protected]@@@%@@@@+ [email protected]@@- #@@@: %@@% // .:=%@@@@@@@@@@@@@@#-. .#@@@@%: @@@% .#@@%=.#@@* [email protected]@@= -%@@#: #@@@: :%@@- [email protected]@@@ [email protected]@@#@@# [email protected]@@* :%@@*: [email protected]@@- [email protected]@@+ [email protected]@@. // .-%@@@@@@%%%%%%%%@@@@@@+=%@@@%*. @@@% :@@@*.#@@* [email protected]@@= [email protected]@@- *@@@- :%@@=..%@@@ [email protected]@%[email protected]@%: [email protected]@@* [email protected]@#: [email protected]@@- *@@@:%@@+ // -%@@@@%##=. :*##@@@@@@@%#. @@@@:-*@@%=.#@@#::*@@%- [email protected]@@- [email protected]@@= :%@@*+#@@@= [email protected]@%[email protected]@@# [email protected]@@#+#@@@= [email protected]@@- .#@@[email protected]@% // [email protected]@@@#*: *@@@@@#- @@@@@@@@#+ .#@@@@@@@@= [email protected]@@- [email protected]@@+.:%@@%##@@#: @@@#.%@@# [email protected]@@%#%@@#-. [email protected]@@- [email protected]@@@@: // :*@@@@+. .=%@@@#*. @@@@***+. .#@@%+*%@@#: [email protected]@@- *@@@+ :%@@- %@@@. [email protected]@@#=*@@%- [email protected]@@* :*@@@= [email protected]@@- #@@@# // .#@@@%= .-#@@@%#: : @@@% .#@@* [email protected]@@= [email protected]@@= *@@@- :%@@- [email protected]@@= [email protected]@@@@@@@@* [email protected]@@* [email protected]@@= [email protected]@@- *@@@: // [email protected]@@@= :*@@@@#-. .-%: @@@% .#@@* [email protected]@@= -%@@*=-%@@#. :%@@*=-%@@@: @@@@++*@@@# [email protected]@@#--*@@%- [email protected]@@*----. *@@@: // [email protected]@@@+ :=#@@@#+: [email protected]@*. @@@% .#@@* [email protected]@@= -#@@@@@@#: :%@@@@@@@*+ [email protected]@@# .*@@%[email protected]@@@@@@@#- [email protected]@@@@@@@: *@@@: // [email protected]@@% .-#@@@%*: *@@@@. +++= .=++- :+++: :++++++. .++++++++. :+++: :+++-.+++++++=: -++++++++. -+++. // #@@@% :*@@@@#-. -%@@@. // %@@@% :+#@@@#=: :%@@@. . . // [email protected]@@% .=#@@@@*: [email protected]@@@. ++++= :++= :++***++: .=+++++++++. =++= .+++- +++= .+++=. :+++- :++***++: // :@@@%- :*@@@@#-. *@@@%. @@@@% [email protected]@# :#@@@#%@@#:-%@@@@@@@@@: %@@%. :@@@* @@@% :@@@@+ [email protected]@@+ :#@@%#@@@#: // @@@@# .*#@@@#=: =%@@@= @@@@@= [email protected]@# [email protected]@@+:=%@@*:---#@@@+--. %@@%. :@@@* @@@% :@@@@#:[email protected]@@+ :%@@*::*@@@- // [email protected]@@@+ =#@@@@*: -%@@@#. @@@#@% [email protected]@# :%@@*. [email protected]@%- *@@@- %@@%. :@@@* @@@% :@@@@@[email protected]@@+ [email protected]@@= :---. // [email protected]@@@#%@@@#-. =%@@@@- @@@[email protected]@*[email protected]@# [email protected]@@* [email protected]@@= *@@@- %@@@#*#@@@* @@@% :@@%[email protected]%*@@@+ [email protected]@@= -****: // [email protected]@@@@@%=. :*@@@@%- @@@-%@%[email protected]@# [email protected]@@* [email protected]@@= *@@@- %@@@@@@@@@* @@@% :@@#[email protected]@%@@@+ [email protected]@@= [email protected]@@@- // [email protected]@@@@*. -#%@@@@+: @@@=:@@%@@# [email protected]@@* [email protected]@@= *@@@- %@@%-:[email protected]@@* @@@% :@@#[email protected]@@@@+ [email protected]@@= .*@@@- // .%@@@@%:. :*+-:-=*#%%@@@@@%- @@@=.#@@@@# .*@@%- :#@@#: *@@@- %@@%. :@@@* @@@% :@@# [email protected]@@@@+ [email protected]@@= [email protected]@@- // *%@@@@=. :#%@@@%@@@@@@@@@*:. @@@= :@@@@# [email protected]@@%+#@@@+ *@@@- %@@%. :@@@* @@@% :@@# [email protected]@@@+ .*@@@*+%@@@- -#%%: // :%@@@@#. .#@@@@@@@@@@@@*:. @@@= .#@@@# [email protected]@@@@@@+ *@@@- %@@%. :@@@* @@@% :@@# [email protected]@@@+ -%@@@@@@@@- :%@@: // .:-:. ....:::..... .. ... ..:::.. ... .. ... ... .. .... .::..... .. // pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IPNTokenSwap.sol"; /** @title Probably Nothing Token Swap from PN to PRBLY * @author 0xEwok and audie.eth * @notice This contract swaps PN tokens for PRBLY tokens and compensates PN * taxes */ contract PNTokenSwap is IPNTokenSwap, ReentrancyGuard, Ownable { address private v1TokenAddress; address private v2TokenAddress; address private v1TokenTaker; bool private swapActive; mapping(address => uint256) private swappedAmount; constructor(address _v1Token, address _v2Token) { v1TokenAddress = _v1Token; v2TokenAddress = _v2Token; } /** @notice Provides address of token being swapped * @return v1Address address of the V1 token contract */ function getV1TokenAddress() external view override returns (address) { return v1TokenAddress; } /** @notice Provides address of received from swap * @return v2Address address of the V2 token contract */ function getV2TokenAddress() external view override returns (address) { return v2TokenAddress; } /** @notice Provides address that receives swapped tokens * @return tokenTaker address that receives swapped tokens */ function getV1TokenTaker() public view override returns (address) { return v1TokenTaker; } /** @notice Allows owner to change who receives swapped tokens * @param newTokenTaker address to receive swapped tokens */ function setV1TokenTaker(address newTokenTaker) external override onlyOwner { v1TokenTaker = newTokenTaker; } /** @notice Allows any caller to see if the swap function is active * @return swapActive boolean indicating whether swap is on or off */ function isSwapActive() external view returns (bool) { return swapActive; } /** @notice Allows owner to pause use of the swap function * @dev Simply calling this function is enough to pause swapping */ function pauseSwap() external onlyOwner { swapActive = false; } /** @notice Allows owner to activate the swap function if it's paused * @dev Ensure the token taker address is set before calling */ function allowSwap() external onlyOwner { require(v1TokenTaker != address(0), "Must setV1TokenTaker"); swapActive = true; } /** @notice Check an addresses cumulative swapped tokens (input) * @param swapper Address for which you want the cumulative balance */ function getSwappedAmount(address swapper) external view returns (uint256) { return swappedAmount[swapper]; } /** @notice Swaps PN v1 tokens for PN v2 tokens * @param amount The amount of v1 tokens to exchange for v2 tokens */ function swap(uint256 amount) external override nonReentrant { require(swapActive, "Swap is paused"); IERC20 v1Contract = IERC20(v1TokenAddress); require( v1Contract.balanceOf(msg.sender) >= amount, "Amount higher than user's balance" ); require( // Tranfer tokens from sender to token taker v1Contract.transferFrom(msg.sender, v1TokenTaker, amount), "Token swap failed" ); IERC20 v2Contract = IERC20(v2TokenAddress); // Transfer amount minus fees to sender v2Contract.transfer(msg.sender, swapAmount(amount)); // record the amount of swapped v1 tokens swappedAmount[msg.sender] = swappedAmount[msg.sender] + amount; } /** @notice Allows Owner to withdraw unswapped v2 tokens * @param amount The amount of v2 tokens to withdraw */ function withdrawV2(uint256 amount) external onlyOwner { IERC20(v2TokenAddress).transfer(msg.sender, amount); } /** @notice Given a v1 Amount, shows the number of v2 tokens swap will return * @param v1Amount The amount of v1 tokens to check * @return v2Amount number of V2 tokens to be swapped for V1 */ function swapAmount(uint256 v1Amount) public pure returns (uint256) { // This results in moving the decimal place 4 positions to the RIGHT! // The reason is because v1 was 9 decimals, and v2 is 18 decimals. return v1Amount * 100000; } } // 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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IPNTokenSwap{ function getV1TokenAddress() external view returns(address); function getV2TokenAddress() external view returns(address); function getV1TokenTaker() external view returns(address); function setV1TokenTaker(address _newTokenTaker) external; function swap(uint256 amount) 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; } }
Provides address of received from swap return v2Address address of the V2 token contract/
function getV2TokenAddress() external view override returns (address) { return v2TokenAddress; }
10,107,143
// File: contracts/lib/math/SafeMath.sol pragma solidity 0.5.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/lib/ownership/Ownable.sol pragma solidity 0.5.12; /** * @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 aplied to your functions to restrict their use to * the owner. */ contract Ownable { address public owner; address public pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @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 msg.sender == owner; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/lib/utils/ReentrancyGuard.sol pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied 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. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: contracts/Utils.sol pragma solidity 0.5.12; interface ERC20 { function balanceOf(address account) external view returns (uint256); } interface MarketDapp { // Returns the address to approve tokens for function tokenReceiver(address[] calldata assetIds, uint256[] calldata dataValues, address[] calldata addresses) external view returns(address); function trade(address[] calldata assetIds, uint256[] calldata dataValues, address[] calldata addresses, address payable recipient) external payable; } /// @title Util functions for the BrokerV2 contract for Switcheo Exchange /// @author Switcheo Network /// @notice Functions were moved from the BrokerV2 contract into this contract /// so that the BrokerV2 contract would not exceed the maximum contract size of /// 24 KB. library Utils { using SafeMath for uint256; // The constants for EIP-712 are precompiled to reduce contract size, // the original values are left here for reference and verification. // // bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract,", // "bytes32 salt", // ")" // )); // bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472; // // bytes32 public constant CONTRACT_NAME = keccak256("Switcheo Exchange"); // bytes32 public constant CONTRACT_VERSION = keccak256("2"); // uint256 public constant CHAIN_ID = 1; // address public constant VERIFYING_CONTRACT = 0x7ee7Ca6E75dE79e618e88bDf80d0B1DB136b22D0; // bytes32 public constant SALT = keccak256("switcheo-eth-salt"); // bytes32 public constant DOMAIN_SEPARATOR = keccak256(abi.encode( // EIP712_DOMAIN_TYPEHASH, // CONTRACT_NAME, // CONTRACT_VERSION, // CHAIN_ID, // VERIFYING_CONTRACT, // SALT // )); bytes32 public constant DOMAIN_SEPARATOR = 0x256c0713d13c6a01bd319a2f7edabde771b6c167d37c01778290d60b362ccc7d; // bytes32 public constant OFFER_TYPEHASH = keccak256(abi.encodePacked( // "Offer(", // "address maker,", // "address offerAssetId,", // "uint256 offerAmount,", // "address wantAssetId,", // "uint256 wantAmount,", // "address feeAssetId,", // "uint256 feeAmount,", // "uint256 nonce", // ")" // )); bytes32 public constant OFFER_TYPEHASH = 0xf845c83a8f7964bc8dd1a092d28b83573b35be97630a5b8a3b8ae2ae79cd9260; // bytes32 public constant CANCEL_TYPEHASH = keccak256(abi.encodePacked( // "Cancel(", // "bytes32 offerHash,", // "address feeAssetId,", // "uint256 feeAmount,", // ")" // )); bytes32 public constant CANCEL_TYPEHASH = 0x46f6d088b1f0ff5a05c3f232c4567f2df96958e05457e6c0e1221dcee7d69c18; // bytes32 public constant FILL_TYPEHASH = keccak256(abi.encodePacked( // "Fill(", // "address filler,", // "address offerAssetId,", // "uint256 offerAmount,", // "address wantAssetId,", // "uint256 wantAmount,", // "address feeAssetId,", // "uint256 feeAmount,", // "uint256 nonce", // ")" // )); bytes32 public constant FILL_TYPEHASH = 0x5f59dbc3412a4575afed909d028055a91a4250ce92235f6790c155a4b2669e99; // The Ether token address is set as the constant 0x00 for backwards // compatibility address private constant ETHER_ADDR = address(0); uint256 private constant mask8 = ~(~uint256(0) << 8); uint256 private constant mask16 = ~(~uint256(0) << 16); uint256 private constant mask24 = ~(~uint256(0) << 24); uint256 private constant mask32 = ~(~uint256(0) << 32); uint256 private constant mask40 = ~(~uint256(0) << 40); uint256 private constant mask48 = ~(~uint256(0) << 48); uint256 private constant mask56 = ~(~uint256(0) << 56); uint256 private constant mask120 = ~(~uint256(0) << 120); uint256 private constant mask128 = ~(~uint256(0) << 128); uint256 private constant mask136 = ~(~uint256(0) << 136); uint256 private constant mask144 = ~(~uint256(0) << 144); event Trade( address maker, address taker, address makerGiveAsset, uint256 makerGiveAmount, address fillerGiveAsset, uint256 fillerGiveAmount ); /// @dev Calculates the balance increments for a set of trades /// @param _values The _values param from the trade method /// @param _incrementsLength Should match the value of _addresses.length / 2 /// from the trade method /// @return An array of increments function calculateTradeIncrements( uint256[] memory _values, uint256 _incrementsLength ) public pure returns (uint256[] memory) { uint256[] memory increments = new uint256[](_incrementsLength); _creditFillBalances(increments, _values); _creditMakerBalances(increments, _values); _creditMakerFeeBalances(increments, _values); return increments; } /// @dev Calculates the balance decrements for a set of trades /// @param _values The _values param from the trade method /// @param _decrementsLength Should match the value of _addresses.length / 2 /// from the trade method /// @return An array of decrements function calculateTradeDecrements( uint256[] memory _values, uint256 _decrementsLength ) public pure returns (uint256[] memory) { uint256[] memory decrements = new uint256[](_decrementsLength); _deductFillBalances(decrements, _values); _deductMakerBalances(decrements, _values); return decrements; } /// @dev Calculates the balance increments for a set of network trades /// @param _values The _values param from the networkTrade method /// @param _incrementsLength Should match the value of _addresses.length / 2 /// from the networkTrade method /// @return An array of increments function calculateNetworkTradeIncrements( uint256[] memory _values, uint256 _incrementsLength ) public pure returns (uint256[] memory) { uint256[] memory increments = new uint256[](_incrementsLength); _creditMakerBalances(increments, _values); _creditMakerFeeBalances(increments, _values); return increments; } /// @dev Calculates the balance decrements for a set of network trades /// @param _values The _values param from the trade method /// @param _decrementsLength Should match the value of _addresses.length / 2 /// from the networkTrade method /// @return An array of decrements function calculateNetworkTradeDecrements( uint256[] memory _values, uint256 _decrementsLength ) public pure returns (uint256[] memory) { uint256[] memory decrements = new uint256[](_decrementsLength); _deductMakerBalances(decrements, _values); return decrements; } /// @dev Validates `BrokerV2.trade` parameters to ensure trade fairness, /// see `BrokerV2.trade` for param details. /// @param _values Values from `trade` /// @param _hashes Hashes from `trade` /// @param _addresses Addresses from `trade` function validateTrades( uint256[] memory _values, bytes32[] memory _hashes, address[] memory _addresses, address _operator ) public returns (bytes32[] memory) { _validateTradeInputLengths(_values, _hashes); _validateUniqueOffers(_values); _validateMatches(_values, _addresses); _validateFillAmounts(_values); _validateTradeData(_values, _addresses, _operator); // validate signatures of all offers _validateTradeSignatures( _values, _hashes, _addresses, OFFER_TYPEHASH, 0, _values[0] & mask8 // numOffers ); // validate signatures of all fills _validateTradeSignatures( _values, _hashes, _addresses, FILL_TYPEHASH, _values[0] & mask8, // numOffers (_values[0] & mask8) + ((_values[0] & mask16) >> 8) // numOffers + numFills ); _emitTradeEvents(_values, _addresses, new address[](0), false); return _hashes; } /// @dev Validates `BrokerV2.networkTrade` parameters to ensure trade fairness, /// see `BrokerV2.networkTrade` for param details. /// @param _values Values from `networkTrade` /// @param _hashes Hashes from `networkTrade` /// @param _addresses Addresses from `networkTrade` /// @param _operator Address of the `BrokerV2.operator` function validateNetworkTrades( uint256[] memory _values, bytes32[] memory _hashes, address[] memory _addresses, address _operator ) public pure returns (bytes32[] memory) { _validateNetworkTradeInputLengths(_values, _hashes); _validateUniqueOffers(_values); _validateNetworkMatches(_values, _addresses, _operator); _validateTradeData(_values, _addresses, _operator); // validate signatures of all offers _validateTradeSignatures( _values, _hashes, _addresses, OFFER_TYPEHASH, 0, _values[0] & mask8 // numOffers ); return _hashes; } /// @dev Executes trades against external markets, /// see `BrokerV2.networkTrade` for param details. /// @param _values Values from `networkTrade` /// @param _addresses Addresses from `networkTrade` /// @param _marketDapps See `BrokerV2.marketDapps` function performNetworkTrades( uint256[] memory _values, address[] memory _addresses, address[] memory _marketDapps ) public returns (uint256[] memory) { uint256[] memory increments = new uint256[](_addresses.length / 2); // i = 1 + numOffers * 2 uint256 i = 1 + (_values[0] & mask8) * 2; uint256 end = _values.length; // loop matches for(i; i < end; i++) { uint256[] memory data = new uint256[](9); data[0] = _values[i]; // match data data[1] = data[0] & mask8; // offerIndex data[2] = (data[0] & mask24) >> 16; // operator.surplusAssetIndex data[3] = _values[data[1] * 2 + 1]; // offer.dataA data[4] = _values[data[1] * 2 + 2]; // offer.dataB data[5] = ((data[3] & mask16) >> 8); // maker.offerAssetIndex data[6] = ((data[3] & mask24) >> 16); // maker.wantAssetIndex // amount of offerAssetId to take from the offer is equal to the match.takeAmount data[7] = data[0] >> 128; // expected amount to receive is: matchData.takeAmount * offer.wantAmount / offer.offerAmount data[8] = data[7].mul(data[4] >> 128).div(data[4] & mask128); address[] memory assetIds = new address[](3); assetIds[0] = _addresses[data[5] * 2 + 1]; // offer.offerAssetId assetIds[1] = _addresses[data[6] * 2 + 1]; // offer.wantAssetId assetIds[2] = _addresses[data[2] * 2 + 1]; // surplusAssetId uint256[] memory dataValues = new uint256[](3); dataValues[0] = data[7]; // the proportion of offerAmount to offer dataValues[1] = data[8]; // the proportion of wantAmount to receive for the offer dataValues[2] = data[0]; // match data increments[data[2]] = _performNetworkTrade( assetIds, dataValues, _marketDapps, _addresses ); } _emitTradeEvents(_values, _addresses, _marketDapps, true); return increments; } /// @dev Validates the signature of a cancel invocation /// @param _values The _values param from the cancel method /// @param _hashes The _hashes param from the cancel method /// @param _addresses The _addresses param from the cancel method function validateCancel( uint256[] memory _values, bytes32[] memory _hashes, address[] memory _addresses ) public pure { bytes32 offerHash = hashOffer(_values, _addresses); bytes32 cancelHash = keccak256(abi.encode( CANCEL_TYPEHASH, offerHash, _addresses[4], _values[1] >> 128 )); validateSignature( cancelHash, _addresses[0], // maker uint8((_values[2] & mask144) >> 136), // v _hashes[0], // r _hashes[1], // s ((_values[2] & mask136) >> 128) != 0 // prefixedSignature ); } /// @dev Hashes an offer for the cancel method /// @param _values The _values param from the cancel method /// @param _addresses THe _addresses param from the cancel method /// @return The hash of the offer function hashOffer( uint256[] memory _values, address[] memory _addresses ) public pure returns (bytes32) { return keccak256(abi.encode( OFFER_TYPEHASH, _addresses[0], // maker _addresses[1], // offerAssetId _values[0] & mask128, // offerAmount _addresses[2], // wantAssetId _values[0] >> 128, // wantAmount _addresses[3], // feeAssetId _values[1] & mask128, // feeAmount _values[2] >> 144 // offerNonce )); } /// @notice Approves a token transfer /// @param _assetId The address of the token to approve /// @param _spender The address of the spender to approve /// @param _amount The number of tokens to approve function approveTokenTransfer( address _assetId, address _spender, uint256 _amount ) public { _validateContractAddress(_assetId); // Some tokens have an `approve` which returns a boolean and some do not. // The ERC20 interface cannot be used here because it requires specifying // an explicit return value, and an EVM exception would be raised when calling // a token with the mismatched return value. bytes memory payload = abi.encodeWithSignature( "approve(address,uint256)", _spender, _amount ); bytes memory returnData = _callContract(_assetId, payload); // Ensure that the asset transfer succeeded _validateContractCallResult(returnData); } /// @notice Transfers tokens into the contract /// @param _user The address to transfer the tokens from /// @param _assetId The address of the token to transfer /// @param _amount The number of tokens to transfer /// @param _expectedAmount The number of tokens expected to be received, /// this may not match `_amount`, for example, tokens which have a /// proportion burnt on transfer will have a different amount received. function transferTokensIn( address _user, address _assetId, uint256 _amount, uint256 _expectedAmount ) public { _validateContractAddress(_assetId); uint256 initialBalance = tokenBalance(_assetId); // Some tokens have a `transferFrom` which returns a boolean and some do not. // The ERC20 interface cannot be used here because it requires specifying // an explicit return value, and an EVM exception would be raised when calling // a token with the mismatched return value. bytes memory payload = abi.encodeWithSignature( "transferFrom(address,address,uint256)", _user, address(this), _amount ); bytes memory returnData = _callContract(_assetId, payload); // Ensure that the asset transfer succeeded _validateContractCallResult(returnData); uint256 finalBalance = tokenBalance(_assetId); uint256 transferredAmount = finalBalance.sub(initialBalance); require(transferredAmount == _expectedAmount, "Invalid transfer"); } /// @notice Transfers tokens from the contract to a user /// @param _receivingAddress The address to transfer the tokens to /// @param _assetId The address of the token to transfer /// @param _amount The number of tokens to transfer function transferTokensOut( address _receivingAddress, address _assetId, uint256 _amount ) public { _validateContractAddress(_assetId); // Some tokens have a `transfer` which returns a boolean and some do not. // The ERC20 interface cannot be used here because it requires specifying // an explicit return value, and an EVM exception would be raised when calling // a token with the mismatched return value. bytes memory payload = abi.encodeWithSignature( "transfer(address,uint256)", _receivingAddress, _amount ); bytes memory returnData = _callContract(_assetId, payload); // Ensure that the asset transfer succeeded _validateContractCallResult(returnData); } /// @notice Returns the number of tokens owned by this contract /// @param _assetId The address of the token to query function externalBalance(address _assetId) public view returns (uint256) { if (_assetId == ETHER_ADDR) { return address(this).balance; } return tokenBalance(_assetId); } /// @notice Returns the number of tokens owned by this contract. /// @dev This will not work for Ether tokens, use `externalBalance` for /// Ether tokens. /// @param _assetId The address of the token to query function tokenBalance(address _assetId) public view returns (uint256) { return ERC20(_assetId).balanceOf(address(this)); } /// @dev Validates that the specified `_hash` was signed by the specified `_user`. /// This method supports the EIP712 specification, the older Ethereum /// signed message specification is also supported for backwards compatibility. /// @param _hash The original hash that was signed by the user /// @param _user The user who signed the hash /// @param _v The `v` component of the `_user`'s signature /// @param _r The `r` component of the `_user`'s signature /// @param _s The `s` component of the `_user`'s signature /// @param _prefixed If true, the signature will be verified /// against the Ethereum signed message specification instead of the /// EIP712 specification function validateSignature( bytes32 _hash, address _user, uint8 _v, bytes32 _r, bytes32 _s, bool _prefixed ) public pure { bytes32 eip712Hash = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, _hash )); if (_prefixed) { bytes32 prefixedHash = keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", eip712Hash )); require(_user == ecrecover(prefixedHash, _v, _r, _s), "Invalid signature"); } else { require(_user == ecrecover(eip712Hash, _v, _r, _s), "Invalid signature"); } } /// @dev Ensures that `_address` is not the zero address /// @param _address The address to check function validateAddress(address _address) public pure { require(_address != address(0), "Invalid address"); } /// @dev Credit fillers for each fill.wantAmount,and credit the operator /// for each fill.feeAmount. See the `trade` method for param details. /// @param _values Values from `trade` function _creditFillBalances( uint256[] memory _increments, uint256[] memory _values ) private pure { // 1 + numOffers * 2 uint256 i = 1 + (_values[0] & mask8) * 2; // i + numFills * 2 uint256 end = i + ((_values[0] & mask16) >> 8) * 2; // loop fills for(i; i < end; i += 2) { uint256 fillerWantAssetIndex = (_values[i] & mask24) >> 16; uint256 wantAmount = _values[i + 1] >> 128; // credit fill.wantAmount to filler _increments[fillerWantAssetIndex] = _increments[fillerWantAssetIndex].add(wantAmount); uint256 feeAmount = _values[i] >> 128; if (feeAmount == 0) { continue; } uint256 operatorFeeAssetIndex = ((_values[i] & mask40) >> 32); // credit fill.feeAmount to operator _increments[operatorFeeAssetIndex] = _increments[operatorFeeAssetIndex].add(feeAmount); } } /// @dev Credit makers for each amount received through a matched fill. /// See the `trade` method for param details. /// @param _values Values from `trade` function _creditMakerBalances( uint256[] memory _increments, uint256[] memory _values ) private pure { uint256 i = 1; // i += numOffers * 2 i += (_values[0] & mask8) * 2; // i += numFills * 2 i += ((_values[0] & mask16) >> 8) * 2; uint256 end = _values.length; // loop matches for(i; i < end; i++) { // match.offerIndex uint256 offerIndex = _values[i] & mask8; // maker.wantAssetIndex uint256 makerWantAssetIndex = (_values[1 + offerIndex * 2] & mask24) >> 16; // match.takeAmount uint256 amount = _values[i] >> 128; // receiveAmount = match.takeAmount * offer.wantAmount / offer.offerAmount amount = amount.mul(_values[2 + offerIndex * 2] >> 128) .div(_values[2 + offerIndex * 2] & mask128); // credit maker for the amount received from the match _increments[makerWantAssetIndex] = _increments[makerWantAssetIndex].add(amount); } } /// @dev Credit the operator for each offer.feeAmount if the offer has not /// been recorded through a previous `trade` call. /// See the `trade` method for param details. /// @param _values Values from `trade` function _creditMakerFeeBalances( uint256[] memory _increments, uint256[] memory _values ) private pure { uint256 i = 1; // i + numOffers * 2 uint256 end = i + (_values[0] & mask8) * 2; // loop offers for(i; i < end; i += 2) { bool nonceTaken = ((_values[i] & mask128) >> 120) == 1; if (nonceTaken) { continue; } uint256 feeAmount = _values[i] >> 128; if (feeAmount == 0) { continue; } uint256 operatorFeeAssetIndex = (_values[i] & mask40) >> 32; // credit make.feeAmount to operator _increments[operatorFeeAssetIndex] = _increments[operatorFeeAssetIndex].add(feeAmount); } } /// @dev Deduct tokens from fillers for each fill.offerAmount /// and each fill.feeAmount. /// See the `trade` method for param details. /// @param _values Values from `trade` function _deductFillBalances( uint256[] memory _decrements, uint256[] memory _values ) private pure { // 1 + numOffers * 2 uint256 i = 1 + (_values[0] & mask8) * 2; // i + numFills * 2 uint256 end = i + ((_values[0] & mask16) >> 8) * 2; // loop fills for(i; i < end; i += 2) { uint256 fillerOfferAssetIndex = (_values[i] & mask16) >> 8; uint256 offerAmount = _values[i + 1] & mask128; // deduct fill.offerAmount from filler _decrements[fillerOfferAssetIndex] = _decrements[fillerOfferAssetIndex].add(offerAmount); uint256 feeAmount = _values[i] >> 128; if (feeAmount == 0) { continue; } // deduct fill.feeAmount from filler uint256 fillerFeeAssetIndex = (_values[i] & mask32) >> 24; _decrements[fillerFeeAssetIndex] = _decrements[fillerFeeAssetIndex].add(feeAmount); } } /// @dev Deduct tokens from makers for each offer.offerAmount /// and each offer.feeAmount if the offer has not been recorded /// through a previous `trade` call. /// See the `trade` method for param details. /// @param _values Values from `trade` function _deductMakerBalances( uint256[] memory _decrements, uint256[] memory _values ) private pure { uint256 i = 1; // i + numOffers * 2 uint256 end = i + (_values[0] & mask8) * 2; // loop offers for(i; i < end; i += 2) { bool nonceTaken = ((_values[i] & mask128) >> 120) == 1; if (nonceTaken) { continue; } uint256 makerOfferAssetIndex = (_values[i] & mask16) >> 8; uint256 offerAmount = _values[i + 1] & mask128; // deduct make.offerAmount from maker _decrements[makerOfferAssetIndex] = _decrements[makerOfferAssetIndex].add(offerAmount); uint256 feeAmount = _values[i] >> 128; if (feeAmount == 0) { continue; } // deduct make.feeAmount from maker uint256 makerFeeAssetIndex = (_values[i] & mask32) >> 24; _decrements[makerFeeAssetIndex] = _decrements[makerFeeAssetIndex].add(feeAmount); } } /// @dev Emits trade events for easier tracking /// @param _values The _values param from the trade / networkTrade method /// @param _addresses The _addresses param from the trade / networkTrade method /// @param _marketDapps The _marketDapps from BrokerV2 /// @param _forNetworkTrade Whether this is called from the networkTrade method function _emitTradeEvents( uint256[] memory _values, address[] memory _addresses, address[] memory _marketDapps, bool _forNetworkTrade ) private { uint256 i = 1; // i += numOffers * 2 i += (_values[0] & mask8) * 2; // i += numFills * 2 i += ((_values[0] & mask16) >> 8) * 2; uint256 end = _values.length; // loop matches for(i; i < end; i++) { uint256[] memory data = new uint256[](7); data[0] = _values[i] & mask8; // match.offerIndex data[1] = _values[1 + data[0] * 2] & mask8; // makerIndex data[2] = (_values[1 + data[0] * 2] & mask16) >> 8; // makerOfferAssetIndex data[3] = (_values[1 + data[0] * 2] & mask24) >> 16; // makerWantAssetIndex data[4] = _values[i] >> 128; // match.takeAmount // receiveAmount = match.takeAmount * offer.wantAmount / offer.offerAmount data[5] = data[4].mul(_values[2 + data[0] * 2] >> 128) .div(_values[2 + data[0] * 2] & mask128); // match.fillIndex for `trade`, marketDappIndex for `networkTrade` data[6] = (_values[i] & mask16) >> 8; address filler; if (_forNetworkTrade) { filler = _marketDapps[data[6]]; } else { uint256 fillerIndex = (_values[1 + data[6] * 2] & mask8); filler = _addresses[fillerIndex * 2]; } emit Trade( _addresses[data[1] * 2], // maker filler, _addresses[data[2] * 2 + 1], // makerGiveAsset data[4], // makerGiveAmount _addresses[data[3] * 2 + 1], // fillerGiveAsset data[5] // fillerGiveAmount ); } } /// @notice Executes a trade against an external market. /// @dev The initial Ether or token balance is compared with the /// balance after the trade to ensure that the appropriate amounts of /// tokens were taken and an appropriate amount received. /// The trade will fail if the number of tokens received is less than /// expected. If the number of tokens received is more than expected than /// the excess tokens are transferred to the `BrokerV2.operator`. /// @param _assetIds[0] The offerAssetId of the offer /// @param _assetIds[1] The wantAssetId of the offer /// @param _assetIds[2] The surplusAssetId /// @param _dataValues[0] The number of tokens offerred /// @param _dataValues[1] The number of tokens expected to be received /// @param _dataValues[2] Match data /// @param _marketDapps See `BrokerV2.marketDapps` /// @param _addresses Addresses from `networkTrade` function _performNetworkTrade( address[] memory _assetIds, uint256[] memory _dataValues, address[] memory _marketDapps, address[] memory _addresses ) private returns (uint256) { uint256 dappIndex = (_dataValues[2] & mask16) >> 8; validateAddress(_marketDapps[dappIndex]); MarketDapp marketDapp = MarketDapp(_marketDapps[dappIndex]); uint256[] memory funds = new uint256[](6); funds[0] = externalBalance(_assetIds[0]); // initialOfferTokenBalance funds[1] = externalBalance(_assetIds[1]); // initialWantTokenBalance if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) { funds[2] = externalBalance(_assetIds[2]); // initialSurplusTokenBalance } uint256 ethValue = 0; address tokenReceiver; if (_assetIds[0] == ETHER_ADDR) { ethValue = _dataValues[0]; // offerAmount } else { tokenReceiver = marketDapp.tokenReceiver(_assetIds, _dataValues, _addresses); approveTokenTransfer( _assetIds[0], // offerAssetId tokenReceiver, _dataValues[0] // offerAmount ); } marketDapp.trade.value(ethValue)( _assetIds, _dataValues, _addresses, // use uint160 to cast `address` to `address payable` address(uint160(address(this))) // destAddress ); funds[3] = externalBalance(_assetIds[0]); // finalOfferTokenBalance funds[4] = externalBalance(_assetIds[1]); // finalWantTokenBalance if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) { funds[5] = externalBalance(_assetIds[2]); // finalSurplusTokenBalance } uint256 surplusAmount = 0; // validate that the appropriate offerAmount was deducted // surplusAssetId == offerAssetId if (_assetIds[2] == _assetIds[0]) { // surplusAmount = finalOfferTokenBalance - (initialOfferTokenBalance - offerAmount) surplusAmount = funds[3].sub(funds[0].sub(_dataValues[0])); } else { // finalOfferTokenBalance == initialOfferTokenBalance - offerAmount require(funds[3] == funds[0].sub(_dataValues[0]), "Invalid offer asset balance"); } // validate that the appropriate wantAmount was credited // surplusAssetId == wantAssetId if (_assetIds[2] == _assetIds[1]) { // surplusAmount = finalWantTokenBalance - (initialWantTokenBalance + wantAmount) surplusAmount = funds[4].sub(funds[1].add(_dataValues[1])); } else { // finalWantTokenBalance == initialWantTokenBalance + wantAmount require(funds[4] == funds[1].add(_dataValues[1]), "Invalid want asset balance"); } // surplusAssetId != offerAssetId && surplusAssetId != wantAssetId if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) { // surplusAmount = finalSurplusTokenBalance - initialSurplusTokenBalance surplusAmount = funds[5].sub(funds[2]); } // set the approved token amount back to zero if (_assetIds[0] != ETHER_ADDR) { approveTokenTransfer( _assetIds[0], tokenReceiver, 0 ); } return surplusAmount; } /// @dev Validates input lengths based on the expected format /// detailed in the `trade` method. /// @param _values Values from `trade` /// @param _hashes Hashes from `trade` function _validateTradeInputLengths( uint256[] memory _values, bytes32[] memory _hashes ) private pure { uint256 numOffers = _values[0] & mask8; uint256 numFills = (_values[0] & mask16) >> 8; uint256 numMatches = (_values[0] & mask24) >> 16; // Validate that bits(24..256) are zero require(_values[0] >> 24 == 0, "Invalid trade input"); // It is enforced by other checks that if a fill is present // then it must be completely filled so there must be at least one offer // and at least one match in this case. // It is possible to have one offer with no matches and no fills // but that is blocked by this check as there is no foreseeable use // case for it. require( numOffers > 0 && numFills > 0 && numMatches > 0, "Invalid trade input" ); require( _values.length == 1 + numOffers * 2 + numFills * 2 + numMatches, "Invalid _values.length" ); require( _hashes.length == (numOffers + numFills) * 2, "Invalid _hashes.length" ); } /// @dev Validates input lengths based on the expected format /// detailed in the `networkTrade` method. /// @param _values Values from `networkTrade` /// @param _hashes Hashes from `networkTrade` function _validateNetworkTradeInputLengths( uint256[] memory _values, bytes32[] memory _hashes ) private pure { uint256 numOffers = _values[0] & mask8; uint256 numFills = (_values[0] & mask16) >> 8; uint256 numMatches = (_values[0] & mask24) >> 16; // Validate that bits(24..256) are zero require(_values[0] >> 24 == 0, "Invalid networkTrade input"); // Validate that numFills is zero because the offers // should be filled against external orders require( numOffers > 0 && numMatches > 0 && numFills == 0, "Invalid networkTrade input" ); require( _values.length == 1 + numOffers * 2 + numMatches, "Invalid _values.length" ); require( _hashes.length == numOffers * 2, "Invalid _hashes.length" ); } /// @dev See the `BrokerV2.trade` method for an explanation of why offer /// uniquness is required. /// The set of offers in `_values` must be sorted such that offer nonces' /// are arranged in a strictly ascending order. /// This allows the validation of offer uniqueness to be done in O(N) time, /// with N being the number of offers. /// @param _values Values from `trade` function _validateUniqueOffers(uint256[] memory _values) private pure { uint256 numOffers = _values[0] & mask8; uint256 prevNonce; for(uint256 i = 0; i < numOffers; i++) { uint256 nonce = (_values[i * 2 + 1] & mask120) >> 56; if (i == 0) { // Set the value of the first nonce prevNonce = nonce; continue; } require(nonce > prevNonce, "Invalid offer nonces"); prevNonce = nonce; } } /// @dev Validate that for every match: /// 1. offerIndexes fall within the range of offers /// 2. fillIndexes falls within the range of fills /// 3. offer.offerAssetId == fill.wantAssetId /// 4. offer.wantAssetId == fill.offerAssetId /// 5. takeAmount > 0 /// 6. (offer.wantAmount * takeAmount) % offer.offerAmount == 0 /// @param _values Values from `trade` /// @param _addresses Addresses from `trade` function _validateMatches( uint256[] memory _values, address[] memory _addresses ) private pure { uint256 numOffers = _values[0] & mask8; uint256 numFills = (_values[0] & mask16) >> 8; uint256 i = 1 + numOffers * 2 + numFills * 2; uint256 end = _values.length; // loop matches for (i; i < end; i++) { uint256 offerIndex = _values[i] & mask8; uint256 fillIndex = (_values[i] & mask16) >> 8; require(offerIndex < numOffers, "Invalid match.offerIndex"); require(fillIndex >= numOffers && fillIndex < numOffers + numFills, "Invalid match.fillIndex"); require( _addresses[_values[1 + offerIndex * 2] & mask8] != _addresses[_values[1 + fillIndex * 2] & mask8], "offer.maker cannot be the same as fill.filler" ); uint256 makerOfferAssetIndex = (_values[1 + offerIndex * 2] & mask16) >> 8; uint256 makerWantAssetIndex = (_values[1 + offerIndex * 2] & mask24) >> 16; uint256 fillerOfferAssetIndex = (_values[1 + fillIndex * 2] & mask16) >> 8; uint256 fillerWantAssetIndex = (_values[1 + fillIndex * 2] & mask24) >> 16; require( _addresses[makerOfferAssetIndex * 2 + 1] == _addresses[fillerWantAssetIndex * 2 + 1], "offer.offerAssetId does not match fill.wantAssetId" ); require( _addresses[makerWantAssetIndex * 2 + 1] == _addresses[fillerOfferAssetIndex * 2 + 1], "offer.wantAssetId does not match fill.offerAssetId" ); // require that bits(16..128) are all zero for every match require((_values[i] & mask128) >> 16 == uint256(0), "Invalid match data"); uint256 takeAmount = _values[i] >> 128; require(takeAmount > 0, "Invalid match.takeAmount"); uint256 offerDataB = _values[2 + offerIndex * 2]; // (offer.wantAmount * takeAmount) % offer.offerAmount == 0 require( (offerDataB >> 128).mul(takeAmount).mod(offerDataB & mask128) == 0, "Invalid amounts" ); } } /// @dev Validate that for every match: /// 1. offerIndexes fall within the range of offers /// 2. _addresses[surplusAssetIndexes * 2] matches the operator address /// 3. takeAmount > 0 /// 4. (offer.wantAmount * takeAmount) % offer.offerAmount == 0 /// @param _values Values from `trade` /// @param _addresses Addresses from `trade` /// @param _operator Address of the `BrokerV2.operator` function _validateNetworkMatches( uint256[] memory _values, address[] memory _addresses, address _operator ) private pure { uint256 numOffers = _values[0] & mask8; // 1 + numOffers * 2 uint256 i = 1 + (_values[0] & mask8) * 2; uint256 end = _values.length; // loop matches for (i; i < end; i++) { uint256 offerIndex = _values[i] & mask8; uint256 surplusAssetIndex = (_values[i] & mask24) >> 16; require(offerIndex < numOffers, "Invalid match.offerIndex"); require(_addresses[surplusAssetIndex * 2] == _operator, "Invalid operator address"); uint256 takeAmount = _values[i] >> 128; require(takeAmount > 0, "Invalid match.takeAmount"); uint256 offerDataB = _values[2 + offerIndex * 2]; // (offer.wantAmount * takeAmount) % offer.offerAmount == 0 require( (offerDataB >> 128).mul(takeAmount).mod(offerDataB & mask128) == 0, "Invalid amounts" ); } } /// @dev Validate that all fills will be completely filled by the specified /// matches. See the `BrokerV2.trade` method for an explanation of why /// fills must be completely filled. /// @param _values Values from `trade` function _validateFillAmounts(uint256[] memory _values) private pure { // "filled" is used to store the sum of `takeAmount`s and `giveAmount`s. // While a fill's `offerAmount` and `wantAmount` are combined to share // a single uint256 value, each sum of `takeAmount`s and `giveAmount`s // for a fill is tracked with an individual uint256 value. // This is to prevent the verification from being vulnerable to overflow // issues. uint256[] memory filled = new uint256[](_values.length); uint256 i = 1; // i += numOffers * 2 i += (_values[0] & mask8) * 2; // i += numFills * 2 i += ((_values[0] & mask16) >> 8) * 2; uint256 end = _values.length; // loop matches for (i; i < end; i++) { uint256 offerIndex = _values[i] & mask8; uint256 fillIndex = (_values[i] & mask16) >> 8; uint256 takeAmount = _values[i] >> 128; uint256 wantAmount = _values[2 + offerIndex * 2] >> 128; uint256 offerAmount = _values[2 + offerIndex * 2] & mask128; // giveAmount = takeAmount * wantAmount / offerAmount uint256 giveAmount = takeAmount.mul(wantAmount).div(offerAmount); // (1 + fillIndex * 2) would give the index of the first part // of the data for the fill at fillIndex within `_values`, // and (2 + fillIndex * 2) would give the index of the second part filled[1 + fillIndex * 2] = filled[1 + fillIndex * 2].add(giveAmount); filled[2 + fillIndex * 2] = filled[2 + fillIndex * 2].add(takeAmount); } // numOffers i = _values[0] & mask8; // i + numFills end = i + ((_values[0] & mask16) >> 8); // loop fills for(i; i < end; i++) { require( // fill.offerAmount == (sum of given amounts for fill) _values[i * 2 + 2] & mask128 == filled[i * 2 + 1] && // fill.wantAmount == (sum of taken amounts for fill) _values[i * 2 + 2] >> 128 == filled[i * 2 + 2], "Invalid fills" ); } } /// @dev Validates that for every offer / fill /// 1. user address matches address referenced by user.offerAssetIndex /// 2. user address matches address referenced by user.wantAssetIndex /// 3. user address matches address referenced by user.feeAssetIndex /// 4. offerAssetId != wantAssetId /// 5. offerAmount > 0 && wantAmount > 0 /// 6. Specified `operator` address matches the expected `operator` address, /// 7. Specified `operator.feeAssetId` matches the offer's feeAssetId /// @param _values Values from `trade` /// @param _addresses Addresses from `trade` function _validateTradeData( uint256[] memory _values, address[] memory _addresses, address _operator ) private pure { // numOffers + numFills uint256 end = (_values[0] & mask8) + ((_values[0] & mask16) >> 8); for (uint256 i = 0; i < end; i++) { uint256 dataA = _values[i * 2 + 1]; uint256 dataB = _values[i * 2 + 2]; uint256 feeAssetIndex = ((dataA & mask40) >> 32) * 2; require( // user address == user in user.offerAssetIndex pair _addresses[(dataA & mask8) * 2] == _addresses[((dataA & mask16) >> 8) * 2], "Invalid user in user.offerAssetIndex" ); require( // user address == user in user.wantAssetIndex pair _addresses[(dataA & mask8) * 2] == _addresses[((dataA & mask24) >> 16) * 2], "Invalid user in user.wantAssetIndex" ); require( // user address == user in user.feeAssetIndex pair _addresses[(dataA & mask8) * 2] == _addresses[((dataA & mask32) >> 24) * 2], "Invalid user in user.feeAssetIndex" ); require( // offerAssetId != wantAssetId _addresses[((dataA & mask16) >> 8) * 2 + 1] != _addresses[((dataA & mask24) >> 16) * 2 + 1], "Invalid trade assets" ); require( // offerAmount > 0 && wantAmount > 0 (dataB & mask128) > 0 && (dataB >> 128) > 0, "Invalid trade amounts" ); require( _addresses[feeAssetIndex] == _operator, "Invalid operator address" ); require( _addresses[feeAssetIndex + 1] == _addresses[((dataA & mask32) >> 24) * 2 + 1], "Invalid operator fee asset ID" ); } } /// @dev Validates signatures for a set of offers or fills /// Note that the r value of the offer / fill in _hashes will be /// overwritten by the hash of that offer / fill /// @param _values Values from `trade` /// @param _hashes Hashes from `trade` /// @param _addresses Addresses from `trade` /// @param _typehash The typehash used to construct the signed hash /// @param _i The starting index to verify /// @param _end The ending index to verify /// @return An array of hash keys if _i started as 0, because only /// the hash keys of offers are needed function _validateTradeSignatures( uint256[] memory _values, bytes32[] memory _hashes, address[] memory _addresses, bytes32 _typehash, uint256 _i, uint256 _end ) private pure { for (_i; _i < _end; _i++) { uint256 dataA = _values[_i * 2 + 1]; uint256 dataB = _values[_i * 2 + 2]; bytes32 hashKey = keccak256(abi.encode( _typehash, _addresses[(dataA & mask8) * 2], // user _addresses[((dataA & mask16) >> 8) * 2 + 1], // offerAssetId dataB & mask128, // offerAmount _addresses[((dataA & mask24) >> 16) * 2 + 1], // wantAssetId dataB >> 128, // wantAmount _addresses[((dataA & mask32) >> 24) * 2 + 1], // feeAssetId dataA >> 128, // feeAmount (dataA & mask120) >> 56 // nonce )); bool prefixedSignature = ((dataA & mask56) >> 48) != 0; validateSignature( hashKey, _addresses[(dataA & mask8) * 2], // user uint8((dataA & mask48) >> 40), // The `v` component of the user's signature _hashes[_i * 2], // The `r` component of the user's signature _hashes[_i * 2 + 1], // The `s` component of the user's signature prefixedSignature ); _hashes[_i * 2] = hashKey; } } /// @dev Ensure that the address is a deployed contract /// @param _contract The address to check function _validateContractAddress(address _contract) private view { assembly { if iszero(extcodesize(_contract)) { revert(0, 0) } } } /// @dev A thin wrapper around the native `call` function, to /// validate that the contract `call` must be successful. /// See https://solidity.readthedocs.io/en/v0.5.1/050-breaking-changes.html /// for details on constructing the `_payload` /// @param _contract Address of the contract to call /// @param _payload The data to call the contract with /// @return The data returned from the contract call function _callContract( address _contract, bytes memory _payload ) private returns (bytes memory) { bool success; bytes memory returnData; (success, returnData) = _contract.call(_payload); require(success, "Contract call failed"); return returnData; } /// @dev Fix for ERC-20 tokens that do not have proper return type /// See: https://github.com/ethereum/solidity/issues/4116 /// https://medium.com/loopring-protocol/an-incompatibility-in-smart-contract-threatening-dapp-ecosystem-72b8ca5db4da /// https://github.com/sec-bit/badERC20Fix/blob/master/badERC20Fix.sol /// @param _data The data returned from a transfer call function _validateContractCallResult(bytes memory _data) private pure { require( _data.length == 0 || (_data.length == 32 && _getUint256FromBytes(_data) != 0), "Invalid contract call result" ); } /// @dev Converts data of type `bytes` into its corresponding `uint256` value /// @param _data The data in bytes /// @return The corresponding `uint256` value function _getUint256FromBytes( bytes memory _data ) private pure returns (uint256) { uint256 parsed; assembly { parsed := mload(add(_data, 32)) } return parsed; } } // File: contracts/BrokerV2.sol pragma solidity 0.5.12; interface IERC1820Registry { function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; } interface TokenList { function validateToken(address assetId) external view; } interface SpenderList { function validateSpender(address spender) external view; function validateSpenderAuthorization(address user, address spender) external view; } /// @title The BrokerV2 contract for Switcheo Exchange /// @author Switcheo Network /// @notice This contract faciliates Ethereum and Ethereum token trades /// between users. /// Users can trade with each other by making and taking offers without /// giving up custody of their tokens. /// Users should first deposit tokens, then communicate off-chain /// with the exchange coordinator, in order to place orders. /// This allows trades to be confirmed immediately by the coordinator, /// and settled on-chain through this contract at a later time. /// /// @dev Bit compacting is used in the contract to reduce gas costs, when /// it is used, params are documented as bits(n..m). /// This means that the documented value is represented by bits starting /// from and including `n`, up to and excluding `m`. /// For example, bits(8..16), indicates that the value is represented by bits: /// [8, 9, 10, 11, 12, 13, 14, 15]. /// /// Bit manipulation of the form (data & ~(~uint(0) << m)) >> n is frequently /// used to recover the value at the specified bits. /// For example, to recover bits(2..7) from a uint8 value, we can use /// (data & ~(~uint8(0) << 7)) >> 2. /// Given a `data` value of `1101,0111`, bits(2..7) should give "10101". /// ~uint8(0): "1111,1111" (8 ones) /// (~uint8(0) << 7): "1000,0000" (1 followed by 7 zeros) /// ~(~uint8(0) << 7): "0111,1111" (0 followed by 7 ones) /// (data & ~(~uint8(0) << 7)): "0101,0111" (bits after the 7th bit is zeroed) /// (data & ~(~uint8(0) << 7)) >> 2: "0001,0101" (matching the expected "10101") /// /// Additionally, bit manipulation of the form data >> n is used to recover /// bits(n..e), where e is equal to the number of bits in the data. /// For example, to recover bits(4..8) from a uint8 value, we can use data >> 4. /// Given a data value of "1111,1111", bits(4..8) should give "1111". /// data >> 4: "0000,1111" (matching the expected "1111") /// /// There is frequent reference and usage of asset IDs, this is a unique /// identifier used within the contract to represent individual assets. /// For all tokens, the asset ID is identical to the contract address /// of the token, this is so that additional mappings are not needed to /// identify tokens during deposits and withdrawals. /// The only exception is the Ethereum token, which does not have a contract /// address, for this reason, the zero address is used to represent the /// Ethereum token's ID. contract BrokerV2 is Ownable, ReentrancyGuard { using SafeMath for uint256; struct WithdrawalAnnouncement { uint256 amount; uint256 withdrawableAt; } // Exchange states enum State { Active, Inactive } // Exchange admin states enum AdminState { Normal, Escalated } // The constants for EIP-712 are precompiled to reduce contract size, // the original values are left here for reference and verification. // // bytes32 public constant WITHDRAW_TYPEHASH = keccak256(abi.encodePacked( // "Withdraw(", // "address withdrawer,", // "address receivingAddress,", // "address assetId,", // "uint256 amount,", // "address feeAssetId,", // "uint256 feeAmount,", // "uint256 nonce", // ")" // )); bytes32 public constant WITHDRAW_TYPEHASH = 0xbe2f4292252fbb88b129dc7717b2f3f74a9afb5b13a2283cac5c056117b002eb; // bytes32 public constant OFFER_TYPEHASH = keccak256(abi.encodePacked( // "Offer(", // "address maker,", // "address offerAssetId,", // "uint256 offerAmount,", // "address wantAssetId,", // "uint256 wantAmount,", // "address feeAssetId,", // "uint256 feeAmount,", // "uint256 nonce", // ")" // )); bytes32 public constant OFFER_TYPEHASH = 0xf845c83a8f7964bc8dd1a092d28b83573b35be97630a5b8a3b8ae2ae79cd9260; // bytes32 public constant SWAP_TYPEHASH = keccak256(abi.encodePacked( // "Swap(", // "address maker,", // "address taker,", // "address assetId,", // "uint256 amount,", // "bytes32 hashedSecret,", // "uint256 expiryTime,", // "address feeAssetId,", // "uint256 feeAmount,", // "uint256 nonce", // ")" // )); bytes32 public constant SWAP_TYPEHASH = 0x6ba9001457a287c210b728198a424a4222098d7fac48f8c5fb5ab10ef907d3ef; // The Ether token address is set as the constant 0x00 for backwards // compatibility address private constant ETHER_ADDR = address(0); // The maximum length of swap secret values uint256 private constant MAX_SWAP_SECRET_LENGTH = 64; // Reason codes are used by the off-chain coordinator to track balance changes uint256 private constant REASON_DEPOSIT = 0x01; uint256 private constant REASON_WITHDRAW = 0x09; uint256 private constant REASON_WITHDRAW_FEE_GIVE = 0x14; uint256 private constant REASON_WITHDRAW_FEE_RECEIVE = 0x15; uint256 private constant REASON_CANCEL = 0x08; uint256 private constant REASON_CANCEL_FEE_GIVE = 0x12; uint256 private constant REASON_CANCEL_FEE_RECEIVE = 0x13; uint256 private constant REASON_SWAP_GIVE = 0x30; uint256 private constant REASON_SWAP_FEE_GIVE = 0x32; uint256 private constant REASON_SWAP_RECEIVE = 0x35; uint256 private constant REASON_SWAP_FEE_RECEIVE = 0x37; uint256 private constant REASON_SWAP_CANCEL_RECEIVE = 0x38; uint256 private constant REASON_SWAP_CANCEL_FEE_RECEIVE = 0x3B; uint256 private constant REASON_SWAP_CANCEL_FEE_REFUND = 0x3D; // 7 days * 24 hours * 60 mins * 60 seconds: 604800 uint256 private constant MAX_SLOW_WITHDRAW_DELAY = 604800; uint256 private constant MAX_SLOW_CANCEL_DELAY = 604800; uint256 private constant mask8 = ~(~uint256(0) << 8); uint256 private constant mask16 = ~(~uint256(0) << 16); uint256 private constant mask24 = ~(~uint256(0) << 24); uint256 private constant mask32 = ~(~uint256(0) << 32); uint256 private constant mask40 = ~(~uint256(0) << 40); uint256 private constant mask120 = ~(~uint256(0) << 120); uint256 private constant mask128 = ~(~uint256(0) << 128); uint256 private constant mask136 = ~(~uint256(0) << 136); uint256 private constant mask144 = ~(~uint256(0) << 144); State public state; AdminState public adminState; // All fees will be transferred to the operator address address public operator; TokenList public tokenList; SpenderList public spenderList; // The delay in seconds to complete the respective escape hatch (`slowCancel` / `slowWithdraw`). // This gives the off-chain service time to update the off-chain state // before the state is separately updated by the user. uint256 public slowCancelDelay; uint256 public slowWithdrawDelay; // A mapping of remaining offer amounts: offerHash => availableAmount mapping(bytes32 => uint256) public offers; // A mapping of used nonces: nonceIndex => nonceData // The storing of nonces is used to ensure that transactions signed by // the user can only be used once. // For space and gas cost efficiency, one nonceData is used to store the // state of 256 nonces. // This reduces the average cost of storing a new nonce from 20,000 gas // to 5000 + 20,000 / 256 = 5078.125 gas // See _markNonce and _nonceTaken for more details. mapping(uint256 => uint256) public usedNonces; // A mapping of user balances: userAddress => assetId => balance mapping(address => mapping(address => uint256)) public balances; // A mapping of atomic swap states: swapHash => isSwapActive mapping(bytes32 => bool) public atomicSwaps; // A record of admin addresses: userAddress => isAdmin mapping(address => bool) public adminAddresses; // A record of market DApp addresses address[] public marketDapps; // A mapping of cancellation announcements for the cancel escape hatch: offerHash => cancellableAt mapping(bytes32 => uint256) public cancellationAnnouncements; // A mapping of withdrawal announcements: userAddress => assetId => { amount, withdrawableAt } mapping(address => mapping(address => WithdrawalAnnouncement)) public withdrawalAnnouncements; // Emitted on positive balance state transitions event BalanceIncrease( address indexed user, address indexed assetId, uint256 amount, uint256 reason, uint256 nonce ); // Emitted on negative balance state transitions event BalanceDecrease( address indexed user, address indexed assetId, uint256 amount, uint256 reason, uint256 nonce ); // Compacted versions of the `BalanceIncrease` and `BalanceDecrease` events. // These are used in the `trade` method, they are compacted to save gas costs. event Increment(uint256 data); event Decrement(uint256 data); event TokenFallback( address indexed user, address indexed assetId, uint256 amount ); event TokensReceived( address indexed user, address indexed assetId, uint256 amount ); event AnnounceCancel( bytes32 indexed offerHash, uint256 cancellableAt ); event SlowCancel( bytes32 indexed offerHash, uint256 amount ); event AnnounceWithdraw( address indexed withdrawer, address indexed assetId, uint256 amount, uint256 withdrawableAt ); event SlowWithdraw( address indexed withdrawer, address indexed assetId, uint256 amount ); /// @notice Initializes the Broker contract /// @dev The coordinator, operator and owner (through Ownable) is initialized /// to be the address of the sender. /// The Broker is put into an active state, with maximum exit delays set. /// The Broker is also registered as an implementer of ERC777TokensRecipient /// through the ERC1820 registry. constructor(address _tokenListAddress, address _spenderListAddress) public { adminAddresses[msg.sender] = true; operator = msg.sender; tokenList = TokenList(_tokenListAddress); spenderList = SpenderList(_spenderListAddress); slowWithdrawDelay = MAX_SLOW_WITHDRAW_DELAY; slowCancelDelay = MAX_SLOW_CANCEL_DELAY; state = State.Active; IERC1820Registry erc1820 = IERC1820Registry( 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24 ); erc1820.setInterfaceImplementer( address(this), keccak256("ERC777TokensRecipient"), address(this) ); } modifier onlyAdmin() { // Error code 1: onlyAdmin, address is not an admin address require(adminAddresses[msg.sender], "1"); _; } modifier onlyActiveState() { // Error code 2: onlyActiveState, state is not 'Active' require(state == State.Active, "2"); _; } modifier onlyEscalatedAdminState() { // Error code 3: onlyEscalatedAdminState, adminState is not 'Escalated' require(adminState == AdminState.Escalated, "3"); _; } /// @notice Checks whether an address is appointed as an admin user /// @param _user The address to check /// @return Whether the address is appointed as an admin user function isAdmin(address _user) external view returns(bool) { return adminAddresses[_user]; } /// @notice Sets tbe Broker's state. /// @dev The two available states are `Active` and `Inactive`. /// The `Active` state allows for regular exchange activity, /// while the `Inactive` state prevents the invocation of deposit /// and trading functions. /// The `Inactive` state is intended as a means to cease contract operation /// in the case of an upgrade or in an emergency. /// @param _state The state to transition the contract into function setState(State _state) external onlyOwner nonReentrant { state = _state; } /// @notice Sets the Broker's admin state. /// @dev The two available states are `Normal` and `Escalated`. /// In the `Normal` admin state, the admin methods `adminCancel` and `adminWithdraw` /// are not invocable. /// The admin state must be set to `Escalated` by the contract owner for these /// methods to become usable. /// In an `Escalated` admin state, admin addresses would be able to cancel offers /// and withdraw balances to the respective user's wallet on behalf of users. /// The escalated state is intended to be used in the case of a contract upgrade or /// in an emergency. /// It is set separately from the `Inactive` state so that it is possible /// to use admin functions without affecting regular operations. /// @param _state The admin state to transition the contract into function setAdminState(AdminState _state) external onlyOwner nonReentrant { adminState = _state; } /// @notice Sets the operator address. /// @dev All fees will be transferred to the operator address. /// @param _operator The address to set as the operator function setOperator(address _operator) external onlyOwner nonReentrant { _validateAddress(operator); operator = _operator; } /// @notice Sets the minimum delay between an `announceCancel` call and /// when the cancellation can actually be executed through `slowCancel`. /// @dev This gives the off-chain service time to update the off-chain state /// before the state is separately updated by the user. /// This differs from the regular `cancel` operation, which does not involve a delay. /// @param _delay The delay in seconds function setSlowCancelDelay(uint256 _delay) external onlyOwner nonReentrant { // Error code 4: setSlowCancelDelay, slow cancel delay exceeds max allowable delay require(_delay <= MAX_SLOW_CANCEL_DELAY, "4"); slowCancelDelay = _delay; } /// @notice Sets the delay between an `announceWithdraw` call and /// when the withdrawal can actually be executed through `slowWithdraw`. /// @dev This gives the off-chain service time to update the off-chain state /// before the state is separately updated by the user. /// This differs from the regular `withdraw` operation, which does not involve a delay. /// @param _delay The delay in seconds function setSlowWithdrawDelay(uint256 _delay) external onlyOwner nonReentrant { // Error code 5: setSlowWithdrawDelay, slow withdraw delay exceeds max allowable delay require(_delay <= MAX_SLOW_WITHDRAW_DELAY, "5"); slowWithdrawDelay = _delay; } /// @notice Gives admin permissons to the specified address. /// @dev Admin addresses are intended to coordinate the regular operation /// of the Broker contract, and to perform special functions such as /// `adminCancel` and `adminWithdraw`. /// @param _admin The address to give admin permissions to function addAdmin(address _admin) external onlyOwner nonReentrant { _validateAddress(_admin); // Error code 6: addAdmin, address is already an admin address require(!adminAddresses[_admin], "6"); adminAddresses[_admin] = true; } /// @notice Removes admin permissons for the specified address. /// @param _admin The admin address to remove admin permissions from function removeAdmin(address _admin) external onlyOwner nonReentrant { _validateAddress(_admin); // Error code 7: removeAdmin, address is not an admin address require(adminAddresses[_admin], "7"); delete adminAddresses[_admin]; } /// @notice Adds a market DApp to be used in `networkTrade` /// @param _dapp Address of the market DApp function addMarketDapp(address _dapp) external onlyOwner nonReentrant { _validateAddress(_dapp); marketDapps.push(_dapp); } /// @notice Updates a market DApp to be used in `networkTrade` /// @param _index Index of the market DApp to update /// @param _dapp The new address of the market DApp function updateMarketDapp(uint256 _index, address _dapp) external onlyOwner nonReentrant { _validateAddress(_dapp); // Error code 8: updateMarketDapp, _index does not refer to an existing non-zero address require(marketDapps[_index] != address(0), "8"); marketDapps[_index] = _dapp; } /// @notice Removes a market DApp /// @param _index Index of the market DApp to remove function removeMarketDapp(uint256 _index) external onlyOwner nonReentrant { // Error code 9: removeMarketDapp, _index does not refer to a DApp address require(marketDapps[_index] != address(0), "9"); delete marketDapps[_index]; } /// @notice Performs a balance transfer from one address to another /// @dev This method is intended to be invoked by spender contracts. /// To invoke this method, a spender contract must have been /// previously whitelisted and also authorized by the address from which /// funds will be deducted. /// Balance events are not emitted by this method, they should be separately /// emitted by the spender contract. /// @param _from The address to deduct from /// @param _to The address to credit /// @param _assetId The asset to transfer /// @param _amount The amount to transfer function spendFrom( address _from, address _to, address _assetId, uint256 _amount ) external nonReentrant { spenderList.validateSpenderAuthorization(_from, msg.sender); _validateAddress(_to); balances[_from][_assetId] = balances[_from][_assetId].sub(_amount); balances[_to][_assetId] = balances[_to][_assetId].add(_amount); } /// @notice Allows a whitelisted contract to mark nonces /// @dev If the whitelisted contract is malicious or vulnerable then there is /// a possibility of a DoS attack. However, since this attack requires cooperation /// of the contract owner, the risk is similar to the contract owner withholding /// transactions, so there is no violation of the contract's trust model. /// In the case that nonces are misused, users will still be able to cancel their offers /// and withdraw all their funds using the escape hatch methods. /// @param _nonce The nonce to mark function markNonce(uint256 _nonce) external nonReentrant { spenderList.validateSpender(msg.sender); _markNonce(_nonce); } /// @notice Returns whether a nonce has been taken /// @param _nonce The nonce to check /// @return Whether the nonce has been taken function nonceTaken(uint256 _nonce) external view returns (bool) { return _nonceTaken(_nonce); } /// @notice Deposits ETH into the sender's contract balance /// @dev This operation is only usable in an `Active` state /// to prevent this contract from receiving ETH in the case that its /// operation has been terminated. function deposit() external payable onlyActiveState nonReentrant { // Error code 10: deposit, msg.value is 0 require(msg.value > 0, "10"); _increaseBalance(msg.sender, ETHER_ADDR, msg.value, REASON_DEPOSIT, 0); } /// @dev This function is needed as market DApps generally send ETH /// using the `<address>.transfer` method. /// It is left empty to avoid issues with the function call running out /// of gas, as some callers set a small limit on how much gas can be /// used by the ETH receiver. function() payable external {} /// @notice Deposits ERC20 tokens under the `_user`'s balance /// @dev Transfers token into the Broker contract using the /// token's `transferFrom` method. /// The user must have previously authorized the token transfer /// through the token's `approve` method. /// This method has separate `_amount` and `_expectedAmount` values /// to support unconventional token transfers, e.g. tokens which have a /// proportion burnt on transfer. /// @param _user The address of the user depositing the tokens /// @param _assetId The address of the token contract /// @param _amount The value to invoke the token's `transferFrom` with /// @param _expectedAmount The final amount expected to be received by this contract /// @param _nonce A nonce for balance tracking, emitted in the BalanceIncrease event function depositToken( address _user, address _assetId, uint256 _amount, uint256 _expectedAmount, uint256 _nonce ) external onlyAdmin onlyActiveState nonReentrant { _increaseBalance( _user, _assetId, _expectedAmount, REASON_DEPOSIT, _nonce ); Utils.transferTokensIn( _user, _assetId, _amount, _expectedAmount ); } /// @notice Deposits ERC223 tokens under the `_user`'s balance /// @dev ERC223 tokens should invoke this method when tokens are /// sent to the Broker contract. /// The invocation will fail unless the token has been previously /// whitelisted through the `whitelistToken` method. /// @param _user The address of the user sending the tokens /// @param _amount The amount of tokens transferred to the Broker function tokenFallback( address _user, uint _amount, bytes calldata /* _data */ ) external onlyActiveState nonReentrant { address assetId = msg.sender; tokenList.validateToken(assetId); _increaseBalance(_user, assetId, _amount, REASON_DEPOSIT, 0); emit TokenFallback(_user, assetId, _amount); } /// @notice Deposits ERC777 tokens under the `_user`'s balance /// @dev ERC777 tokens should invoke this method when tokens are /// sent to the Broker contract. /// The invocation will fail unless the token has been previously /// whitelisted through the `whitelistToken` method. /// @param _user The address of the user sending the tokens /// @param _to The address receiving the tokens /// @param _amount The amount of tokens transferred to the Broker function tokensReceived( address /* _operator */, address _user, address _to, uint _amount, bytes calldata /* _userData */, bytes calldata /* _operatorData */ ) external onlyActiveState nonReentrant { if (_to != address(this)) { return; } address assetId = msg.sender; tokenList.validateToken(assetId); _increaseBalance(_user, assetId, _amount, REASON_DEPOSIT, 0); emit TokensReceived(_user, assetId, _amount); } /// @notice Executes an array of offers and fills /// @dev This method accepts an array of "offers" and "fills" together with /// an array of "matches" to specify the matching between the "offers" and "fills". /// The data is bit compacted for ease of index referencing and to reduce gas costs, /// i.e. data representing different types of information is stored within one 256 bit value. /// /// For efficient balance updates, the `_addresses` array is meant to contain a /// unique set of user asset pairs in the form of: /// [ /// user_1_address, /// asset_1_address, /// user_1_address, /// asset_2_address, /// user_2_address, /// asset_1_address, /// ... /// ] /// This allows combining multiple balance updates for a user asset pair /// into a single update by first calculating the total balance update for /// a pair at a specified index, then looping through the sums to perform /// the balance update. /// /// The added benefit is further gas cost reduction because repeated /// user asset pairs do not need to be duplicated for the calldata. /// /// The operator address is enforced to be the contract's current operator /// address, and the operator fee asset ID is enforced to be identical to /// the maker's / filler's feeAssetId. /// /// A tradeoff of compacting the bits is that there is a lower maximum value /// for offer and fill data, however the limits remain generally practical. /// /// For `offerAmount`, `wantAmount`, `feeAmount` values, the maximum value /// is 2^128. For a token with 18 decimals, this allows support for tokens /// with a maximum supply of 1000 million billion billion (33 zeros). /// In the case where the maximum value needs to be exceeded, a single /// offer / fill can be split into multiple offers / fills by the off-chain /// service. /// /// For nonces the maximum value is 2^64, or more than a billion billion (19 zeros). /// /// Offers and fills both encompass information about how much (offerAmount) /// of a specified token (offerAssetId) the user wants to offer and /// how much (wantAmount) of another token (wantAssetId) they want /// in return. /// /// Each match specifies how much of the match's `offer.offerAmount` should /// be transferred to the filler, in return, the offer's maker receives: /// `offer.wantAmount * match.takeAmount / offer.offerAmount` of the /// `offer.wantAssetId` from the filler. /// /// A few restirctions are enforced to ensure fairness and security of trades: /// 1. To prevent unfairness due to rounding issues, it is required that: /// `offer.wantAmount * match.takeAmount % offer.offerAmount == 0`. /// /// 2. Fills can be filled by offers which do not individually match /// the `fill.offerAmount` and `fill.wantAmount` ratio. As such, it is /// required that: /// fill.offerAmount == total amount deducted from filler for the fill's /// associated matches (excluding fees) /// fill.wantAmount == total amount credited to filler for the fill's /// associated matches (excluding fees) /// /// 3. The offer array must not consist of repeated offers. For efficient /// balance updates, a loop through each offer in the offer array is used /// to deduct the offer.offerAmount from the respective maker /// if the offer has not been recorded by a previos `trade` call. /// If an offer is repeated in the offers array, then there would be /// duplicate deductions from the maker. /// To enforce uniqueness, it is required that offers for a trade transaction /// are sorted such that their nonces are in a strictly ascending order. /// /// 4. The fill array must not consist of repeated fills, for the same /// reason why there cannot be repeated offers. Additionally, to prevent /// replay attacks, all fill nonces are required to be unused. /// /// @param _values[0] Number of offers, fills, matches /// bits(0..8): number of offers (numOffers) /// bits(8..16): number of fills (numFills) /// bits(16..24): number of matches (numMatches) /// bits(24..256): must be zero /// /// @param _values[1 + i * 2] First part of offer data for the i'th offer /// bits(0..8): Index of the maker's address in _addresses /// bits(8..16): Index of the maker offerAssetId pair in _addresses /// bits(16..24): Index of the maker wantAssetId pair in _addresses /// bits(24..32): Index of the maker feeAssetId pair in _addresses /// bits(32..40): Index of the operator feeAssetId pair in _addresses /// bits(40..48): The `v` component of the maker's signature for this offer /// bits(48..56): Indicates whether the Ethereum signed message /// prefix should be prepended during signature verification /// bits(56..120): The offer nonce to prevent replay attacks /// bits(120..128): Space to indicate whether the offer nonce has been marked before /// bits(128..256): The number of tokens to be paid to the operator as fees for this offer /// /// @param _values[2 + i * 2] Second part of offer data for the i'th offer /// bits(0..128): offer.offerAmount, i.e. the number of tokens to offer /// bits(128..256): offer.wantAmount, i.e. the number of tokens to ask for in return /// /// @param _values[1 + numOffers * 2 + i * 2] First part of fill data for the i'th fill /// bits(0..8): Index of the filler's address in _addresses /// bits(8..16): Index of the filler offerAssetId pair in _addresses /// bits(16..24): Index of the filler wantAssetId pair in _addresses /// bits(24..32): Index of the filler feeAssetId pair in _addresses /// bits(32..40): Index of the operator feeAssetId pair in _addresses /// bits(40..48): The `v` component of the filler's signature for this fill /// bits(48..56): Indicates whether the Ethereum signed message /// prefix should be prepended during signature verification /// bits(56..120): The fill nonce to prevent replay attacks /// bits(120..128): Left empty to match the offer values format /// bits(128..256): The number of tokens to be paid to the operator as fees for this fill /// /// @param _values[2 + numOffers * 2 + i * 2] Second part of fill data for the i'th fill /// bits(0..128): fill.offerAmount, i.e. the number of tokens to offer /// bits(128..256): fill.wantAmount, i.e. the number of tokens to ask for in return /// /// @param _values[1 + numOffers * 2 + numFills * 2 + i] Data for the i'th match /// bits(0..8): Index of the offerIndex for this match /// bits(8..16): Index of the fillIndex for this match /// bits(128..256): The number of tokens to take from the matched offer's offerAmount /// /// @param _hashes[i * 2] The `r` component of the maker's / filler's signature /// for the i'th offer / fill /// /// @param _hashes[i * 2 + 1] The `s` component of the maker's / filler's signature /// for the i'th offer / fill /// /// @param _addresses An array of user asset pairs in the form of: /// [ /// user_1_address, /// asset_1_address, /// user_1_address, /// asset_2_address, /// user_2_address, /// asset_1_address, /// ... /// ] function trade( uint256[] memory _values, bytes32[] memory _hashes, address[] memory _addresses ) public onlyAdmin onlyActiveState nonReentrant { // Cache the operator address to reduce gas costs from storage reads address operatorAddress = operator; // An array variable to store balance increments / decrements uint256[] memory statements; // Cache whether offer nonces are taken in the offer's nonce space _cacheOfferNonceStates(_values); // `validateTrades` needs to calculate the hash keys of offers and fills // to verify the signature of the offer / fill. // The calculated hash keys are returned to reduce repeated computation. _hashes = Utils.validateTrades( _values, _hashes, _addresses, operatorAddress ); statements = Utils.calculateTradeIncrements(_values, _addresses.length / 2); _incrementBalances(statements, _addresses, 1); statements = Utils.calculateTradeDecrements(_values, _addresses.length / 2); _decrementBalances(statements, _addresses); // Reduce available offer amounts of offers and store the remaining // offer amount in the `offers` mapping. // Offer nonces will also be marked as taken. _storeOfferData(_values, _hashes); // Mark all fill nonces as taken in the `usedNonces` mapping. _storeFillNonces(_values); } /// @notice Executes an array of offers against external orders. /// @dev This method accepts an array of "offers" together with /// an array of "matches" to specify the matching between the "offers" and /// external orders. /// The data is bit compacted and formatted in the same way as the `trade` function. /// /// @param _values[0] Number of offers, fills, matches /// bits(0..8): number of offers (numOffers) /// bits(8..16): number of fills, must be zero /// bits(16..24): number of matches (numMatches) /// bits(24..256): must be zero /// /// @param _values[1 + i * 2] First part of offer data for the i'th offer /// bits(0..8): Index of the maker's address in _addresses /// bits(8..16): Index of the maker offerAssetId pair in _addresses /// bits(16..24): Index of the maker wantAssetId pair in _addresses /// bits(24..32): Index of the maker feeAssetId pair in _addresses /// bits(32..40): Index of the operator feeAssetId pair in _addresses /// bits(40..48): The `v` component of the maker's signature for this offer /// bits(48..56): Indicates whether the Ethereum signed message /// prefix should be prepended during signature verification /// bits(56..120): The offer nonce to prevent replay attacks /// bits(120..128): Space to indicate whether the offer nonce has been marked before /// bits(128..256): The number of tokens to be paid to the operator as fees for this offer /// /// @param _values[2 + i * 2] Second part of offer data for the i'th offer /// bits(0..128): offer.offerAmount, i.e. the number of tokens to offer /// bits(128..256): offer.wantAmount, i.e. the number of tokens to ask for in return /// /// @param _values[1 + numOffers * 2 + i] Data for the i'th match /// bits(0..8): Index of the offerIndex for this match /// bits(8..16): Index of the marketDapp for this match /// bits(16..24): Index of the surplus receiver and surplus asset ID for this /// match, for any excess tokens resulting from the trade /// bits(24..128): Additional DApp specific data /// bits(128..256): The number of tokens to take from the matched offer's offerAmount /// /// @param _hashes[i * 2] The `r` component of the maker's / filler's signature /// for the i'th offer / fill /// /// @param _hashes[i * 2 + 1] The `s` component of the maker's / filler's signature /// for the i'th offer / fill /// /// @param _addresses An array of user asset pairs in the form of: /// [ /// user_1_address, /// asset_1_address, /// user_1_address, /// asset_2_address, /// user_2_address, /// asset_1_address, /// ... /// ] function networkTrade( uint256[] memory _values, bytes32[] memory _hashes, address[] memory _addresses ) public onlyAdmin onlyActiveState nonReentrant { // Cache the operator address to reduce gas costs from storage reads address operatorAddress = operator; // An array variable to store balance increments / decrements uint256[] memory statements; // Cache whether offer nonces are taken in the offer's nonce space _cacheOfferNonceStates(_values); // `validateNetworkTrades` needs to calculate the hash keys of offers // to verify the signature of the offer. // The calculated hash keys for each offer is return to reduce repeated // computation. _hashes = Utils.validateNetworkTrades( _values, _hashes, _addresses, operatorAddress ); statements = Utils.calculateNetworkTradeIncrements(_values, _addresses.length / 2); _incrementBalances(statements, _addresses, 1); statements = Utils.calculateNetworkTradeDecrements(_values, _addresses.length / 2); _decrementBalances(statements, _addresses); // Reduce available offer amounts of offers and store the remaining // offer amount in the `offers` mapping. // Offer nonces will also be marked as taken. _storeOfferData(_values, _hashes); // There may be excess tokens resulting from a trade // Any excess tokens are returned and recorded in `increments` statements = Utils.performNetworkTrades( _values, _addresses, marketDapps ); _incrementBalances(statements, _addresses, 0); } /// @notice Cancels a perviously made offer and refunds the remaining offer /// amount to the offer maker. /// To reduce gas costs, the original parameters of the offer are not stored /// in the contract's storage, only the hash of the parameters is stored for /// verification, so the original parameters need to be re-specified here. /// /// The `_expectedavailableamount` is required to help prevent accidental /// cancellation of an offer ahead of time, for example, if there is /// a pending fill in the off-chain state. /// /// @param _values[0] The offerAmount and wantAmount of the offer /// bits(0..128): offer.offerAmount /// bits(128..256): offer.wantAmount /// /// @param _values[1] The fee amounts /// bits(0..128): offer.feeAmount /// bits(128..256): cancelFeeAmount /// /// @param _values[2] Additional offer and cancellation data /// bits(0..128): expectedAvailableAmount /// bits(128..136): prefixedSignature /// bits(136..144): The `v` component of the maker's signature for the cancellation /// bits(144..256): offer.nonce /// /// @param _hashes[0] The `r` component of the maker's signature for the cancellation /// @param _hashes[1] The `s` component of the maker's signature for the cancellation /// /// @param _addresses[0] offer.maker /// @param _addresses[1] offer.offerAssetId /// @param _addresses[2] offer.wantAssetId /// @param _addresses[3] offer.feeAssetId /// @param _addresses[4] offer.cancelFeeAssetId function cancel( uint256[] calldata _values, bytes32[] calldata _hashes, address[] calldata _addresses ) external onlyAdmin nonReentrant { Utils.validateCancel(_values, _hashes, _addresses); bytes32 offerHash = Utils.hashOffer(_values, _addresses); _cancel( _addresses[0], // maker offerHash, _values[2] & mask128, // expectedAvailableAmount _addresses[1], // offerAssetId _values[2] >> 144, // offerNonce _addresses[4], // cancelFeeAssetId _values[1] >> 128 // cancelFeeAmount ); } /// @notice Cancels an offer without requiring the maker's signature /// @dev This method is intended to be used in the case of a contract /// upgrade or in an emergency. It can only be invoked by an admin and only /// after the admin state has been set to `Escalated` by the contract owner. /// /// To reduce gas costs, the original parameters of the offer are not stored /// in the contract's storage, only the hash of the parameters is stored for /// verification, so the original parameters need to be re-specified here. /// /// The `_expectedavailableamount` is required to help prevent accidental /// cancellation of an offer ahead of time, for example, if there is /// a pending fill in the off-chain state. /// @param _maker The address of the offer's maker /// @param _offerAssetId The contract address of the offerred asset /// @param _offerAmount The number of tokens offerred /// @param _wantAssetId The contract address of the asset asked in return /// @param _wantAmount The number of tokens asked for in return /// @param _feeAssetId The contract address of the fee asset /// @param _feeAmount The number of tokens to pay as fees to the operator /// @param _offerNonce The nonce of the original offer /// @param _expectedAvailableAmount The offer amount remaining function adminCancel( address _maker, address _offerAssetId, uint256 _offerAmount, address _wantAssetId, uint256 _wantAmount, address _feeAssetId, uint256 _feeAmount, uint256 _offerNonce, uint256 _expectedAvailableAmount ) external onlyAdmin onlyEscalatedAdminState nonReentrant { bytes32 offerHash = keccak256(abi.encode( OFFER_TYPEHASH, _maker, _offerAssetId, _offerAmount, _wantAssetId, _wantAmount, _feeAssetId, _feeAmount, _offerNonce )); _cancel( _maker, offerHash, _expectedAvailableAmount, _offerAssetId, _offerNonce, address(0), 0 ); } /// @notice Announces a user's intention to cancel their offer /// @dev This method allows a user to cancel their offer without requiring /// admin permissions. /// An announcement followed by a delay is needed so that the off-chain /// service has time to update the off-chain state. /// /// To reduce gas costs, the original parameters of the offer are not stored /// in the contract's storage, only the hash of the parameters is stored for /// verification, so the original parameters need to be re-specified here. /// /// @param _maker The address of the offer's maker /// @param _offerAssetId The contract address of the offerred asset /// @param _offerAmount The number of tokens offerred /// @param _wantAssetId The contract address of the asset asked in return /// @param _wantAmount The number of tokens asked for in return /// @param _feeAssetId The contract address of the fee asset /// @param _feeAmount The number of tokens to pay as fees to the operator /// @param _offerNonce The nonce of the original offer function announceCancel( address _maker, address _offerAssetId, uint256 _offerAmount, address _wantAssetId, uint256 _wantAmount, address _feeAssetId, uint256 _feeAmount, uint256 _offerNonce ) external nonReentrant { // Error code 11: announceCancel, invalid msg.sender require(_maker == msg.sender, "11"); bytes32 offerHash = keccak256(abi.encode( OFFER_TYPEHASH, _maker, _offerAssetId, _offerAmount, _wantAssetId, _wantAmount, _feeAssetId, _feeAmount, _offerNonce )); // Error code 12: announceCancel, nothing left to cancel require(offers[offerHash] > 0, "12"); uint256 cancellableAt = now.add(slowCancelDelay); cancellationAnnouncements[offerHash] = cancellableAt; emit AnnounceCancel(offerHash, cancellableAt); } /// @notice Executes an offer cancellation previously announced in `announceCancel` /// @dev This method allows a user to cancel their offer without requiring /// admin permissions. /// An announcement followed by a delay is needed so that the off-chain /// service has time to update the off-chain state. /// /// To reduce gas costs, the original parameters of the offer are not stored /// in the contract's storage, only the hash of the parameters is stored for /// verification, so the original parameters need to be re-specified here. /// /// @param _maker The address of the offer's maker /// @param _offerAssetId The contract address of the offerred asset /// @param _offerAmount The number of tokens offerred /// @param _wantAssetId The contract address of the asset asked in return /// @param _wantAmount The number of tokens asked for in return /// @param _feeAssetId The contract address of the fee asset /// @param _feeAmount The number of tokens to pay as fees to the operator /// @param _offerNonce The nonce of the original offer function slowCancel( address _maker, address _offerAssetId, uint256 _offerAmount, address _wantAssetId, uint256 _wantAmount, address _feeAssetId, uint256 _feeAmount, uint256 _offerNonce ) external nonReentrant { bytes32 offerHash = keccak256(abi.encode( OFFER_TYPEHASH, _maker, _offerAssetId, _offerAmount, _wantAssetId, _wantAmount, _feeAssetId, _feeAmount, _offerNonce )); uint256 cancellableAt = cancellationAnnouncements[offerHash]; // Error code 13: slowCancel, cancellation was not announced require(cancellableAt != 0, "13"); // Error code 14: slowCancel, cancellation delay not yet reached require(now >= cancellableAt, "14"); uint256 availableAmount = offers[offerHash]; // Error code 15: slowCancel, nothing left to cancel require(availableAmount > 0, "15"); delete cancellationAnnouncements[offerHash]; _cancel( _maker, offerHash, availableAmount, _offerAssetId, _offerNonce, address(0), 0 ); emit SlowCancel(offerHash, availableAmount); } /// @notice Withdraws tokens from the Broker contract to a user's wallet balance /// @dev The user's internal balance is decreased, and the tokens are transferred /// to the `_receivingAddress` signed by the user. /// @param _withdrawer The user address whose balance will be reduced /// @param _receivingAddress The address to tranfer the tokens to /// @param _assetId The contract address of the token to withdraw /// @param _amount The number of tokens to withdraw /// @param _feeAssetId The contract address of the fee asset /// @param _feeAmount The number of tokens to pay as fees to the operator /// @param _nonce An unused nonce to prevent replay attacks /// @param _v The `v` component of the `_user`'s signature /// @param _r The `r` component of the `_user`'s signature /// @param _s The `s` component of the `_user`'s signature /// @param _prefixedSignature Indicates whether the Ethereum signed message /// prefix should be prepended during signature verification function withdraw( address _withdrawer, address payable _receivingAddress, address _assetId, uint256 _amount, address _feeAssetId, uint256 _feeAmount, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s, bool _prefixedSignature ) external onlyAdmin nonReentrant { _markNonce(_nonce); _validateSignature( keccak256(abi.encode( WITHDRAW_TYPEHASH, _withdrawer, _receivingAddress, _assetId, _amount, _feeAssetId, _feeAmount, _nonce )), _withdrawer, _v, _r, _s, _prefixedSignature ); _withdraw( _withdrawer, _receivingAddress, _assetId, _amount, _feeAssetId, _feeAmount, _nonce ); } /// @notice Withdraws tokens without requiring the withdrawer's signature /// @dev This method is intended to be used in the case of a contract /// upgrade or in an emergency. It can only be invoked by an admin and only /// after the admin state has been set to `Escalated` by the contract owner. /// Unlike `withdraw`, tokens can only be withdrawn to the `_withdrawer`'s /// address. /// @param _withdrawer The user address whose balance will be reduced /// @param _assetId The contract address of the token to withdraw /// @param _amount The number of tokens to withdraw /// @param _nonce An unused nonce for balance tracking function adminWithdraw( address payable _withdrawer, address _assetId, uint256 _amount, uint256 _nonce ) external onlyAdmin onlyEscalatedAdminState nonReentrant { _markNonce(_nonce); _withdraw( _withdrawer, _withdrawer, _assetId, _amount, address(0), 0, _nonce ); } /// @notice Announces a user's intention to withdraw their funds /// @dev This method allows a user to withdraw their funds without requiring /// admin permissions. /// An announcement followed by a delay before execution is needed so that /// the off-chain service has time to update the off-chain state. /// @param _assetId The contract address of the token to withdraw /// @param _amount The number of tokens to withdraw function announceWithdraw( address _assetId, uint256 _amount ) external nonReentrant { // Error code 16: announceWithdraw, invalid withdrawal amount require(_amount > 0 && _amount <= balances[msg.sender][_assetId], "16"); WithdrawalAnnouncement storage announcement = withdrawalAnnouncements[msg.sender][_assetId]; announcement.withdrawableAt = now.add(slowWithdrawDelay); announcement.amount = _amount; emit AnnounceWithdraw(msg.sender, _assetId, _amount, announcement.withdrawableAt); } /// @notice Executes a withdrawal previously announced in `announceWithdraw` /// @dev This method allows a user to withdraw their funds without requiring /// admin permissions. /// An announcement followed by a delay before execution is needed so that /// the off-chain service has time to update the off-chain state. /// @param _withdrawer The user address whose balance will be reduced /// @param _assetId The contract address of the token to withdraw function slowWithdraw( address payable _withdrawer, address _assetId, uint256 _amount ) external nonReentrant { WithdrawalAnnouncement memory announcement = withdrawalAnnouncements[_withdrawer][_assetId]; // Error code 17: slowWithdraw, withdrawal was not announced require(announcement.withdrawableAt != 0, "17"); // Error code 18: slowWithdraw, withdrawal delay not yet reached require(now >= announcement.withdrawableAt, "18"); // Error code 19: slowWithdraw, withdrawal amount does not match announced amount require(announcement.amount == _amount, "19"); delete withdrawalAnnouncements[_withdrawer][_assetId]; _withdraw( _withdrawer, _withdrawer, _assetId, _amount, address(0), 0, 0 ); emit SlowWithdraw(_withdrawer, _assetId, _amount); } /// @notice Locks a user's balances for the first part of an atomic swap /// @param _addresses[0] maker: the address of the user to deduct the swap tokens from /// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens /// if the swap is completed through `executeSwap` /// @param _addresses[2] assetId: the contract address of the token to swap /// @param _addresses[3] feeAssetId: the contract address of the token to use as fees /// @param _values[0] amount: the number of tokens to lock and to transfer if the swap /// is completed through `executeSwap` /// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable /// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees /// @param _values[3] nonce: an unused nonce to prevent replay attacks /// @param _hashes[0] hashedSecret: the hash of the secret decided by the maker /// @param _hashes[1] The `r` component of the user's signature /// @param _hashes[2] The `s` component of the user's signature /// @param _v The `v` component of the user's signature /// @param _prefixedSignature Indicates whether the Ethereum signed message /// prefix should be prepended during signature verification function createSwap( address[4] calldata _addresses, uint256[4] calldata _values, bytes32[3] calldata _hashes, uint8 _v, bool _prefixedSignature ) external onlyAdmin onlyActiveState nonReentrant { // Error code 20: createSwap, invalid swap amount require(_values[0] > 0, "20"); // Error code 21: createSwap, expiry time has already passed require(_values[1] > now, "21"); _validateAddress(_addresses[1]); // Error code 39: createSwap, swap maker cannot be the swap taker require(_addresses[0] != _addresses[1], "39"); bytes32 swapHash = _hashSwap(_addresses, _values, _hashes[0]); // Error code 22: createSwap, the swap is already active require(!atomicSwaps[swapHash], "22"); _markNonce(_values[3]); _validateSignature( swapHash, _addresses[0], // swap.maker _v, _hashes[1], // r _hashes[2], // s _prefixedSignature ); if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId // Error code 23: createSwap, swap.feeAmount exceeds swap.amount require(_values[2] < _values[0], "23"); // feeAmount < amount } else { _decreaseBalance( _addresses[0], // maker _addresses[3], // feeAssetId _values[2], // feeAmount REASON_SWAP_FEE_GIVE, _values[3] // nonce ); } _decreaseBalance( _addresses[0], // maker _addresses[2], // assetId _values[0], // amount REASON_SWAP_GIVE, _values[3] // nonce ); atomicSwaps[swapHash] = true; } /// @notice Executes a swap by transferring the tokens previously locked through /// a `createSwap` call to the swap taker. /// /// @dev To reduce gas costs, the original parameters of the swap are not stored /// in the contract's storage, only the hash of the parameters is stored for /// verification, so the original parameters need to be re-specified here. /// /// @param _addresses[0] maker: the address of the user to deduct the swap tokens from /// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens /// @param _addresses[2] assetId: the contract address of the token to swap /// @param _addresses[3] feeAssetId: the contract address of the token to use as fees /// @param _values[0] amount: the number of tokens previously locked /// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable /// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees /// @param _values[3] nonce: an unused nonce to prevent replay attacks /// @param _hashedSecret The hash of the secret decided by the maker /// @param _preimage The preimage of the `_hashedSecret` function executeSwap( address[4] calldata _addresses, uint256[4] calldata _values, bytes32 _hashedSecret, bytes calldata _preimage ) external nonReentrant { // Error code 37: swap secret length exceeded require(_preimage.length <= MAX_SWAP_SECRET_LENGTH, "37"); bytes32 swapHash = _hashSwap(_addresses, _values, _hashedSecret); // Error code 24: executeSwap, swap is not active require(atomicSwaps[swapHash], "24"); // Error code 25: executeSwap, hash of preimage does not match hashedSecret require(sha256(abi.encodePacked(sha256(_preimage))) == _hashedSecret, "25"); uint256 takeAmount = _values[0]; if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId takeAmount = takeAmount.sub(_values[2]); } delete atomicSwaps[swapHash]; _increaseBalance( _addresses[1], // taker _addresses[2], // assetId takeAmount, REASON_SWAP_RECEIVE, _values[3] // nonce ); _increaseBalance( operator, _addresses[3], // feeAssetId _values[2], // feeAmount REASON_SWAP_FEE_RECEIVE, _values[3] // nonce ); } /// @notice Cancels a swap and refunds the previously locked tokens to /// the swap maker. /// /// @dev To reduce gas costs, the original parameters of the swap are not stored /// in the contract's storage, only the hash of the parameters is stored for /// verification, so the original parameters need to be re-specified here. /// /// @param _addresses[0] maker: the address of the user to deduct the swap tokens from /// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens /// @param _addresses[2] assetId: the contract address of the token to swap /// @param _addresses[3] feeAssetId: the contract address of the token to use as fees /// @param _values[0] amount: the number of tokens previously locked /// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable /// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees /// @param _values[3] nonce: an unused nonce to prevent replay attacks /// @param _hashedSecret The hash of the secret decided by the maker /// @param _cancelFeeAmount The number of tokens to be paid to the operator as the cancellation fee function cancelSwap( address[4] calldata _addresses, uint256[4] calldata _values, bytes32 _hashedSecret, uint256 _cancelFeeAmount ) external nonReentrant { // Error code 26: cancelSwap, expiry time has not been reached require(_values[1] <= now, "26"); bytes32 swapHash = _hashSwap(_addresses, _values, _hashedSecret); // Error code 27: cancelSwap, swap is not active require(atomicSwaps[swapHash], "27"); uint256 cancelFeeAmount = _cancelFeeAmount; if (!adminAddresses[msg.sender]) { cancelFeeAmount = _values[2]; } // cancelFeeAmount <= feeAmount // Error code 28: cancelSwap, cancelFeeAmount exceeds swap.feeAmount require(cancelFeeAmount <= _values[2], "28"); uint256 refundAmount = _values[0]; if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId refundAmount = refundAmount.sub(cancelFeeAmount); } delete atomicSwaps[swapHash]; _increaseBalance( _addresses[0], // maker _addresses[2], // assetId refundAmount, REASON_SWAP_CANCEL_RECEIVE, _values[3] // nonce ); _increaseBalance( operator, _addresses[3], // feeAssetId cancelFeeAmount, REASON_SWAP_CANCEL_FEE_RECEIVE, _values[3] // nonce ); if (_addresses[3] != _addresses[2]) { // feeAssetId != assetId uint256 refundFeeAmount = _values[2].sub(cancelFeeAmount); _increaseBalance( _addresses[0], // maker _addresses[3], // feeAssetId refundFeeAmount, REASON_SWAP_CANCEL_FEE_REFUND, _values[3] // nonce ); } } /// @dev Cache whether offer nonces are taken in the offer's nonce space /// @param _values The _values param from the trade / networkTrade method function _cacheOfferNonceStates(uint256[] memory _values) private view { uint256 i = 1; // i + numOffers * 2 uint256 end = i + (_values[0] & mask8) * 2; // loop offers for(i; i < end; i += 2) { // Error code 38: Invalid nonce space require(((_values[i] & mask128) >> 120) == 0, "38"); uint256 nonce = (_values[i] & mask120) >> 56; if (_nonceTaken(nonce)) { _values[i] = _values[i] | (uint256(1) << 120); } } } /// @dev Reduce available offer amounts of offers and store the remaining /// offer amount in the `offers` mapping. /// Offer nonces will also be marked as taken. /// See the `trade` method for param details. /// @param _values Values from `trade` /// @param _hashes An array of offer hash keys function _storeOfferData( uint256[] memory _values, bytes32[] memory _hashes ) private { // takenAmounts with same size as numOffers uint256[] memory takenAmounts = new uint256[](_values[0] & mask8); uint256 i = 1; // i += numOffers * 2 i += (_values[0] & mask8) * 2; // i += numFills * 2 i += ((_values[0] & mask16) >> 8) * 2; uint256 end = _values.length; // loop matches for (i; i < end; i++) { uint256 offerIndex = _values[i] & mask8; uint256 takeAmount = _values[i] >> 128; takenAmounts[offerIndex] = takenAmounts[offerIndex].add(takeAmount); } i = 0; end = _values[0] & mask8; // numOffers // loop offers for (i; i < end; i++) { // we can use the cached nonce taken value here because offers have been // validated to be unique bool existingOffer = ((_values[i * 2 + 1] & mask128) >> 120) == 1; bytes32 hashKey = _hashes[i * 2]; uint256 availableAmount = existingOffer ? offers[hashKey] : (_values[i * 2 + 2] & mask128); // Error code 31: _storeOfferData, offer's available amount is zero require(availableAmount > 0, "31"); uint256 remainingAmount = availableAmount.sub(takenAmounts[i]); if (remainingAmount > 0) { offers[hashKey] = remainingAmount; } if (existingOffer && remainingAmount == 0) { delete offers[hashKey]; } if (!existingOffer) { uint256 nonce = (_values[i * 2 + 1] & mask120) >> 56; _markNonce(nonce); } } } /// @dev Mark all fill nonces as taken in the `usedNonces` mapping. /// This also validates fill uniquness within the set of fills in `_values`, /// since fill nonces are marked one at a time with validation that the /// nonce to be marked has not been marked before. /// See the `trade` method for param details. /// @param _values Values from `trade` function _storeFillNonces(uint256[] memory _values) private { // 1 + numOffers * 2 uint256 i = 1 + (_values[0] & mask8) * 2; // i + numFills * 2 uint256 end = i + ((_values[0] & mask16) >> 8) * 2; // loop fills for(i; i < end; i += 2) { uint256 nonce = (_values[i] & mask120) >> 56; _markNonce(nonce); } } /// @dev The actual cancellation logic shared by `cancel`, `adminCancel`, /// `slowCancel`. /// The remaining offer amount is refunded back to the offer's maker, and /// the specified cancellation fee will be deducted from the maker's balances. function _cancel( address _maker, bytes32 _offerHash, uint256 _expectedAvailableAmount, address _offerAssetId, uint256 _offerNonce, address _cancelFeeAssetId, uint256 _cancelFeeAmount ) private { uint256 refundAmount = offers[_offerHash]; // Error code 32: _cancel, there is no offer amount left to cancel require(refundAmount > 0, "32"); // Error code 33: _cancel, the remaining offer amount does not match // the expectedAvailableAmount require(refundAmount == _expectedAvailableAmount, "33"); delete offers[_offerHash]; if (_cancelFeeAssetId == _offerAssetId) { refundAmount = refundAmount.sub(_cancelFeeAmount); } else { _decreaseBalance( _maker, _cancelFeeAssetId, _cancelFeeAmount, REASON_CANCEL_FEE_GIVE, _offerNonce ); } _increaseBalance( _maker, _offerAssetId, refundAmount, REASON_CANCEL, _offerNonce ); _increaseBalance( operator, _cancelFeeAssetId, _cancelFeeAmount, REASON_CANCEL_FEE_RECEIVE, _offerNonce // offer nonce ); } /// @dev The actual withdrawal logic shared by `withdraw`, `adminWithdraw`, /// `slowWithdraw`. The specified amount is deducted from the `_withdrawer`'s /// contract balance and transferred to the external `_receivingAddress`, /// and the specified withdrawal fee will be deducted from the `_withdrawer`'s /// balance. function _withdraw( address _withdrawer, address payable _receivingAddress, address _assetId, uint256 _amount, address _feeAssetId, uint256 _feeAmount, uint256 _nonce ) private { // Error code 34: _withdraw, invalid withdrawal amount require(_amount > 0, "34"); _validateAddress(_receivingAddress); _decreaseBalance( _withdrawer, _assetId, _amount, REASON_WITHDRAW, _nonce ); _increaseBalance( operator, _feeAssetId, _feeAmount, REASON_WITHDRAW_FEE_RECEIVE, _nonce ); uint256 withdrawAmount; if (_feeAssetId == _assetId) { withdrawAmount = _amount.sub(_feeAmount); } else { _decreaseBalance( _withdrawer, _feeAssetId, _feeAmount, REASON_WITHDRAW_FEE_GIVE, _nonce ); withdrawAmount = _amount; } if (_assetId == ETHER_ADDR) { _receivingAddress.transfer(withdrawAmount); return; } Utils.transferTokensOut( _receivingAddress, _assetId, withdrawAmount ); } /// @dev Creates a hash key for a swap using the swap's parameters /// @param _addresses[0] Address of the user making the swap /// @param _addresses[1] Address of the user taking the swap /// @param _addresses[2] Contract address of the asset to swap /// @param _addresses[3] Contract address of the fee asset /// @param _values[0] The number of tokens to be transferred /// @param _values[1] The time in epoch seconds after which the swap will become cancellable /// @param _values[2] The number of tokens to pay as fees to the operator /// @param _values[3] The swap nonce to prevent replay attacks /// @param _hashedSecret The hash of the secret decided by the maker /// @return The hash key of the swap function _hashSwap( address[4] memory _addresses, uint256[4] memory _values, bytes32 _hashedSecret ) private pure returns (bytes32) { return keccak256(abi.encode( SWAP_TYPEHASH, _addresses[0], // maker _addresses[1], // taker _addresses[2], // assetId _values[0], // amount _hashedSecret, // hashedSecret _values[1], // expiryTime _addresses[3], // feeAssetId _values[2], // feeAmount _values[3] // nonce )); } /// @dev Checks if the `_nonce` had been previously taken. /// To reduce gas costs, a single `usedNonces` value is used to /// store the state of 256 nonces, using the formula: /// nonceTaken = "usedNonces[_nonce / 256] bit (_nonce % 256)" != 0 /// For example: /// nonce 0 taken: "usedNonces[0] bit 0" != 0 (0 / 256 = 0, 0 % 256 = 0) /// nonce 1 taken: "usedNonces[0] bit 1" != 0 (1 / 256 = 0, 1 % 256 = 1) /// nonce 2 taken: "usedNonces[0] bit 2" != 0 (2 / 256 = 0, 2 % 256 = 2) /// nonce 255 taken: "usedNonces[0] bit 255" != 0 (255 / 256 = 0, 255 % 256 = 255) /// nonce 256 taken: "usedNonces[1] bit 0" != 0 (256 / 256 = 1, 256 % 256 = 0) /// nonce 257 taken: "usedNonces[1] bit 1" != 0 (257 / 256 = 1, 257 % 256 = 1) /// @param _nonce The nonce to check /// @return Whether the nonce has been taken function _nonceTaken(uint256 _nonce) private view returns (bool) { uint256 slotData = _nonce.div(256); uint256 shiftedBit = uint256(1) << _nonce.mod(256); uint256 bits = usedNonces[slotData]; // The check is for "!= 0" instead of "== 1" because the shiftedBit is // not at the zero'th position, so it would require an additional // shift to compare it with "== 1" return bits & shiftedBit != 0; } /// @dev Sets the corresponding `_nonce` bit to 1. /// An error will be raised if the corresponding `_nonce` bit was /// previously set to 1. /// See `_nonceTaken` for details on calculating the corresponding `_nonce` bit. /// @param _nonce The nonce to mark function _markNonce(uint256 _nonce) private { // Error code 35: _markNonce, nonce cannot be zero require(_nonce != 0, "35"); uint256 slotData = _nonce.div(256); uint256 shiftedBit = 1 << _nonce.mod(256); uint256 bits = usedNonces[slotData]; // Error code 36: _markNonce, nonce has already been marked require(bits & shiftedBit == 0, "36"); usedNonces[slotData] = bits | shiftedBit; } /// @dev Validates that the specified `_hash` was signed by the specified `_user`. /// This method supports the EIP712 specification, the older Ethereum /// signed message specification is also supported for backwards compatibility. /// @param _hash The original hash that was signed by the user /// @param _user The user who signed the hash /// @param _v The `v` component of the `_user`'s signature /// @param _r The `r` component of the `_user`'s signature /// @param _s The `s` component of the `_user`'s signature /// @param _prefixed If true, the signature will be verified /// against the Ethereum signed message specification instead of the /// EIP712 specification function _validateSignature( bytes32 _hash, address _user, uint8 _v, bytes32 _r, bytes32 _s, bool _prefixed ) private pure { Utils.validateSignature( _hash, _user, _v, _r, _s, _prefixed ); } /// @dev A utility method to increase the balance of a user. /// A corressponding `BalanceIncrease` event will also be emitted. /// @param _user The address to increase balance for /// @param _assetId The asset's contract address /// @param _amount The number of tokens to increase the balance by /// @param _reasonCode The reason code for the `BalanceIncrease` event /// @param _nonce The nonce for the `BalanceIncrease` event function _increaseBalance( address _user, address _assetId, uint256 _amount, uint256 _reasonCode, uint256 _nonce ) private { if (_amount == 0) { return; } balances[_user][_assetId] = balances[_user][_assetId].add(_amount); emit BalanceIncrease( _user, _assetId, _amount, _reasonCode, _nonce ); } /// @dev A utility method to decrease the balance of a user. /// A corressponding `BalanceDecrease` event will also be emitted. /// @param _user The address to decrease balance for /// @param _assetId The asset's contract address /// @param _amount The number of tokens to decrease the balance by /// @param _reasonCode The reason code for the `BalanceDecrease` event /// @param _nonce The nonce for the `BalanceDecrease` event function _decreaseBalance( address _user, address _assetId, uint256 _amount, uint256 _reasonCode, uint256 _nonce ) private { if (_amount == 0) { return; } balances[_user][_assetId] = balances[_user][_assetId].sub(_amount); emit BalanceDecrease( _user, _assetId, _amount, _reasonCode, _nonce ); } /// @dev Ensures that `_address` is not the zero address /// @param _address The address to check function _validateAddress(address _address) private pure { Utils.validateAddress(_address); } /// @dev A utility method to increase balances of multiple addresses. /// A corressponding `Increment` event will also be emitted. /// @param _increments An array of amounts to increase a user's balance by, /// the corresponding user and assetId is referenced by /// _addresses[index * 2] and _addresses[index * 2 + 1] respectively /// @param _addresses An array of user asset pairs in the form of: /// [ /// user_1_address, /// asset_1_address, /// user_1_address, /// asset_2_address, /// user_2_address, /// asset_1_address, /// ... /// ] /// @param _static Indicates if the amount was pre-calculated or only known /// at the time the transaction was executed function _incrementBalances( uint256[] memory _increments, address[] memory _addresses, uint256 _static ) private { uint256 end = _increments.length; for(uint256 i = 0; i < end; i++) { uint256 increment = _increments[i]; if (increment == 0) { continue; } balances[_addresses[i * 2]][_addresses[i * 2 + 1]] = balances[_addresses[i * 2]][_addresses[i * 2 + 1]].add(increment); emit Increment((i << 248) | (_static << 240) | increment); } } /// @dev A utility method to decrease balances of multiple addresses. /// A corressponding `Decrement` event will also be emitted. /// @param _decrements An array of amounts to decrease a user's balance by, /// the corresponding user and assetId is referenced by /// _addresses[index * 2] and _addresses[index * 2 + 1] respectively /// @param _addresses An array of user asset pairs in the form of: /// [ /// user_1_address, /// asset_1_address, /// user_1_address, /// asset_2_address, /// user_2_address, /// asset_1_address, /// ... /// ] function _decrementBalances( uint256[] memory _decrements, address[] memory _addresses ) private { uint256 end = _decrements.length; for(uint256 i = 0; i < end; i++) { uint256 decrement = _decrements[i]; if (decrement == 0) { continue; } balances[_addresses[i * 2]][_addresses[i * 2 + 1]] = balances[_addresses[i * 2]][_addresses[i * 2 + 1]].sub(decrement); emit Decrement(i << 248 | decrement); } } }
Locks a user's balances for the first part of an atomic swap _addresses[0] maker: the address of the user to deduct the swap tokens from _addresses[1] taker: the address of the swap taker who will receive the swap tokens if the swap is completed through `executeSwap` _addresses[2] assetId: the contract address of the token to swap _addresses[3] feeAssetId: the contract address of the token to use as fees _values[0] amount: the number of tokens to lock and to transfer if the swap is completed through `executeSwap` _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable _values[2] feeAmount: the number of tokens to be paid to the operator as fees _values[3] nonce: an unused nonce to prevent replay attacks _hashes[0] hashedSecret: the hash of the secret decided by the maker _hashes[1] The `r` component of the user's signature _hashes[2] The `s` component of the user's signature _v The `v` component of the user's signature _prefixedSignature Indicates whether the Ethereum signed message prefix should be prepended during signature verification Error code 20: createSwap, invalid swap amount Error code 21: createSwap, expiry time has already passed Error code 39: createSwap, swap maker cannot be the swap taker Error code 22: createSwap, the swap is already active Error code 23: createSwap, swap.feeAmount exceeds swap.amount
function createSwap( address[4] calldata _addresses, uint256[4] calldata _values, bytes32[3] calldata _hashes, uint8 _v, bool _prefixedSignature ) external onlyAdmin onlyActiveState nonReentrant { require(_values[0] > 0, "20"); require(_values[1] > now, "21"); _validateAddress(_addresses[1]); require(_addresses[0] != _addresses[1], "39"); bytes32 swapHash = _hashSwap(_addresses, _values, _hashes[0]); require(!atomicSwaps[swapHash], "22"); _markNonce(_values[3]); _validateSignature( swapHash, _v, _prefixedSignature ); _decreaseBalance( REASON_SWAP_FEE_GIVE, ); } _decreaseBalance( REASON_SWAP_GIVE, ); atomicSwaps[swapHash] = true;
13,110,327
./partial_match/1/0x2dd110C6646468d82D4160EBdb8Ec462373784A2/sources/pepe.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Pepe0x69", "PEPE0x69") { 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 = 7; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 3; uint256 _sellMarketingFee = 36; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 12; uint256 totalSupply = 420690000000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x4a4395699DC85f5503cc36DF3c5805C0A8b4BB07); devWallet = address(0x4a4395699DC85f5503cc36DF3c5805C0A8b4BB07); 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);
4,048,146
pragma solidity ^0.4.23; import "../util/Ownable.sol"; import "../util/SafeMath.sol"; import "../storage/KeyValueStorage.sol"; import "../ip-organisations/IPOrganisations.sol"; /** * @title Marketplaces * @author Civic Ledger */ contract Marketplaces is Ownable { using SafeMath for uint256; KeyValueStorage internal storageContract; /// @dev Checks that sender is an authorised IPO account modifier onlyAuthorisedIPO(uint256 _ipoIndex, address _ipoAddress){ IPOrganisations ipOrganisations = IPOrganisations(storageContract.getAddress(keccak256("contract.name", "IPOrganisations"))); require(ipOrganisations.isAddressAuthorised(_ipoIndex, _ipoAddress)); _; } /** * @dev constructor * @param _storageAddress Address of central storage contract */ constructor(address _storageAddress) public { storageContract = KeyValueStorage(_storageAddress); } /// @dev Get a marketplace by index /// @param _marketplaceIndex Index of the marketplace to retrieve function byIndex(uint256 _marketplaceIndex) external view returns(string, string, address, uint256) { return ( storageContract.getString(keccak256("marketplace.name", _marketplaceIndex)), storageContract.getString(keccak256("marketplace.website", _marketplaceIndex)), storageContract.getAddress(keccak256("marketplace.address", _marketplaceIndex)), storageContract.getUint(keccak256("marketplace.registeringIPOIndex", _marketplaceIndex)) ); } // @dev Check an address is a registered marketplace // @param Address to check whether is is a registered marketplace function isRegistered(address _marketplaceAddress) external view returns(bool) { return storageContract.getBool(keccak256("marketplace.registered", _marketplaceAddress)); } /// @dev Register a marketplace to be able to participate in IPRx /// @param _marketplaceName Name of the marketplace for display /// @param _marketplaceWebsiteUrl Url of the marketplaces website /// @param _marketplaceAddress Address of the marketplace /// @param _registeringIPOIndex Index of the registering IPO function register(string _marketplaceName, string _marketplaceWebsiteUrl, address _marketplaceAddress, uint256 _registeringIPOIndex) external onlyAuthorisedIPO(_registeringIPOIndex, msg.sender) { // name should not be empty require(bytes(_marketplaceName).length > 0); // url should not be empty require(bytes(_marketplaceWebsiteUrl).length > 0); // marketplace address should be not be null address require(_marketplaceAddress != 0x0); // get new marketplace index uint256 nextIndex = storageContract.getUint(keccak256("marketplaces.nextIndex")); // store details storageContract.setString(keccak256("marketplace.name", nextIndex), _marketplaceName); storageContract.setString(keccak256("marketplace.website", nextIndex), _marketplaceWebsiteUrl); storageContract.setAddress(keccak256("marketplace.address", nextIndex), _marketplaceAddress); storageContract.setUint(keccak256("marketplace.registeringIPOIndex", nextIndex), _registeringIPOIndex); // save reverse lookup storageContract.setUint(keccak256("marketplace.reverse", _marketplaceAddress), nextIndex); // save registered check storageContract.setBool(keccak256("marketplace.registered", _marketplaceAddress), true); // increment the marketplace index for next registration storageContract.setUint(keccak256("marketplaces.nextIndex"), nextIndex.add(1)); } }
Get a marketplace by index _marketplaceIndex Index of the marketplace to retrieve
function byIndex(uint256 _marketplaceIndex) external view returns(string, string, address, uint256) { return ( storageContract.getString(keccak256("marketplace.name", _marketplaceIndex)), storageContract.getString(keccak256("marketplace.website", _marketplaceIndex)), storageContract.getAddress(keccak256("marketplace.address", _marketplaceIndex)), storageContract.getUint(keccak256("marketplace.registeringIPOIndex", _marketplaceIndex)) ); }
12,609,702
./full_match/1/0x2C5e00ec69b27740CB8155736390ee7e74d279DB/sources/contracts/utils/HStrategyHelper.sol
calculates current amounts of tokens erc20Vault the erc20 vault of the strategy moneyVault the money vault of the strategy params current position and pool state combined with predictions from the oracle return amounts amounts of tokens
function calculateCurrentTokenAmounts( IIntegrationVault erc20Vault, IIntegrationVault moneyVault, HStrategy.DomainPositionParams memory params ) external returns (HStrategy.TokenAmounts memory amounts) { (amounts.uniV3Token0, amounts.uniV3Token1) = LiquidityAmounts.getAmountsForLiquidity( params.intervalPriceSqrtX96, params.lowerPriceSqrtX96, params.upperPriceSqrtX96, params.liquidity ); { if (moneyVault.supportsInterface(type(IAaveVault).interfaceId)) { IAaveVault(address(moneyVault)).updateTvls(); } (uint256[] memory minMoneyTvl, ) = moneyVault.tvl(); amounts.moneyToken0 = minMoneyTvl[0]; amounts.moneyToken1 = minMoneyTvl[1]; } { (uint256[] memory erc20Tvl, ) = erc20Vault.tvl(); amounts.erc20Token0 = erc20Tvl[0]; amounts.erc20Token1 = erc20Tvl[1]; } }
16,590,921
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../YakStrategyV2.sol"; /** * @notice Adapter strategy for MasterChef. */ abstract contract MasterChefStrategy is YakStrategyV2 { using SafeMath for uint256; uint256 public immutable PID; address private stakingRewards; constructor( string memory _name, address _depositToken, address _rewardToken, address _stakingRewards, address _timelock, uint256 _pid, uint256 _minTokensToReinvest, uint256 _adminFeeBips, uint256 _devFeeBips, uint256 _reinvestRewardBips ) Ownable() { name = _name; depositToken = IERC20(_depositToken); rewardToken = IERC20(_rewardToken); PID = _pid; devAddr = msg.sender; stakingRewards = _stakingRewards; setAllowances(); updateMinTokensToReinvest(_minTokensToReinvest); updateAdminFee(_adminFeeBips); updateDevFee(_devFeeBips); updateReinvestReward(_reinvestRewardBips); updateDepositsEnabled(true); transferOwnership(_timelock); emit Reinvest(0, 0); } /** * @notice Approve tokens for use in Strategy * @dev Restricted to avoid griefing attacks */ function setAllowances() public override onlyOwner { depositToken.approve(stakingRewards, type(uint256).max); } /** * @notice Deposit tokens to receive receipt tokens * @param amount Amount of tokens to deposit */ function deposit(uint256 amount) external override { _deposit(msg.sender, amount); } /** * @notice Deposit using Permit * @param amount Amount of tokens to deposit * @param deadline 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 depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { depositToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(msg.sender, amount); } function depositFor(address account, uint256 amount) external override { _deposit(account, amount); } function _deposit(address account, uint256 amount) internal { require(DEPOSITS_ENABLED == true, "MasterChefStrategyV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint256 unclaimedRewards = checkReward(); if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(unclaimedRewards); } } require( depositToken.transferFrom(account, address(this), amount), "MasterChefStrategyV1::transfer failed" ); _stakeDepositTokens(amount); uint256 depositFeeBips = _getDepositFeeBips(PID); uint256 depositFee = amount.mul(depositFeeBips).div(_bip()); _mint(account, getSharesForDepositTokens(amount.sub(depositFee))); emit Deposit(account, amount); } function withdraw(uint256 amount) external override { uint256 depositTokenAmount = getDepositTokensForShares(amount); if (depositTokenAmount > 0) { _withdrawDepositTokens(depositTokenAmount); uint256 withdrawFeeBips = _getWithdrawFeeBips(PID); uint256 withdrawFee = depositTokenAmount.mul(withdrawFeeBips).div(_bip()); _safeTransfer( address(depositToken), msg.sender, depositTokenAmount.sub(withdrawFee) ); _burn(msg.sender, amount); emit Withdraw(msg.sender, depositTokenAmount); } } function _withdrawDepositTokens(uint256 amount) private { require(amount > 0, "MasterChefStrategyV1::_withdrawDepositTokens"); _withdrawMasterchef(PID, amount); } function reinvest() external override onlyEOA { uint256 unclaimedRewards = checkReward(); require( unclaimedRewards >= MIN_TOKENS_TO_REINVEST, "MasterChefStrategyV1::reinvest" ); _reinvest(unclaimedRewards); } /** * @notice Reinvest rewards from staking contract to deposit tokens * @dev Reverts if the expected amount of tokens are not returned from `MasterChef` * @param amount deposit tokens to reinvest */ function _reinvest(uint256 amount) private { _getRewards(PID); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint256 depositTokenAmount = _convertRewardTokenToDepositToken( amount.sub(devFee).sub(adminFee).sub(reinvestFee) ); _stakeDepositTokens(depositTokenAmount); emit Reinvest(totalDeposits(), totalSupply); } function _stakeDepositTokens(uint256 amount) private { require(amount > 0, "MasterChefStrategyV1::_stakeDepositTokens"); _depositMasterchef(PID, amount); } /** * @notice Safely transfer using an anonymosu ERC20 token * @dev Requires token to return true on transfer * @param token address * @param to recipient address * @param value amount */ function _safeTransfer( address token, address to, uint256 value ) private { require( IERC20(token).transfer(to, value), "MasterChefStrategyV1::TRANSFER_FROM_FAILED" ); } function checkReward() public view override returns (uint256) { uint256 pendingReward = _pendingRewards(PID, address(this)); uint256 contractBalance = rewardToken.balanceOf(address(this)); return pendingReward.add(contractBalance); } /** * @notice Estimate recoverable balance after withdraw fee * @return deposit tokens after withdraw fee */ function estimateDeployedBalance() external view override returns (uint256) { return _totalDeposits(); } function totalDeposits() public view override returns (uint256) { return _totalDeposits(); } function _totalDeposits() internal view returns (uint256) { uint256 depositBalance = _getDepositBalance(PID, address(this)); uint256 withdrawFeeBips = _getWithdrawFeeBips(PID); uint256 withdrawFee = depositBalance.mul(withdrawFeeBips).div(_bip()); return depositBalance.sub(withdrawFee); } function rescueDeployedFunds(uint256 minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint256 balanceBefore = depositToken.balanceOf(address(this)); _emergencyWithdraw(PID); uint256 balanceAfter = depositToken.balanceOf(address(this)); require( balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "MasterChefStrategyV1::rescueDeployedFunds" ); emit Reinvest(totalDeposits(), totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } /* VIRTUAL */ function _convertRewardTokenToDepositToken(uint256 fromAmount) internal virtual returns (uint256 toAmount); function _depositMasterchef(uint256 pid, uint256 amount) internal virtual; function _withdrawMasterchef(uint256 pid, uint256 amount) internal virtual; function _emergencyWithdraw(uint256 pid) internal virtual; function _getRewards(uint256 pid) internal virtual; function _pendingRewards(uint256 pid, address user) internal view virtual returns (uint256 amount); function _getDepositBalance(uint256 pid, address user) internal view virtual returns (uint256 amount); function _getDepositFeeBips(uint256 pid) internal view virtual returns (uint256); function _getWithdrawFeeBips(uint256 pid) internal view virtual returns (uint256); function _bip() internal view virtual returns (uint256); }
Estimate recoverable balance after withdraw fee return deposit tokens after withdraw fee/
function estimateDeployedBalance() external view override returns (uint256) { return _totalDeposits(); }
2,539,598
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../WStep.sol"; import "../WFStorage.sol"; import '../ExtensionEventRegistry.sol'; import "./LibRecetaDocument.sol"; contract RecetaModel is WFStorage, ExtensionEventRegistry, LibRecetaDocument { address owner; mapping (uint256 => DocumentPayload) public table; ExtensionEventRegistry private extReg; constructor(address r) public WFStorage() { owner = msg.sender; extReg = ExtensionEventRegistry(r); } function onAddRow( address to, address sender, WStep memory current, WStep memory next, bytes memory payload ) public nonReentrant returns (bool) { currentDocumentIndex = rowCount; rowCount = rowCount + 1; if (hasAttachedFiles(rowCount + 1)) return false; table[rowCount-1] = this.getTableFromRlp(rowCount - 1, payload); table[rowCount-1].stepInfo.user = sender; table[rowCount-1].stepInfo.recipient = to; table[rowCount-1].stepInfo.status = keccak256(abi.encodePacked(next.current)); return true; } function onUpdate(uint256 doc, address to, address sender, WStep memory current, WStep memory next, bytes memory payload ) public returns (bool) { validateSender(current, sender); validateRecipient(current, to); validateStatus(next, current.current); currentDocumentIndex = doc; table[doc].stepInfo.status = keccak256(abi.encodePacked(next.current)); if (table[doc].documentStatus == 1) { // 1 = updated, 0 = nothing updateFilesMapping(doc, payload); } return true; } function updateSwitch(uint256 doc, address to, address sender, WStep memory currentStep, WStep memory nextStep, uint256 extensionEvtId, bytes memory fields ) public returns (bool, uint256) { uint256 calculatedNextFork = currentStep.next; if (currentStep.forkId > 0) { calculatedNextFork = currentStep.forkId; } this.onUpdate(doc, to, sender, currentStep, nextStep, fields); return (true, calculatedNextFork); } }
1 = updated, 0 = nothing
function onUpdate(uint256 doc, address to, address sender, WStep memory current, WStep memory next, bytes memory payload ) public returns (bool) { validateSender(current, sender); validateRecipient(current, to); validateStatus(next, current.current); currentDocumentIndex = doc; table[doc].stepInfo.status = keccak256(abi.encodePacked(next.current)); if (table[doc].documentStatus == 1) { updateFilesMapping(doc, payload); } return true; }
5,528,645
//pragma solidity >=0.6.0 <0.9.0; pragma solidity ^0.8.10; //SPDX-License-Identifier: MIT // import "hardhat/console.sol"; import "./hashVerifier.sol"; import "./MerkleTreeWithHistory.sol"; // import {IHasher} from "./Hasher.sol"; //import "@openzeppelin/contracts/access/Ownable.sol"; //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol contract YourContract is Verifier, MerkleTreeWithHistory { event SetPurpose(address sender, string purpose); string public purpose = "Building Unstoppable Apps"; uint256 public verifiedBid; constructor(uint32 _levels, address _hasher) MerkleTreeWithHistory(_levels, _hasher){ } function setPurpose(string memory newPurpose) public { purpose = newPurpose; // console.log(msg.sender,"set purpose to",purpose); emit SetPurpose(msg.sender, purpose); } function commit(bytes32 _commitment) public { uint32 insertedIndex = _insert(_commitment); } function bid( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[36] memory input ) public { require(verifyProof(a, b, c, input), "Invalid Proof"); verifiedBid = input[0]; } }
console.log(msg.sender,"set purpose to",purpose);
function setPurpose(string memory newPurpose) public { purpose = newPurpose; emit SetPurpose(msg.sender, purpose); }
12,535,041
pragma solidity ^0.5.11; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false struct Airline { string name; address aAccount; // wallet address, used to uniquely identify the airline account bool isFounder; // is this a founding airline? bool isRegistered; // allows to de-register an airline bool isApproved; // has this airline been voted in? uint voteCount; // count of votes used to nominate this airline to be registered address[] voters; // members that voted this airline in. used to prevent duplicate votes } struct Policy { address pHolder; // Wallet Address of the Policy Holder (the person that purchased inssurance and will need to be paid out) string flightNumber; // flight number that this policy covers uint premiumPaid; // Amount of Ether paid to the policy for this flight by this address bool isRedeemed; // Tracks whether this policy has been cashed out or not (redeemed) bytes32 flightKey; // FlightKey is used as a unique identifier for the insurance record. It combines the airline, the flight number, and the flight timestamp } mapping(address => Policy[]) policies; // Mapping of address (policy holders) to an array of polcies mapping(address => Airline) airlines; // Mapping for storing airlines that are registered mapping(address => uint) credits; // Mapping to store the amount of credit each account has pending withrawl uint private membershipCount = 1; // Variable for keeping track of the total number of registered airlines /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( address firstAirline ) public { contractOwner = msg.sender; airlines[firstAirline] = Airline({ name: "Founding Airline", aAccount: firstAirline, isFounder: true, isRegistered: true, isApproved: true, voteCount: 1, voters: new address[](0) }); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier hasCredit(address account) { require(credits[account] > 0, "account does not have any credit"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /* * Source: https://ethereum.stackexchange.com/questions/30912/how-to-compare-strings-in-solidity * Truffle wasn't playing nice with import "github.com/Arachnid/solidity-stringutils/strings.sol"; * So I used the strategy from the above website. */ function compareStrings (string memory a, string memory b) public view returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) ); } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } function getMemberCount() external returns(uint) { return membershipCount; } function getVoteCount(address account) external returns(uint){ return airlines[account].voteCount; } function getCreditAmount(address account) hasCredit(account) external returns (uint) { return credits[account]; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /** * @dev Check if an airline is registered * @return A bool that indicates if the airline is registered */ function isAirlineRegistered(address account) external view returns (bool) { return airlines[account].isRegistered; } /** * @dev Check if an airline is registered * @return A bool that indicates if the airline is registered */ function isAirlineApproved(address account) external view returns (bool) { return airlines[account].isApproved; } function hasVoted(address nominatingAirline, address nominee) external returns (bool) { if (airlines[nominee].voters.length == 0) { return false; } else { // there are already some votes, check to see if this nominatingAirline is already one of them for(uint i=0; i<airlines[nominee].voters.length; i++) { if(airlines[nominee].voters[i] == nominatingAirline){ return true; // found a vote from this nominating airline } return false; // this is a new vote //FIXME: i++ is never reached if the second vote is this nominated airline it won't get flagged } } } /* hasPolicy: returns bool indicating if a policy account has been created already for this account */ function hasPolicy(address account) internal returns (bool) { if (policies[account].length == 0) { return false; } else { return true; } } function getPolicyLength(address account) external returns(uint) { return policies[account].length; } function hasFlightPolicy(address account, bytes32 flightKey) public returns(bool) { for (uint i = 0; i < policies[account].length; i++) { if (policies[account][i].flightKey == flightKey) { return true; // policy exists for this flight } } return false; // flight not found in list of policies } function getPolicy(address account, bytes32 flightKey) external returns(address, string memory, uint, bool,bytes32) { for (uint i = 0; i < policies[account].length; i++) { if (policies[account][i].flightKey == flightKey) { return ( policies[account][i].pHolder, policies[account][i].flightNumber, policies[account][i].premiumPaid, policies[account][i].isRedeemed, policies[account][i].flightKey ); } } // policy not found. What do I return here? } function getPolicyIndex(address account, bytes32 flightKey) internal returns(uint) { require(hasFlightPolicy(account, flightKey),"This flight is not insured for this account"); for (uint i = 0; i < policies[account].length; i++) { if (policies[account][i].flightKey == flightKey) { return ( i ); } } // policy not found. What do I return here? } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address account, string calldata airlineName, bool approvalStatus, address msgSender) external requireIsOperational { // require(!airlines[account].isRegistered, "Airline is already registered."); // require(airlines[tx.origin].isRegistered, "Airline must be registered by another airline."); if (approvalStatus) { // airline is approved, this is a founder airlines[account] = Airline({ name: airlineName, aAccount: account, // this is redundant but a placeholder for more fields. isRegistered: true, isApproved: approvalStatus, isFounder: true, voteCount: 1, voters: new address[](0) }); membershipCount = membershipCount + 1; } else { // airline is not approved, this is a new nominee airlines[account] = Airline({ name: airlineName, aAccount: account, // this is redundant but a placeholder for more fields. isRegistered: true, isApproved: approvalStatus, isFounder: false, voteCount: 1, voters: new address[](0) }); airlines[account].voters.push(msgSender); } } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function approveAirline(address account) external requireIsOperational { airlines[account].isApproved = true; membershipCount = membershipCount + 1; } function nominateAirline(address nominatingAirline, address nominee) external requireIsOperational { airlines[nominee].voters.push(nominatingAirline); airlines[nominee].voteCount = airlines[nominee].voteCount + 1; } /** * @dev Buy insurance for a flight * */ function buy (address account, string calldata flightNumber, uint premiumPaid, bytes32 flightKey) external // payable // nope, application logic will be payable? { // check to see if they currently have a policy in the policies mapping if (hasPolicy(account)) { // has account: so we need to add a new policy for this flight to the array of policies Policy memory newPolicy = Policy({ pHolder: account, flightNumber: flightNumber, premiumPaid: premiumPaid, isRedeemed: false, flightKey: flightKey }); policies[account].push(newPolicy); } else { // doesn't have account: so we need to create an account in policies and add a new policy to the array for this flight Policy memory newPolicy = Policy({ pHolder: account, flightNumber: flightNumber, premiumPaid: premiumPaid, isRedeemed: false, flightKey: flightKey }); policies[account].push(newPolicy); } } /** * @dev Credits payouts to insurees */ function creditInsuree(address account, uint payout, bytes32 flightKey) external { require(hasFlightPolicy(account, flightKey),"This flight is not insured for this account"); uint policyNumber = getPolicyIndex(account, flightKey); // add credit to credits for this account credits[account] = credits[account] + payout; // mark policy as paid policies[account][policyNumber].isRedeemed = true; } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( ) external pure { } function getFlightKey ( address airline, string calldata flight, uint256 timestamp ) pure external returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ // function() // external // payable // { // fund(); // } }
Truffle wasn't playing nice with import "github.com/Arachnid/solidity-stringutils/strings.sol"; So I used the strategy from the above website./
function compareStrings (string memory a, string memory b) public view returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) ); }
7,327,187
contract IOwnable { function getOwner() public view returns (address); function transferOwnership(address _newOwner) public returns (bool); } contract IERC20 { function totalSupply() public view returns (uint256); function balanceOf(address owner) public view returns (uint256); function transfer(address to, uint256 amount) public returns (bool); function transferFrom(address from, address to, uint256 amount) public returns (bool); function approve(address spender, uint256 amount) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ICash is IERC20 { function joinMint(address usr, uint wad) public returns (bool); function joinBurn(address usr, uint wad) public returns (bool); } contract ITyped { function getTypeName() public view returns (bytes32); } interface IStandardToken { function noHooksTransfer(address recipient, uint256 amount) external returns (bool); } contract IReputationToken is IERC20 { function migrateOutByPayout(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); function migrateIn(address _reporter, uint256 _attotokens) public returns (bool); function trustedReportingParticipantTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedMarketTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedUniverseTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedDisputeWindowTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function getUniverse() public view returns (IUniverse); function getTotalMigrated() public view returns (uint256); function getTotalTheoreticalSupply() public view returns (uint256); function mintForReportingParticipant(uint256 _amountMigrated) public returns (bool); } contract IV2ReputationToken is IReputationToken, IStandardToken { function burnForMarket(uint256 _amountToBurn) public returns (bool); function mintForUniverse(uint256 _amountToMint, address _target) public returns (bool); } contract IDisputeWindow is ITyped, IERC20 { uint256 public invalidMarketsTotal; uint256 public validityBondTotal; uint256 public incorrectDesignatedReportTotal; uint256 public initialReportBondTotal; uint256 public designatedReportNoShowsTotal; uint256 public designatedReporterNoShowBondTotal; function initialize(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, uint256 _duration, uint256 _startTime, address _erc1820RegistryAddress) public; function trustedBuy(address _buyer, uint256 _attotokens) public returns (bool); function getUniverse() public view returns (IUniverse); function getReputationToken() public view returns (IReputationToken); function getStartTime() public view returns (uint256); function getEndTime() public view returns (uint256); function getWindowId() public view returns (uint256); function isActive() public view returns (bool); function isOver() public view returns (bool); function onMarketFinalized() public; function redeem(address _account) public returns (bool); } contract IReportingParticipant { function getStake() public view returns (uint256); function getPayoutDistributionHash() public view returns (bytes32); function liquidateLosing() public; function redeem(address _redeemer) public returns (bool); function isDisavowed() public view returns (bool); function getPayoutNumerator(uint256 _outcome) public view returns (uint256); function getPayoutNumerators() public view returns (uint256[] memory); function getMarket() public view returns (IMarket); function getSize() public view returns (uint256); } contract IUniverse { mapping(address => uint256) public marketBalance; function fork() public returns (bool); function updateForkValues() public returns (bool); function getParentUniverse() public view returns (IUniverse); function createChildUniverse(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); function getChildUniverse(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); function getReputationToken() public view returns (IV2ReputationToken); function getForkingMarket() public view returns (IMarket); function getForkEndTime() public view returns (uint256); function getForkReputationGoal() public view returns (uint256); function getParentPayoutDistributionHash() public view returns (bytes32); function getDisputeRoundDurationInSeconds(bool _initial) public view returns (uint256); function getOrCreateDisputeWindowByTimestamp(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); function getOrCreateCurrentDisputeWindow(bool _initial) public returns (IDisputeWindow); function getOrCreateNextDisputeWindow(bool _initial) public returns (IDisputeWindow); function getOrCreatePreviousDisputeWindow(bool _initial) public returns (IDisputeWindow); function getOpenInterestInAttoCash() public view returns (uint256); function getRepMarketCapInAttoCash() public view returns (uint256); function getTargetRepMarketCapInAttoCash() public view returns (uint256); function getOrCacheValidityBond() public returns (uint256); function getOrCacheDesignatedReportStake() public returns (uint256); function getOrCacheDesignatedReportNoShowBond() public returns (uint256); function getOrCacheMarketRepBond() public returns (uint256); function getOrCacheReportingFeeDivisor() public returns (uint256); function getDisputeThresholdForFork() public view returns (uint256); function getDisputeThresholdForDisputePacing() public view returns (uint256); function getInitialReportMinValue() public view returns (uint256); function getPayoutNumerators() public view returns (uint256[] memory); function getReportingFeeDivisor() public view returns (uint256); function getPayoutNumerator(uint256 _outcome) public view returns (uint256); function getWinningChildPayoutNumerator(uint256 _outcome) public view returns (uint256); function isOpenInterestCash(address) public view returns (bool); function isForkingMarket() public view returns (bool); function getCurrentDisputeWindow(bool _initial) public view returns (IDisputeWindow); function isParentOf(IUniverse _shadyChild) public view returns (bool); function updateTentativeWinningChildUniverse(bytes32 _parentPayoutDistributionHash) public returns (bool); function isContainerForDisputeWindow(IDisputeWindow _shadyTarget) public view returns (bool); function isContainerForMarket(IMarket _shadyTarget) public view returns (bool); function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool); function isContainerForShareToken(IShareToken _shadyTarget) public view returns (bool); function migrateMarketOut(IUniverse _destinationUniverse) public returns (bool); function migrateMarketIn(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); function decrementOpenInterest(uint256 _amount) public returns (bool); function decrementOpenInterestFromMarket(IMarket _market) public returns (bool); function incrementOpenInterest(uint256 _amount) public returns (bool); function getWinningChildUniverse() public view returns (IUniverse); function isForking() public view returns (bool); function assertMarketBalance() public view returns (bool); function deposit(address _sender, uint256 _amount, address _market) public returns (bool); function withdraw(address _recipient, uint256 _amount, address _market) public returns (bool); } // Copyright (C) 2015 Forecast Foundation OU, full GPL notice in LICENSE // Bid / Ask actions: puts orders on the book // price is denominated by the specific market's numTicks // amount is the number of attoshares the order is for (either to buy or to sell). // price is the exact price you want to buy/sell at [which may not be the cost, for example to short a yesNo market it'll cost numTicks-price, to go long it'll cost price] /** * @title SafeMathUint256 * @dev Uint256 math operations with safety checks that throw on error */ library SafeMathUint256 { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a <= b) { return a; } else { return b; } } function max(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a; } else { return b; } } function getUint256Min() internal pure returns (uint256) { return 0; } function getUint256Max() internal pure returns (uint256) { // 2 ** 256 - 1 return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function isMultipleOf(uint256 a, uint256 b) internal pure returns (bool) { return a % b == 0; } // Float [fixed point] Operations function fxpMul(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { return div(mul(a, b), base); } function fxpDiv(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { return div(mul(a, base), b); } } contract IOrders { function saveOrder(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed, bytes32 _betterOrderId, bytes32 _worseOrderId, bytes32 _tradeGroupId, IERC20 _kycToken) external returns (bytes32 _orderId); function removeOrder(bytes32 _orderId) external returns (bool); function getMarket(bytes32 _orderId) public view returns (IMarket); function getOrderType(bytes32 _orderId) public view returns (Order.Types); function getOutcome(bytes32 _orderId) public view returns (uint256); function getAmount(bytes32 _orderId) public view returns (uint256); function getPrice(bytes32 _orderId) public view returns (uint256); function getOrderCreator(bytes32 _orderId) public view returns (address); function getOrderSharesEscrowed(bytes32 _orderId) public view returns (uint256); function getOrderMoneyEscrowed(bytes32 _orderId) public view returns (uint256); function getOrderDataForLogs(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); function getBetterOrderId(bytes32 _orderId) public view returns (bytes32); function getWorseOrderId(bytes32 _orderId) public view returns (bytes32); function getKYCToken(bytes32 _orderId) public view returns (IERC20); function getBestOrderId(Order.Types _type, IMarket _market, uint256 _outcome, IERC20 _kycToken) public view returns (bytes32); function getWorstOrderId(Order.Types _type, IMarket _market, uint256 _outcome, IERC20 _kycToken) public view returns (bytes32); function getLastOutcomePrice(IMarket _market, uint256 _outcome) public view returns (uint256); function getOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed, IERC20 _kycToken) public pure returns (bytes32); function getTotalEscrowed(IMarket _market) public view returns (uint256); function isBetterPrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); function isWorsePrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); function assertIsNotBetterPrice(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); function assertIsNotWorsePrice(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); function recordFillOrder(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); function setPrice(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); } // CONSIDER: Is `price` the most appropriate name for the value being used? It does correspond 1:1 with the attoCASH per share, but the range might be considered unusual? library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IOrders orders; IMarket market; IAugur augur; IERC20 kycToken; ICash cash; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } // No validation is needed here as it is simply a library function for organizing data function create(IAugur _augur, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId, IERC20 _kycToken) internal view returns (Data memory) { require(_outcome < _market.getNumberOfOutcomes(), "Order.create: Outcome is not within market range"); require(_price != 0, "Order.create: Price may not be 0"); require(_price < _market.getNumTicks(), "Order.create: Price is outside of market range"); require(_attoshares > 0, "Order.create: Cannot use amount of 0"); require(_creator != address(0), "Order.create: Creator is 0x0"); IOrders _orders = IOrders(_augur.lookup("Orders")); return Data({ orders: _orders, market: _market, augur: _augur, kycToken: _kycToken, cash: ICash(_augur.lookup("Cash")), id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function getOrderId(Order.Data memory _orderData) internal view returns (bytes32) { if (_orderData.id == bytes32(0)) { bytes32 _orderId = _orderData.orders.getOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed, _orderData.kycToken); require(_orderData.orders.getAmount(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible"); _orderData.id = _orderId; } return _orderData.id; } function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function escrowFunds(Order.Data memory _orderData) internal returns (bool) { if (_orderData.orderType == Order.Types.Ask) { return escrowFundsForAsk(_orderData); } else if (_orderData.orderType == Order.Types.Bid) { return escrowFundsForBid(_orderData); } } function saveOrder(Order.Data memory _orderData, bytes32 _tradeGroupId) internal returns (bytes32) { return _orderData.orders.saveOrder(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed, _orderData.betterOrderId, _orderData.worseOrderId, _tradeGroupId, _orderData.kycToken); } // // Private functions // function escrowFundsForBid(Order.Data memory _orderData) private returns (bool) { require(_orderData.moneyEscrowed == 0, "Order.escrowFundsForBid: New order had money escrowed. This should not be possible"); require(_orderData.sharesEscrowed == 0, "Order.escrowFundsForBid: New order had shares escrowed. This should not be possible"); uint256 _attosharesToCover = _orderData.amount; uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes(); // Figure out how many almost-complete-sets (just missing `outcome` share) the creator has uint256 _attosharesHeld = 2**254; for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) { if (_i != _orderData.outcome) { uint256 _creatorShareTokenBalance = _orderData.market.getShareToken(_i).balanceOf(_orderData.creator); _attosharesHeld = SafeMathUint256.min(_creatorShareTokenBalance, _attosharesHeld); } } // Take shares into escrow if they have any almost-complete-sets if (_attosharesHeld > 0) { _orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover); _attosharesToCover -= _orderData.sharesEscrowed; for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) { if (_i != _orderData.outcome) { _orderData.market.getShareToken(_i).trustedOrderTransfer(_orderData.creator, address(_orderData.market), _orderData.sharesEscrowed); } } } // If not able to cover entire order with shares alone, then cover remaining with tokens if (_attosharesToCover > 0) { _orderData.moneyEscrowed = _attosharesToCover.mul(_orderData.price); _orderData.market.getUniverse().deposit(_orderData.creator, _orderData.moneyEscrowed, address(_orderData.market)); } return true; } function escrowFundsForAsk(Order.Data memory _orderData) private returns (bool) { require(_orderData.moneyEscrowed == 0, "Order.escrowFundsForAsk: New order had money escrowed. This should not be possible"); require(_orderData.sharesEscrowed == 0, "Order.escrowFundsForAsk: New order had shares escrowed. This should not be possible"); IShareToken _shareToken = _orderData.market.getShareToken(_orderData.outcome); uint256 _attosharesToCover = _orderData.amount; // Figure out how many shares of the outcome the creator has uint256 _attosharesHeld = _shareToken.balanceOf(_orderData.creator); // Take shares in escrow if user has shares if (_attosharesHeld > 0) { _orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover); _attosharesToCover -= _orderData.sharesEscrowed; _shareToken.trustedOrderTransfer(_orderData.creator, address(_orderData.market), _orderData.sharesEscrowed); } // If not able to cover entire order with shares alone, then cover remaining with tokens if (_attosharesToCover > 0) { _orderData.moneyEscrowed = _orderData.market.getNumTicks().sub(_orderData.price).mul(_attosharesToCover); _orderData.market.getUniverse().deposit(_orderData.creator, _orderData.moneyEscrowed, address(_orderData.market)); } return true; } } contract IAugur { function createChildUniverse(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); function isKnownUniverse(IUniverse _universe) public view returns (bool); function trustedTransfer(IERC20 _token, address _from, address _to, uint256 _amount) public returns (bool); function isTrustedSender(address _address) public returns (bool); function logCategoricalMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); function logYesNoMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); function logScalarMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); function logInitialReportSubmitted(IUniverse _universe, address _reporter, address _market, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); function disputeCrowdsourcerCreated(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); function logDisputeCrowdsourcerContribution(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); function logDisputeCrowdsourcerCompleted(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); function logInitialReporterRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); function logDisputeCrowdsourcerRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); function logMarketFinalized(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); function logMarketMigrated(IMarket _market, IUniverse _originalUniverse) public returns (bool); function logReportingParticipantDisavowed(IUniverse _universe, IMarket _market) public returns (bool); function logMarketParticipantsDisavowed(IUniverse _universe) public returns (bool); function logOrderCanceled(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); function logOrderCreated(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); function logOrderFilled(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); function logZeroXOrderFilled(IUniverse _universe, IMarket _market, bytes32 _tradeGroupId, Order.Types _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); function logCompleteSetsPurchased(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); function logCompleteSetsSold(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); function logMarketOIChanged(IUniverse _universe, IMarket _market) public returns (bool); function logTradingProceedsClaimed(IUniverse _universe, address _shareToken, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _finalTokenBalance, uint256 _fees) public returns (bool); function logUniverseForked(IMarket _forkingMarket) public returns (bool); function logShareTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance, uint256 _outcome) public returns (bool); function logReputationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); function logReputationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logReputationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logShareTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance, uint256 _outcome) public returns (bool); function logShareTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance, uint256 _outcome) public returns (bool); function logDisputeCrowdsourcerTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); function logDisputeCrowdsourcerTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logDisputeCrowdsourcerTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logDisputeWindowCreated(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); function logParticipationTokensRedeemed(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); function logTimestampSet(uint256 _newTimestamp) public returns (bool); function logInitialReporterTransferred(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); function logMarketTransferred(IUniverse _universe, address _from, address _to) public returns (bool); function logParticipationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); function logParticipationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logParticipationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logMarketVolumeChanged(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes) public returns (bool); function logProfitLossChanged(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); function isKnownFeeSender(address _feeSender) public view returns (bool); function isKnownShareToken(IShareToken _token) public view returns (bool); function lookup(bytes32 _key) public view returns (address); function getTimestamp() public view returns (uint256); function getMaximumMarketEndDate() public returns (uint256); function isKnownMarket(IMarket _market) public view returns (bool); function derivePayoutDistributionHash(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); } contract IShareToken is ITyped, IERC20 { function initialize(IAugur _augur, IMarket _market, uint256 _outcome, address _erc1820RegistryAddress) external; function createShares(address _owner, uint256 _amount) external returns (bool); function destroyShares(address, uint256 balance) external returns (bool); function getMarket() external view returns (IMarket); function getOutcome() external view returns (uint256); function trustedOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedFillOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedCancelOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); } contract IInitialReporter is IReportingParticipant { function initialize(IAugur _augur, IMarket _market, address _designatedReporter) public; function report(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; function designatedReporterShowed() public view returns (bool); function designatedReporterWasCorrect() public view returns (bool); function getDesignatedReporter() public view returns (address); function getReportTimestamp() public view returns (uint256); function migrateToNewUniverse(address _designatedReporter) public; function returnRepFromDisavow() public; } contract IMarket is IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function initialize(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; function derivePayoutDistributionHash(uint256[] memory _payoutNumerators) public view returns (bytes32); function getUniverse() public view returns (IUniverse); function getDisputeWindow() public view returns (IDisputeWindow); function getNumberOfOutcomes() public view returns (uint256); function getNumTicks() public view returns (uint256); function getShareToken(uint256 _outcome) public view returns (IShareToken); function getMarketCreatorSettlementFeeDivisor() public view returns (uint256); function getForkingMarket() public view returns (IMarket _market); function getEndTime() public view returns (uint256); function getWinningPayoutDistributionHash() public view returns (bytes32); function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256); function getWinningReportingParticipant() public view returns (IReportingParticipant); function getReputationToken() public view returns (IV2ReputationToken); function getFinalizationTime() public view returns (uint256); function getInitialReporter() public view returns (IInitialReporter); function getDesignatedReportingEndTime() public view returns (uint256); function getValidityBondAttoCash() public view returns (uint256); function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256); function recordMarketCreatorFees(uint256 _marketCreatorFees, address _affiliateAddress) public returns (bool); function isContainerForShareToken(IShareToken _shadyTarget) public view returns (bool); function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool); function isInvalid() public view returns (bool); function finalize() public returns (bool); function designatedReporterWasCorrect() public view returns (bool); function designatedReporterShowed() public view returns (bool); function isFinalized() public view returns (bool); function assertBalances() public view returns (bool); } contract Initializable { bool private initialized = false; modifier beforeInitialized { require(!initialized); _; } function endInitialization() internal beforeInitialized { initialized = true; } function getInitialized() public view returns (bool) { return initialized; } } /** * @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 is IOwnable { address internal owner; /** * @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); _; } function getOwner() public view returns (address) { return 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 returns (bool) { if (_newOwner != address(0)) { onTransferOwnership(owner, _newOwner); owner = _newOwner; } return true; } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function onTransferOwnership(address, address) internal; } contract IMap { function initialize(address _owner) public; function add(bytes32 _key, address _value) public returns (bool); function remove(bytes32 _key) public returns (bool); function get(bytes32 _key) public view returns (address); function getAsAddressOrZero(bytes32 _key) public view returns (address); function contains(bytes32 _key) public view returns (bool); function getCount() public view returns (uint256); } // Provides a mapping that has a count and more control over the behavior of Key errors. Additionally allows for a clean way to clear an existing map by simply creating a new one on owning contracts. contract Map is Ownable, Initializable, IMap { mapping(bytes32 => address) private items; uint256 private count; function initialize(address _owner) public beforeInitialized { endInitialization(); owner = _owner; } function add(bytes32 _key, address _value) public onlyOwner returns (bool) { require(_value != address(0)); if (contains(_key)) { return false; } items[_key] = _value; count += 1; return true; } function remove(bytes32 _key) public onlyOwner returns (bool) { if (!contains(_key)) { return false; } delete items[_key]; count -= 1; return true; } function get(bytes32 _key) public view returns (address) { address _value = items[_key]; require(_value != address(0)); return _value; } function getAsAddressOrZero(bytes32 _key) public view returns (address) { return items[_key]; } function contains(bytes32 _key) public view returns (bool) { return items[_key] != address(0); } function getCount() public view returns (uint256) { return count; } function onTransferOwnership(address, address) internal { } } contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 { function initialize(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, address _erc1820RegistryAddress) public; function contribute(address _participant, uint256 _amount, bool _overload) public returns (uint256); function setSize(uint256 _size) public; function getRemainingToFill() public view returns (uint256); function correctSize() public returns (bool); } contract IDisputeCrowdsourcerFactory { function createDisputeCrowdsourcer(IAugur _augur, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators) public returns (IDisputeCrowdsourcer); } // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1167.md /* Template Code for the create clone method: function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target)${bytes == 20 ? "" : "<<" + ((20 - bytes) * 8)}; assembly { let clone := mload(0x40) mstore(clone, 0x${code.substring(0, 2*(cloner.labels.address + 1)).padEnd(64, '0')}) mstore(add(clone, 0x${(cloner.labels.address + 1).toString(16)}), targetBytes) mstore(add(clone, 0x${(cloner.labels.address + bytes + 1).toString(16)}), 0x${code.substring(2*(cloner.labels.address + bytes + 1), 2*(cloner.labels.address+bytes+1) + 30).padEnd(64, '0')}) result := create(0, clone, 0x${(code.length / 2).toString(16)}) } } */ contract CloneFactory { function createClone(address target) internal returns (address result) { // convert address to bytes20 for assembly use bytes20 targetBytes = bytes20(target); assembly { // allocate clone memory let clone := mload(0x40) // store initial portion of the delegation contract code in bytes form mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) // store the provided address mstore(add(clone, 0x14), targetBytes) // store the remaining delegation contract code mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) // create the actual delegate contract reference and return its address result := create(0, clone, 0x37) } } } /** * @title Share Token Factory * @notice A Factory contract to create Share Token contracts * @dev Should not be used directly. Only intended to be used by Market contracts. */ contract ShareTokenFactory is CloneFactory { function createShareToken(IAugur _augur, uint256 _outcome) public returns (IShareToken) { IMarket _market = IMarket(msg.sender); IShareToken _shareToken = IShareToken(createClone(_augur.lookup("ShareToken"))); _shareToken.initialize(_augur, _market, _outcome, _augur.lookup("ERC1820Registry")); return _shareToken; } } /** * @title Initial Reporter Factory * @notice A Factory contract to create Initial Reporter delegate contracts * @dev Should not be used directly. Only intended to be used by Market contracts */ contract InitialReporterFactory is CloneFactory { function createInitialReporter(IAugur _augur, address _designatedReporter) public returns (IInitialReporter) { IMarket _market = IMarket(msg.sender); IInitialReporter _initialReporter = IInitialReporter(createClone(_augur.lookup("InitialReporter"))); _initialReporter.initialize(_augur, _market, _designatedReporter); return _initialReporter; } } /** * @title Map Factory * @notice A Factory contract to create Map delegate contracts */ contract MapFactory is CloneFactory { function createMap(IAugur _augur, address _owner) public returns (IMap) { IMap _map = IMap(createClone(_augur.lookup("Map"))); _map.initialize(_owner); return _map; } } /** * @title SafeMathInt256 * @dev Int256 math operations with safety checks that throw on error */ library SafeMathInt256 { // Signed ints with n bits can range from -2**(n-1) to (2**(n-1) - 1) int256 private constant INT256_MIN = -2**(255); int256 private constant INT256_MAX = (2**(255) - 1); function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; require(a == 0 || c / a == b); return c; } function div(int256 a, int256 b) internal pure returns (int256) { // No need to check for dividing by 0 -- Solidity automatically throws on division by 0 int256 c = a / b; return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require(((a >= 0) && (b >= a - INT256_MAX)) || ((a < 0) && (b <= a - INT256_MIN))); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { require(((a >= 0) && (b <= INT256_MAX - a)) || ((a < 0) && (b >= INT256_MIN - a))); return a + b; } function min(int256 a, int256 b) internal pure returns (int256) { if (a <= b) { return a; } else { return b; } } function max(int256 a, int256 b) internal pure returns (int256) { if (a >= b) { return a; } else { return b; } } function abs(int256 a) internal pure returns (int256) { if (a < 0) { return -a; } return a; } function getInt256Min() internal pure returns (int256) { return INT256_MIN; } function getInt256Max() internal pure returns (int256) { return INT256_MAX; } // Float [fixed point] Operations function fxpMul(int256 a, int256 b, int256 base) internal pure returns (int256) { return div(mul(a, b), base); } function fxpDiv(int256 a, int256 b, int256 base) internal pure returns (int256) { return div(mul(a, base), b); } } library Reporting { uint256 private constant DESIGNATED_REPORTING_DURATION_SECONDS = 1 days; uint256 private constant DISPUTE_ROUND_DURATION_SECONDS = 7 days; uint256 private constant INITIAL_DISPUTE_ROUND_DURATION_SECONDS = 1 days; uint256 private constant DISPUTE_WINDOW_BUFFER_SECONDS = 1 hours; uint256 private constant FORK_DURATION_SECONDS = 60 days; uint256 private constant BASE_MARKET_DURATION_MAXIMUM = 30 days; // A market of 30 day length can always be created uint256 private constant UPGRADE_CADENCE = 365 days; uint256 private constant INITIAL_UPGRADE_TIMESTAMP = 1626307484; // July 15th 2021 uint256 private constant INITIAL_REP_SUPPLY = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP uint256 private constant DEFAULT_VALIDITY_BOND = 10 ether; // 10 Cash (Dai) uint256 private constant VALIDITY_BOND_FLOOR = 10 ether; // 10 Cash (Dai) uint256 private constant DEFAULT_REPORTING_FEE_DIVISOR = 100; // 1% fees uint256 private constant MAXIMUM_REPORTING_FEE_DIVISOR = 10000; // Minimum .01% fees uint256 private constant MINIMUM_REPORTING_FEE_DIVISOR = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. uint256 private constant TARGET_INVALID_MARKETS_DIVISOR = 100; // 1% of markets are expected to be invalid uint256 private constant TARGET_INCORRECT_DESIGNATED_REPORT_MARKETS_DIVISOR = 100; // 1% of markets are expected to have an incorrect designate report uint256 private constant TARGET_DESIGNATED_REPORT_NO_SHOWS_DIVISOR = 20; // 5% of markets are expected to have a no show uint256 private constant TARGET_REP_MARKET_CAP_MULTIPLIER = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount uint256 private constant FORK_THRESHOLD_DIVISOR = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork uint256 private constant MAXIMUM_DISPUTE_ROUNDS = 20; // We ensure that after 20 rounds of disputes a fork will occur uint256 private constant MINIMUM_SLOW_ROUNDS = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins function getDesignatedReportingDurationSeconds() internal pure returns (uint256) { return DESIGNATED_REPORTING_DURATION_SECONDS; } function getInitialDisputeRoundDurationSeconds() internal pure returns (uint256) { return INITIAL_DISPUTE_ROUND_DURATION_SECONDS; } function getDisputeWindowBufferSeconds() internal pure returns (uint256) { return DISPUTE_WINDOW_BUFFER_SECONDS; } function getDisputeRoundDurationSeconds() internal pure returns (uint256) { return DISPUTE_ROUND_DURATION_SECONDS; } function getForkDurationSeconds() internal pure returns (uint256) { return FORK_DURATION_SECONDS; } function getBaseMarketDurationMaximum() internal pure returns (uint256) { return BASE_MARKET_DURATION_MAXIMUM; } function getUpgradeCadence() internal pure returns (uint256) { return UPGRADE_CADENCE; } function getInitialUpgradeTimestamp() internal pure returns (uint256) { return INITIAL_UPGRADE_TIMESTAMP; } function getDefaultValidityBond() internal pure returns (uint256) { return DEFAULT_VALIDITY_BOND; } function getValidityBondFloor() internal pure returns (uint256) { return VALIDITY_BOND_FLOOR; } function getTargetInvalidMarketsDivisor() internal pure returns (uint256) { return TARGET_INVALID_MARKETS_DIVISOR; } function getTargetIncorrectDesignatedReportMarketsDivisor() internal pure returns (uint256) { return TARGET_INCORRECT_DESIGNATED_REPORT_MARKETS_DIVISOR; } function getTargetDesignatedReportNoShowsDivisor() internal pure returns (uint256) { return TARGET_DESIGNATED_REPORT_NO_SHOWS_DIVISOR; } function getTargetRepMarketCapMultiplier() internal pure returns (uint256) { return TARGET_REP_MARKET_CAP_MULTIPLIER; } function getMaximumReportingFeeDivisor() internal pure returns (uint256) { return MAXIMUM_REPORTING_FEE_DIVISOR; } function getMinimumReportingFeeDivisor() internal pure returns (uint256) { return MINIMUM_REPORTING_FEE_DIVISOR; } function getDefaultReportingFeeDivisor() internal pure returns (uint256) { return DEFAULT_REPORTING_FEE_DIVISOR; } function getInitialREPSupply() internal pure returns (uint256) { return INITIAL_REP_SUPPLY; } function getForkThresholdDivisor() internal pure returns (uint256) { return FORK_THRESHOLD_DIVISOR; } function getMaximumDisputeRounds() internal pure returns (uint256) { return MAXIMUM_DISPUTE_ROUNDS; } function getMinimumSlowRounds() internal pure returns (uint256) { return MINIMUM_SLOW_ROUNDS; } } /** * @title Market * @notice The contract which encapsulates event data and payout resolution for the event */ contract Market is Initializable, Ownable, IMarket { using SafeMathUint256 for uint256; using SafeMathInt256 for int256; // Constants uint256 private constant MAX_APPROVAL_AMOUNT = 2 ** 256 - 1; address private constant NULL_ADDRESS = address(0); // Contract Refs IUniverse private universe; IDisputeWindow private disputeWindow; ICash private cash; IAugur public augur; MapFactory public mapFactory; // Attributes uint256 private numTicks; uint256 private feeDivisor; uint256 public affiliateFeeDivisor; uint256 private endTime; uint256 private numOutcomes; bytes32 private winningPayoutDistributionHash; uint256 public validityBondAttoCash; uint256 private finalizationTime; uint256 public repBond; bool private disputePacingOn; address public repBondOwner; uint256 public marketCreatorFeesAttoCash; uint256 public totalAffiliateFeesAttoCash; IDisputeCrowdsourcer public preemptiveDisputeCrowdsourcer; // Collections IReportingParticipant[] public participants; IMap public crowdsourcers; IShareToken[] private shareTokens; mapping (address => uint256) public affiliateFeesAttoCash; function initialize(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public beforeInitialized { endInitialization(); augur = _augur; require(msg.sender == augur.lookup("MarketFactory")); _numOutcomes += 1; // The INVALID outcome is always first universe = _universe; cash = ICash(augur.lookup("Cash")); owner = _creator; repBondOwner = owner; cash.approve(address(augur), MAX_APPROVAL_AMOUNT); assessFees(); endTime = _endTime; numOutcomes = _numOutcomes; numTicks = _numTicks; feeDivisor = _feePerCashInAttoCash == 0 ? 0 : 1 ether / _feePerCashInAttoCash; affiliateFeeDivisor = _affiliateFeeDivisor; InitialReporterFactory _initialReporterFactory = InitialReporterFactory(augur.lookup("InitialReporterFactory")); participants.push(_initialReporterFactory.createInitialReporter(augur, _designatedReporterAddress)); mapFactory = MapFactory(augur.lookup("MapFactory")); clearCrowdsourcers(); for (uint256 _outcome = 0; _outcome < numOutcomes; _outcome++) { shareTokens.push(createShareToken(_outcome)); } approveSpenders(); } function assessFees() private { repBond = universe.getOrCacheMarketRepBond(); require(getReputationToken().balanceOf(address(this)) >= repBond); validityBondAttoCash = cash.balanceOf(address(this)); require(validityBondAttoCash >= universe.getOrCacheValidityBond()); universe.deposit(address(this), validityBondAttoCash, address(this)); } /** * @notice Increase the validity bond by sending more Cash to this contract * @param _attoCash the amount of Cash to send and increase the validity bond by * @return Bool True */ function increaseValidityBond(uint256 _attoCash) public returns (bool) { require(!isFinalized()); cash.transferFrom(msg.sender, address(this), _attoCash); universe.deposit(address(this), _attoCash, address(this)); validityBondAttoCash = validityBondAttoCash.add(_attoCash); return true; } function createShareToken(uint256 _outcome) private returns (IShareToken) { return ShareTokenFactory(augur.lookup("ShareTokenFactory")).createShareToken(augur, _outcome); } function approveSpenders() public returns (bool) { bytes32[5] memory _names = [bytes32("CancelOrder"), bytes32("CompleteSets"), bytes32("FillOrder"), bytes32("ClaimTradingProceeds"), bytes32("Orders")]; for (uint256 i = 0; i < _names.length; i++) { require(cash.approve(augur.lookup(_names[i]), MAX_APPROVAL_AMOUNT)); } for (uint256 j = 0; j < numOutcomes; j++) { require(shareTokens[j].approve(augur.lookup("FillOrder"), MAX_APPROVAL_AMOUNT)); } return true; } /** * @notice Do the initial report for the market. * @param _payoutNumerators An array indicating the payout for each market outcome * @param _description Any additional information or justification for this report * @param _additionalStake Additional optional REP to stake in anticipation of a dispute. This REP will be held in a bond that only activates if the report is disputed * @return Bool True */ function doInitialReport(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool) { doInitialReportInternal(msg.sender, _payoutNumerators, _description); if (_additionalStake > 0) { contributeToTentativeInternal(msg.sender, _payoutNumerators, _additionalStake, _description); } return true; } function doInitialReportInternal(address _reporter, uint256[] memory _payoutNumerators, string memory _description) private { require(!universe.isForking()); IInitialReporter _initialReporter = getInitialReporter(); uint256 _timestamp = augur.getTimestamp(); require(_timestamp > endTime, "Market.doInitialReportInternal: Market has not reached Reporting phase"); uint256 _initialReportStake = distributeInitialReportingRep(_reporter, _initialReporter); // The derive call will validate that an Invalid report is entirely paid out on the Invalid outcome bytes32 _payoutDistributionHash = derivePayoutDistributionHash(_payoutNumerators); disputeWindow = universe.getOrCreateNextDisputeWindow(true); _initialReporter.report(_reporter, _payoutDistributionHash, _payoutNumerators, _initialReportStake); augur.logInitialReportSubmitted(universe, _reporter, address(this), _initialReportStake, _initialReporter.designatedReporterShowed(), _payoutNumerators, _description, disputeWindow.getStartTime(), disputeWindow.getEndTime()); } function distributeInitialReportingRep(address _reporter, IInitialReporter _initialReporter) private returns (uint256) { IV2ReputationToken _reputationToken = getReputationToken(); uint256 _initialReportStake = repBond; repBond = 0; // If the designated reporter showed up and is not also the rep bond owner return the rep bond to the bond owner. Otherwise it will be used as stake in the first report. if (_reporter == _initialReporter.getDesignatedReporter() && _reporter != repBondOwner) { require(_reputationToken.noHooksTransfer(repBondOwner, _initialReportStake)); _reputationToken.trustedMarketTransfer(_reporter, address(_initialReporter), _initialReportStake); } else { require(_reputationToken.noHooksTransfer(address(_initialReporter), _initialReportStake)); } return _initialReportStake; } /** * @notice Contribute REP to the tentative winning outcome in anticipation of a dispute * @dev This will escrow REP in a bond which will be active immediately if the tentative outcome is successfully disputed. * @param _payoutNumerators An array indicating the payout for each market outcome * @param _amount The amount of REP to contribute * @param _description Any additional information or justification for this dispute * @return Bool True */ function contributeToTentative(uint256[] memory _payoutNumerators, uint256 _amount, string memory _description) public returns (bool) { contributeToTentativeInternal(msg.sender, _payoutNumerators, _amount, _description); return true; } function contributeToTentativeInternal(address _sender, uint256[] memory _payoutNumerators, uint256 _amount, string memory _description) private { require(!disputePacingOn); // The derive call will validate that an Invalid report is entirely paid out on the Invalid outcome bytes32 _payoutDistributionHash = derivePayoutDistributionHash(_payoutNumerators); require(_payoutDistributionHash == getWinningReportingParticipant().getPayoutDistributionHash()); internalContribute(_sender, _payoutDistributionHash, _payoutNumerators, _amount, true, _description); } /** * @notice Contribute REP to a payout other than the tenative winning outcome in order to dispute it * @param _payoutNumerators An array indicating the payout for each market outcome * @param _amount The amount of REP to contribute * @param _description Any additional information or justification for this dispute * @return Bool True */ function contribute(uint256[] memory _payoutNumerators, uint256 _amount, string memory _description) public returns (bool) { // The derive call will validate that an Invalid report is entirely paid out on the Invalid outcome bytes32 _payoutDistributionHash = derivePayoutDistributionHash(_payoutNumerators); require(_payoutDistributionHash != getWinningReportingParticipant().getPayoutDistributionHash()); internalContribute(msg.sender, _payoutDistributionHash, _payoutNumerators, _amount, false, _description); return true; } function internalContribute(address _contributor, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _amount, bool _overload, string memory _description) internal { if (disputePacingOn) { require(disputeWindow.isActive()); } else { require(!disputeWindow.isOver()); } // This will require that the universe is not forking universe.updateForkValues(); IDisputeCrowdsourcer _crowdsourcer = getOrCreateDisputeCrowdsourcer(_payoutDistributionHash, _payoutNumerators, _overload); uint256 _actualAmount = _crowdsourcer.contribute(_contributor, _amount, _overload); uint256 _amountRemainingToFill = _overload ? 0 : _crowdsourcer.getRemainingToFill(); augur.logDisputeCrowdsourcerContribution(universe, _contributor, address(this), address(_crowdsourcer), _actualAmount, _description, _payoutNumerators, _crowdsourcer.getStake(), _amountRemainingToFill, getNumParticipants()); if (!_overload) { if (_amountRemainingToFill == 0) { finishedCrowdsourcingDisputeBond(_crowdsourcer); } else { require(_amountRemainingToFill >= getInitialReporter().getSize(), "Market.internalContribute: Must totally fill bond or leave initial report amount"); } } } function finishedCrowdsourcingDisputeBond(IDisputeCrowdsourcer _crowdsourcer) private { correctLastParticipantSize(); participants.push(_crowdsourcer); clearCrowdsourcers(); // disavow other crowdsourcers uint256 _crowdsourcerSize = IDisputeCrowdsourcer(_crowdsourcer).getSize(); if (_crowdsourcerSize >= universe.getDisputeThresholdForFork()) { universe.fork(); } else { if (_crowdsourcerSize >= universe.getDisputeThresholdForDisputePacing()) { disputePacingOn = true; } disputeWindow = universe.getOrCreateNextDisputeWindow(false); } augur.logDisputeCrowdsourcerCompleted( universe, address(this), address(_crowdsourcer), _crowdsourcer.getPayoutNumerators(), disputeWindow.getStartTime(), disputeWindow.getEndTime(), disputePacingOn, getStakeInOutcome(_crowdsourcer.getPayoutDistributionHash()), getParticipantStake(), participants.length); if (preemptiveDisputeCrowdsourcer != IDisputeCrowdsourcer(0)) { IDisputeCrowdsourcer _newCrowdsourcer = preemptiveDisputeCrowdsourcer; preemptiveDisputeCrowdsourcer = IDisputeCrowdsourcer(0); bytes32 _payoutDistributionHash = _newCrowdsourcer.getPayoutDistributionHash(); // The size of any dispute bond should be (2 * ALL STAKE) - (3 * STAKE IN OUTCOME) uint256 _correctSize = getParticipantStake().mul(2).sub(getStakeInOutcome(_payoutDistributionHash).mul(3)); _newCrowdsourcer.setSize(_correctSize); if (_newCrowdsourcer.getStake() >= _correctSize) { finishedCrowdsourcingDisputeBond(_newCrowdsourcer); } else { crowdsourcers.add(_payoutDistributionHash, address(_newCrowdsourcer)); } } } function correctLastParticipantSize() private { // A dispute has occured if there is more than one completed reporting participant if (participants.length > 1) { IDisputeCrowdsourcer(address(getWinningReportingParticipant())).correctSize(); } } /** * @notice Finalize a market * @return Bool True */ function finalize() public returns (bool) { require(!isFinalized()); uint256[] memory _winningPayoutNumerators; if (isForkingMarket()) { IUniverse _winningUniverse = universe.getWinningChildUniverse(); winningPayoutDistributionHash = _winningUniverse.getParentPayoutDistributionHash(); _winningPayoutNumerators = _winningUniverse.getPayoutNumerators(); } else { require(disputeWindow.isOver()); require(!universe.isForking()); IReportingParticipant _reportingParticipant = getWinningReportingParticipant(); winningPayoutDistributionHash = _reportingParticipant.getPayoutDistributionHash(); _winningPayoutNumerators = _reportingParticipant.getPayoutNumerators(); // Make sure the dispute window for which we record finalization is the standard cadence window and not an initial dispute window disputeWindow = universe.getOrCreatePreviousDisputeWindow(false); disputeWindow.onMarketFinalized(); universe.decrementOpenInterestFromMarket(this); redistributeLosingReputation(); } finalizationTime = augur.getTimestamp(); distributeValidityBondAndMarketCreatorFees(); augur.logMarketFinalized(universe, _winningPayoutNumerators); return true; } function redistributeLosingReputation() private { // If no disputes occurred early exit if (participants.length == 1) { return; } IReportingParticipant _reportingParticipant; // Initial pass is to liquidate losers so we have sufficient REP to pay the winners. Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21 for (uint256 i = 0; i < participants.length; i++) { _reportingParticipant = participants[i]; if (_reportingParticipant.getPayoutDistributionHash() != winningPayoutDistributionHash) { _reportingParticipant.liquidateLosing(); } } IV2ReputationToken _reputationToken = getReputationToken(); // We burn 20% of the REP to prevent griefing attacks which rely on getting back lost REP _reputationToken.burnForMarket(_reputationToken.balanceOf(address(this)) / 5); // Now redistribute REP. Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21. for (uint256 j = 0; j < participants.length; j++) { _reportingParticipant = participants[j]; if (_reportingParticipant.getPayoutDistributionHash() == winningPayoutDistributionHash) { // The last participant's owed REP will not actually be 40% ROI in the event it was created through pre-emptive contributions. We just give them all the remaining non burn REP uint256 amountToTransfer = j == participants.length - 1 ? _reputationToken.balanceOf(address(this)) : _reportingParticipant.getSize().mul(2) / 5; require(_reputationToken.noHooksTransfer(address(_reportingParticipant), amountToTransfer)); } } } /** * @return The amount any settlement proceeds are divided by in order to calculate the market creator fee portion */ function getMarketCreatorSettlementFeeDivisor() public view returns (uint256) { return feeDivisor; } /** * @param _amount The total settlement proceeds of a trade or claim * @return The amount of fees the market creator will receive */ function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256) { return feeDivisor == 0 ? 0 : _amount / feeDivisor; } function recordMarketCreatorFees(uint256 _marketCreatorFees, address _affiliateAddress) public returns (bool) { require(augur.isKnownFeeSender(msg.sender)); if (_affiliateAddress != NULL_ADDRESS && affiliateFeeDivisor != 0) { uint256 _affiliateFees = _marketCreatorFees / affiliateFeeDivisor; affiliateFeesAttoCash[_affiliateAddress] += _affiliateFees; _marketCreatorFees = _marketCreatorFees.sub(_affiliateFees); totalAffiliateFeesAttoCash = totalAffiliateFeesAttoCash.add(_affiliateFees); } marketCreatorFeesAttoCash = marketCreatorFeesAttoCash.add(_marketCreatorFees); if (isFinalized()) { distributeMarketCreatorAndAffiliateFees(_affiliateAddress); } } function distributeValidityBondAndMarketCreatorFees() private { // If the market resolved to invalid the bond gets sent to the dispute window. Otherwise it gets returned to the market creator. marketCreatorFeesAttoCash = validityBondAttoCash.add(marketCreatorFeesAttoCash); distributeMarketCreatorAndAffiliateFees(NULL_ADDRESS); } function distributeMarketCreatorAndAffiliateFees(address _affiliateAddress) private { uint256 _marketCreatorFeesAttoCash = marketCreatorFeesAttoCash; marketCreatorFeesAttoCash = 0; if (!isInvalid()) { universe.withdraw(owner, _marketCreatorFeesAttoCash, address(this)); if (_affiliateAddress != NULL_ADDRESS) { withdrawAffiliateFees(_affiliateAddress); } } else { universe.withdraw(address(universe.getOrCreateNextDisputeWindow(false)), _marketCreatorFeesAttoCash.add(totalAffiliateFeesAttoCash), address(this)); totalAffiliateFeesAttoCash = 0; } } /** * @notice Redeems any owed affiliate fees for a particular address * @dev Will fail if the market is Invalid * @param _affiliate The address that is owed affiliate fees * @return Bool True */ function withdrawAffiliateFees(address _affiliate) public returns (bool) { require(!isInvalid()); uint256 _affiliateBalance = affiliateFeesAttoCash[_affiliate]; if (_affiliateBalance == 0) { return true; } affiliateFeesAttoCash[_affiliate] = 0; universe.withdraw(_affiliate, _affiliateBalance, address(this)); return true; } function getOrCreateDisputeCrowdsourcer(bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, bool _overload) private returns (IDisputeCrowdsourcer) { IDisputeCrowdsourcer _crowdsourcer = _overload ? preemptiveDisputeCrowdsourcer : IDisputeCrowdsourcer(crowdsourcers.getAsAddressOrZero(_payoutDistributionHash)); if (_crowdsourcer == IDisputeCrowdsourcer(0)) { IDisputeCrowdsourcerFactory _disputeCrowdsourcerFactory = IDisputeCrowdsourcerFactory(augur.lookup("DisputeCrowdsourcerFactory")); uint256 _participantStake = getParticipantStake(); if (_overload) { // The stake of a dispute bond is (2 * ALL STAKE) - (3 * STAKE IN OUTCOME) _participantStake = _participantStake.add(_participantStake.mul(2).sub(getHighestNonTentativeParticipantStake().mul(3))); } uint256 _size = _participantStake.mul(2).sub(getStakeInOutcome(_payoutDistributionHash).mul(3)); _crowdsourcer = _disputeCrowdsourcerFactory.createDisputeCrowdsourcer(augur, _size, _payoutDistributionHash, _payoutNumerators); if (!_overload) { crowdsourcers.add(_payoutDistributionHash, address(_crowdsourcer)); } else { preemptiveDisputeCrowdsourcer = _crowdsourcer; } augur.disputeCrowdsourcerCreated(universe, address(this), address(_crowdsourcer), _payoutNumerators, _size, getNumParticipants()); } return _crowdsourcer; } /** * @notice Migrates the market through a fork into the winning Universe * @dev This will extract a new REP no show bond from whoever calls this and if the market is in the reporting phase will require a report be made as well * @param _payoutNumerators An array indicating the payout for each market outcome * @param _description Any additional information or justification for this report * @return Bool True */ function migrateThroughOneFork(uint256[] memory _payoutNumerators, string memory _description) public returns (bool) { // only proceed if the forking market is finalized IMarket _forkingMarket = universe.getForkingMarket(); require(_forkingMarket.isFinalized()); require(!isFinalized()); disavowCrowdsourcers(); bytes32 _winningForkPayoutDistributionHash = _forkingMarket.getWinningPayoutDistributionHash(); IUniverse _destinationUniverse = universe.getChildUniverse(_winningForkPayoutDistributionHash); // follow the forking market to its universe if (disputeWindow != IDisputeWindow(0)) { // Markets go into the standard resolution period during fork migration even if they were in the initial dispute window. We want to give some time for REP to migrate. disputeWindow = _destinationUniverse.getOrCreateNextDisputeWindow(false); } universe.migrateMarketOut(_destinationUniverse); universe = _destinationUniverse; // Pay the REP bond. repBond = universe.getOrCacheMarketRepBond(); repBondOwner = msg.sender; getReputationToken().trustedMarketTransfer(repBondOwner, address(this), repBond); // Update the Initial Reporter IInitialReporter _initialReporter = getInitialReporter(); _initialReporter.migrateToNewUniverse(msg.sender); // If the market is past expiration use the reporting data to make an initial report uint256 _timestamp = augur.getTimestamp(); if (_timestamp > endTime) { doInitialReportInternal(msg.sender, _payoutNumerators, _description); } return true; } function disavowCrowdsourcers() public returns (bool) { IMarket _forkingMarket = getForkingMarket(); require(_forkingMarket != this); require(_forkingMarket != IMarket(NULL_ADDRESS)); require(!isFinalized()); IInitialReporter _initialParticipant = getInitialReporter(); delete participants; participants.push(_initialParticipant); clearCrowdsourcers(); // Send REP from the rep bond back to the address that placed it. If a report has been made tell the InitialReporter to return that REP and reset if (repBond > 0) { IV2ReputationToken _reputationToken = getReputationToken(); uint256 _repBond = repBond; require(_reputationToken.noHooksTransfer(repBondOwner, _repBond)); repBond = 0; } else { _initialParticipant.returnRepFromDisavow(); } augur.logMarketParticipantsDisavowed(universe); return true; } function clearCrowdsourcers() private { crowdsourcers = mapFactory.createMap(augur, address(this)); } function getHighestNonTentativeParticipantStake() public view returns (uint256) { if (participants.length < 2) { return 0; } bytes32 _payoutDistributionHash = participants[participants.length - 2].getPayoutDistributionHash(); return getStakeInOutcome(_payoutDistributionHash); } /** * @notice Gets all REP stake in completed bonds for this market * @return uint256 indicating sum of all stake */ function getParticipantStake() public view returns (uint256) { uint256 _sum; // Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21 for (uint256 i = 0; i < participants.length; ++i) { _sum += participants[i].getStake(); } return _sum; } /** * @param _payoutDistributionHash the payout distribution hash being checked * @return uint256 indicating the REP stake in a single outcome for a particular payout hash */ function getStakeInOutcome(bytes32 _payoutDistributionHash) public view returns (uint256) { uint256 _sum; // Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21 for (uint256 i = 0; i < participants.length; ++i) { IReportingParticipant _reportingParticipant = participants[i]; if (_reportingParticipant.getPayoutDistributionHash() != _payoutDistributionHash) { continue; } _sum = _sum.add(_reportingParticipant.getStake()); } return _sum; } /** * @return The forking market for the associated universe if one exists */ function getForkingMarket() public view returns (IMarket) { return universe.getForkingMarket(); } /** * @return The current bytes32 winning distribution hash if one exists */ function getWinningPayoutDistributionHash() public view returns (bytes32) { return winningPayoutDistributionHash; } /** * @return Bool indicating if the market is finalized */ function isFinalized() public view returns (bool) { return winningPayoutDistributionHash != bytes32(0); } /** * @return The designated reporter */ function getDesignatedReporter() public view returns (address) { return getInitialReporter().getDesignatedReporter(); } /** * @return Bool indicating if the designated reporter showed */ function designatedReporterShowed() public view returns (bool) { return getInitialReporter().designatedReporterShowed(); } /** * @return Bool indicating if the initial reporter was correct */ function designatedReporterWasCorrect() public view returns (bool) { return getInitialReporter().designatedReporterWasCorrect(); } /** * @return Time at which the event is considered ready to report on */ function getEndTime() public view returns (uint256) { return endTime; } /** * @return Bool indicating if the market resolved as anything other than Invalid */ function isInvalid() public view returns (bool) { require(isFinalized()); if (isForkingMarket()) { return getWinningChildPayout(0) > 0; } return getWinningReportingParticipant().getPayoutNumerator(0) > 0; } /** * @return The Initial Reporter contract */ function getInitialReporter() public view returns (IInitialReporter) { return IInitialReporter(address(participants[0])); } /** * @param _index The filled report or dispute at the given index * @return The Initial Reporter or a Dispute Crowdsourcer contract */ function getReportingParticipant(uint256 _index) public view returns (IReportingParticipant) { return participants[_index]; } /** * @param _payoutDistributionHash The payout distribution hash for a Dispute Crowdsourcer contract for this round of disputing * @return The associated Dispute Crowdsourcer contract for this round of disputing */ function getCrowdsourcer(bytes32 _payoutDistributionHash) public view returns (IDisputeCrowdsourcer) { return IDisputeCrowdsourcer(crowdsourcers.getAsAddressOrZero(_payoutDistributionHash)); } /** * @return The associated Initial Reporter or a Dispute Crowdsourcer contract for the current tentative winning payout */ function getWinningReportingParticipant() public view returns (IReportingParticipant) { return participants[participants.length-1]; } /** * @param _outcome The outcome to get a payout for * @return The payout for a particular outcome for the tentative winning payout */ function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256) { if (isForkingMarket()) { return getWinningChildPayout(_outcome); } return getWinningReportingParticipant().getPayoutNumerator(_outcome); } /** * @return The Universe associated with this Market */ function getUniverse() public view returns (IUniverse) { return universe; } /** * @return The Dispute Window currently associated with this Market */ function getDisputeWindow() public view returns (IDisputeWindow) { return disputeWindow; } /** * @return The time the Market was finalzied as a uint256 timestmap if the market was finalized */ function getFinalizationTime() public view returns (uint256) { return finalizationTime; } /** * @return The REP token associated with this Market */ function getReputationToken() public view returns (IV2ReputationToken) { return universe.getReputationToken(); } /** * @return The number of outcomes (including invalid) this market has */ function getNumberOfOutcomes() public view returns (uint256) { return numOutcomes; } /** * @return The number of ticks for this market. The number of ticks determines the possible on chain prices for Shares of the market. (e.g. A Market with 10 ticks can have prices 1-9 and a complete set will cost 10) */ function getNumTicks() public view returns (uint256) { return numTicks; } /** * @param _outcome The outcome to get the associated Share Token for * @return The Share Token associated with the provided outcome */ function getShareToken(uint256 _outcome) public view returns (IShareToken) { return shareTokens[_outcome]; } /** * @return The uint256 timestamp for when the designated reporting period is over and anyone may report */ function getDesignatedReportingEndTime() public view returns (uint256) { return endTime.add(Reporting.getDesignatedReportingDurationSeconds()); } /** * @return The number of rounds of reporting + disputing that have occured */ function getNumParticipants() public view returns (uint256) { return participants.length; } /** * @return The size of the validity bond */ function getValidityBondAttoCash() public view returns (uint256) { return validityBondAttoCash; } /** * @return Bool indicating if slow dispute rounds have turned on */ function getDisputePacingOn() public view returns (bool) { return disputePacingOn; } /** * @param _payoutNumerators array of payouts per outcome * @return Bytes32 has of the payout for use in other functions */ function derivePayoutDistributionHash(uint256[] memory _payoutNumerators) public view returns (bytes32) { return augur.derivePayoutDistributionHash(_payoutNumerators, numTicks, numOutcomes); } function isContainerForShareToken(IShareToken _shadyShareToken) public view returns (bool) { return getShareToken(_shadyShareToken.getOutcome()) == _shadyShareToken; } function isContainerForReportingParticipant(IReportingParticipant _shadyReportingParticipant) public view returns (bool) { require(_shadyReportingParticipant != IReportingParticipant(0)); if (address(preemptiveDisputeCrowdsourcer) == address(_shadyReportingParticipant)) { return true; } if (crowdsourcers.getAsAddressOrZero(_shadyReportingParticipant.getPayoutDistributionHash()) == address(_shadyReportingParticipant)) { return true; } // Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21 for (uint256 i = 0; i < participants.length; i++) { if (_shadyReportingParticipant == participants[i]) { return true; } } return false; } function onTransferOwnership(address _owner, address _newOwner) internal { augur.logMarketTransferred(getUniverse(), _owner, _newOwner); } /** * @notice Transfers ownership of the REP no-show bond * @param _newOwner The new REP no show bond owner * @return Bool True */ function transferRepBondOwnership(address _newOwner) public returns (bool) { require(msg.sender == repBondOwner); repBondOwner = _newOwner; return true; } function assertBalances() public view returns (bool) { universe.assertMarketBalance(); return true; } function isForkingMarket() public view returns (bool) { return universe.isForkingMarket(); } function getWinningChildPayout(uint256 _outcome) public view returns (uint256) { return universe.getWinningChildPayoutNumerator(_outcome); } }
Gets all REP stake in completed bonds for this market return uint256 indicating sum of all stake/ Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21
function getParticipantStake() public view returns (uint256) { uint256 _sum; for (uint256 i = 0; i < participants.length; ++i) { _sum += participants[i].getStake(); } return _sum; }
1,040,705
/** *Submitted for verification at Etherscan.io on 2021-05-07 */ // Sources flattened with hardhat v2.0.3 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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); } // File deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol 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 SafeMathUpgradeable { /** * @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 deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol pragma solidity ^0.6.2; /** * @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 in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol pragma solidity ^0.6.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 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"); } } } // File interfaces/uniswap/IUniswapRouterV2.sol pragma solidity >=0.5.0 <0.8.0; interface IUniswapRouterV2 { function factory() external view returns (address); 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); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // File interfaces/badger/IBadgerGeyser.sol pragma solidity >=0.5.0 <0.8.0; interface IBadgerGeyser { function stake(address) external returns (uint256); function signalTokenLock( address token, uint256 amount, uint256 durationSec, uint256 startTime ) external; function modifyTokenLock( address token, uint256 index, uint256 amount, uint256 durationSec, uint256 startTime ) external; } // File interfaces/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); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() 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 interfaces/sushi/ISushiChef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } interface ISushiChef { // ===== Write ===== function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function add( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function updatePool(uint256 _pid) external; // ===== Read ===== function totalAllocPoint() external view returns (uint256); function poolLength() external view returns (uint256); function owner() external view returns (address); function poolInfo(uint256 _pid) external view returns (PoolInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); } // File interfaces/sushi/IxSushi.sol pragma solidity ^0.6.0; interface IxSushi { function enter(uint256 _amount) external; function leave(uint256 _shares) external; } // File interfaces/badger/IController.sol pragma solidity >=0.5.0 <0.8.0; interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // File interfaces/badger/IMintr.sol pragma solidity >=0.5.0 <0.8.0; interface IMintr { function mint(address) external; } // File interfaces/badger/IStrategy.sol pragma solidity >=0.5.0 <0.8.0; interface IStrategy { function want() external view returns (address); function deposit() external; // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address) external returns (uint256 balance); // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function getName() external pure returns (string memory); function setStrategist(address _strategist) external; function setWithdrawalFee(uint256 _withdrawalFee) external; function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external; function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external; function setGovernance(address _governance) external; function setController(address _controller) external; function tend() external; function harvest() external; } // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol pragma solidity ^0.6.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 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 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; } // File interfaces/uniswap/IUniswapV2Factory.sol pragma solidity >=0.5.0 <0.8.0; 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); } // File contracts/badger-sett/SettAccessControl.sol pragma solidity ^0.6.11; /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require(msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist"); } function _onlyAuthorizedActors() internal view { require(msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors"); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @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 contracts/badger-sett/strategies/BaseStrategy.sol pragma solidity ^0.6.11; /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require(msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController"); } function _onlyAuthorizedPausers() internal view { require(msg.sender == guardian || msg.sender == governance, "onlyPausers"); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public virtual view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public virtual view returns (bool) { return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require(_withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee"); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require(_performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee"); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require(_performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee"); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require(_threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold"); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold"); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapEthIn(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH(balance, 0, path, address(this), now); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_uniswap(address token0, address token1) internal virtual { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _want) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() external virtual view returns (address[] memory); /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external virtual pure returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public virtual view returns (uint256); uint256[49] private __gap; } // File contracts/badger-sett/strategies/BaseStrategySwapper.sol pragma solidity ^0.6.11; /* Expands swapping functionality over base strategy - ETH in and ETH out Variants - Sushiswap support in addition to Uniswap */ abstract contract BaseStrategyMultiSwapper is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; address public constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router /// @notice Swap specified balance of given token on Uniswap with given path function _swap_uniswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap_sushiswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, sushiswap, balance); IUniswapRouterV2(sushiswap).swapExactTokensForTokens(balance, 0, path, address(this), now); } function _swapEthIn_uniswap(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthIn_sushiswap(uint256 balance, address[] memory path) internal { IUniswapRouterV2(sushiswap).swapExactETHForTokens{value: balance}(0, path, address(this), now); } function _swapEthOut_uniswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH(balance, 0, path, address(this), now); } function _swapEthOut_sushiswap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, sushiswap, balance); IUniswapRouterV2(sushiswap).swapExactTokensForETH(balance, 0, path, address(this), now); } function _get_uni_pair(address token0, address token1) internal view returns (address) { address factory = IUniswapRouterV2(uniswap).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } function _get_sushi_pair(address token0, address token1) internal view returns (address) { address factory = IUniswapRouterV2(sushiswap).factory(); return IUniswapV2Factory(factory).getPair(token0, token1); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_sushiswap(address token0, address token1) internal { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, sushiswap, _token0Balance); _safeApproveHelper(token1, sushiswap, _token1Balance); IUniswapRouterV2(sushiswap).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp); } uint256[50] private __gap; } // File contracts/badger-sett/strategies/sushi/StrategySushiLpOptimizer.sol pragma solidity ^0.6.11; /* Optimize Sushi rewards for arbitrary Sushi LP pair */ contract StrategySushiLpOptimizer is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; // WBTC Token address public constant sushi = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; // SUSHI token address public constant xsushi = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI token address public constant chef = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; // Master staking contract uint256 public pid; address public badgerTree; event HarvestState( uint256 xSushiHarvested, uint256 totalxSushi, uint256 toStrategist, uint256 toGovernance, uint256 toBadgerTree, uint256 timestamp, uint256 blockNumber ); struct HarvestData { uint256 xSushiHarvested; uint256 totalxSushi; uint256 toStrategist; uint256 toGovernance; uint256 toBadgerTree; } struct TendData { uint256 sushiTended; } event WithdrawState(uint256 toWithdraw, uint256 preWant, uint256 postWant, uint256 withdrawn); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[2] memory _wantConfig, uint256 _pid, uint256[3] memory _feeConfig ) public initializer whenNotPaused { __BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian); want = _wantConfig[0]; badgerTree = _wantConfig[1]; pid = _pid; // LP token pool ID performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; // Approve Chef and xSushi (aka SushiBar) to use our sushi IERC20Upgradeable(want).approve(chef, uint256(-1)); IERC20Upgradeable(sushi).approve(xsushi, uint256(-1)); } /// ===== Permissioned Functions ===== function setPid(uint256 _pid) external { _onlyGovernance(); pid = _pid; // LP token pool ID } /// ===== View Functions ===== function version() external pure returns (string memory) { return "1.1"; } function getName() external override pure returns (string memory) { return "StrategySushiLpOptimizer"; } function balanceOfPool() public override view returns (uint256) { (uint256 staked, ) = ISushiChef(chef).userInfo(pid, address(this)); return staked; } function getProtectedTokens() external override view returns (address[] memory) { address[] memory protectedTokens = new address[](5); protectedTokens[0] = want; protectedTokens[1] = sushi; protectedTokens[2] = xsushi; return protectedTokens; } function isTendable() public override view returns (bool) { return true; } /// ===== Internal Core Implementations ===== function _onlyNotProtectedTokens(address _asset) internal override { require(address(want) != _asset, "want"); require(address(sushi) != _asset, "sushi"); require(address(xsushi) != _asset, "xsushi"); } /// @dev Deposit Badger into the staking contract /// @dev Track balance in the StakingRewards function _deposit(uint256 _want) internal override { // Deposit all want in sushi chef ISushiChef(chef).deposit(pid, _want); } /// @dev Unroll from all strategy positions, and transfer non-core tokens to controller rewards function _withdrawAll() internal override { (uint256 staked, ) = ISushiChef(chef).userInfo(pid, address(this)); // Withdraw all want from Chef ISushiChef(chef).withdraw(pid, staked); // === Transfer extra token: Sushi === // Withdraw all sushi from SushiBar uint256 _xsushi = IERC20Upgradeable(xsushi).balanceOf(address(this)); IxSushi(xsushi).leave(_xsushi); uint256 _sushi = IERC20Upgradeable(sushi).balanceOf(address(this)); // Send all Sushi to controller rewards IERC20Upgradeable(sushi).safeTransfer(IController(controller).rewards(), _sushi); // Note: All want is automatically withdrawn outside this "inner hook" in base strategy function } /// @dev Withdraw want from staking rewards, using earnings first function _withdrawSome(uint256 _amount) internal override returns (uint256) { // Get idle want in the strategy uint256 _preWant = IERC20Upgradeable(want).balanceOf(address(this)); // If we lack sufficient idle want, withdraw the difference from the strategy position if (_preWant < _amount) { uint256 _toWithdraw = _amount.sub(_preWant); ISushiChef(chef).withdraw(pid, _toWithdraw); // Note: Withdrawl process will earn sushi, this will be deposited into SushiBar on next tend() } // Confirm how much want we actually end up with uint256 _postWant = IERC20Upgradeable(want).balanceOf(address(this)); // Return the actual amount withdrawn if less than requested uint256 _withdrawn = MathUpgradeable.min(_postWant, _amount); emit WithdrawState(_amount, _preWant, _postWant, _withdrawn); return _withdrawn; } /// @notice Harvest sushi gains from Chef and deposit into SushiBar (xSushi) to increase gains /// @notice Any excess Sushi sitting in the Strategy will be staked as well /// @notice The more frequent the tend, the higher returns will be function tend() external whenNotPaused returns (TendData memory) { _onlyAuthorizedActors(); TendData memory tendData; // Note: Deposit of zero harvests rewards balance. ISushiChef(chef).deposit(pid, 0); tendData.sushiTended = IERC20Upgradeable(sushi).balanceOf(address(this)); // Stake any harvested sushi in SushiBar to increase returns if (tendData.sushiTended > 0) { IxSushi(xsushi).enter(tendData.sushiTended); } emit Tend(tendData.sushiTended); return tendData; } /// @dev Harvest accumulated sushi from SushiChef and SushiBar and send to rewards tree for distribution. Take performance fees on gains /// @dev The less frequent the harvest, the higher the gains due to compounding function harvest() external whenNotPaused returns (HarvestData memory) { _onlyAuthorizedActors(); HarvestData memory harvestData; uint256 _beforexSushi = IERC20Upgradeable(xsushi).balanceOf(address(this)); uint256 _beforeLp = IERC20Upgradeable(want).balanceOf(address(this)); // == Harvest sushi rewards from Chef == // Note: Deposit of zero harvests rewards balance, but go ahead and deposit idle want if we have it ISushiChef(chef).deposit(pid, _beforeLp); // Put all sushi into xsushi uint256 _sushi = IERC20Upgradeable(sushi).balanceOf(address(this)); if (_sushi > 0) { IxSushi(xsushi).enter(_sushi); } uint256 _xsushi = IERC20Upgradeable(xsushi).balanceOf(address(this)); //all xsushi is profit harvestData.totalxSushi = _xsushi; //harvested is the xsushi gain since last tend harvestData.xSushiHarvested = _xsushi.sub(_beforexSushi); // Process performance fees //performance fees in xsushi harvestData.toStrategist = _processFee(xsushi, harvestData.totalxSushi, performanceFeeStrategist, strategist); harvestData.toGovernance = _processFee(xsushi, harvestData.totalxSushi, performanceFeeGovernance, IController(controller).rewards()); // Transfer remainder to Tree //tree gets xsushi instead of sushi so it keeps compounding harvestData.toBadgerTree = IERC20Upgradeable(xsushi).balanceOf(address(this)); IERC20Upgradeable(xsushi).safeTransfer(badgerTree, harvestData.toBadgerTree); emit HarvestState( harvestData.xSushiHarvested, harvestData.totalxSushi, harvestData.toStrategist, harvestData.toGovernance, harvestData.toBadgerTree, block.timestamp, block.number ); // We never increase underlying position emit Harvest(0, block.number); return harvestData; } }
Approve Chef and xSushi (aka SushiBar) to use our sushi
function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[2] memory _wantConfig, uint256 _pid, uint256[3] memory _feeConfig ) public initializer whenNotPaused { __BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian); want = _wantConfig[0]; badgerTree = _wantConfig[1]; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; IERC20Upgradeable(want).approve(chef, uint256(-1)); IERC20Upgradeable(sushi).approve(xsushi, uint256(-1)); }
2,107,455
./full_match/137/0x5FC38507A6223Ce492181B79Bf604929AdB85016/sources/vaultchef/GrasslandChef.sol
Calls strategy earn function to harvest rewards from the underlying farm Transfers amount to the strategy and calls strategy deposit function to calculate the shares assigned to the user/
function _deposit( uint256 _pid, uint256 _amount, address _to ) internal { require(_amount > 0, "desposit: amount should be greater than zero"); PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_to]; if (pool.strategy.sharesTotal() > 0) { _tryEarn(pool.strategy); } uint256 balanceBefore = pool.stakeToken.balanceOf( address(pool.strategy) ); pool.stakeToken.safeTransferFrom( address(msg.sender), address(pool.strategy), _amount ); _amount = pool.stakeToken.balanceOf(address(pool.strategy)).sub( balanceBefore ); uint256 sharesAdded = pool.strategy.deposit(_amount); user.shares = user.shares.add(sharesAdded); emit Deposit(_to, _pid, _amount); }
4,687,895
./partial_match/1/0x136b52Aba68EaBdFEa49A134cB47f35AAA61f8a7/sources/BEAR.sol
Interface for the optional metadata functions from the ERC20 standard. _Available since v4.1._/
interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } }
2,717,817
./partial_match/1/0x3c64Dc415EBB4690d1DF2b6216148c8de6Dd29f7/sources/SonartTools.sol
See {IERC721-transferFrom}./
function transferFrom( address from, address to, uint256 tokenId ) virtual public override { _transfer(from, to, tokenId); }
3,662,544
/** *Submitted for verification at Etherscan.io on 2021-08-12 */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.7.0; pragma experimental ABIEncoderV2; // Harbor Trade 2 addresses at Thu Aug 12 13:31:01 CEST 2021 contract Addresses { address constant public ACTIONS = 0x80F33ED0A69935dd74310b9D0009D0BA647Cf223; address constant public AO_REWARD_RECIPIENT = 0x384bE790Ac9526D1103EfC520d733AD64618D90d; address constant public ASSESSOR = 0x6e40A9d1eE2c8eF95322b879CBae35BE6Dd2D143; address constant public ASSESSOR_ADMIN = 0x35e805BA2FB7Ad4C8Ad9D644Ca9Bd34a49f5500d; address constant public COLLECTOR = 0xDdA9c8631ea904Ef4c0444F2A252eC7B45B8e7e9; address constant public COORDINATOR = 0xE2a04a4d4Df350a752ADA79616D7f588C1A195cF; address constant public FEED = 0xdB9A84e5214e03a4e5DD14cFB3782e0bcD7567a7; address constant public JUNIOR_MEMBERLIST = 0x0b635CD35fC3AF8eA29f84155FA03dC9AD0Bab27; address constant public JUNIOR_OPERATOR = 0x6DAecbC801EcA2873599bA3d980c237D9296cF57; address constant public JUNIOR_TOKEN = 0xAA67Bb563e14fBd4E92DCc646aAac0c00c7d9526; address constant public JUNIOR_TRANCHE = 0x294309E42e1b3863a316BEb52df91B1CcB15eef9; address constant public PILE = 0xE7876f282bdF0f62e5fdb2C63b8b89c10538dF32; address constant public PROXY_REGISTRY = 0xC9045c815bF123ad12EA75b9A7c579C1e05051f9; address constant public RESERVE = 0x573a8a054e0C80F0E9B1e96E8a2198BB46c999D6; address constant public ROOT_CONTRACT = 0x4cA805cE8EcE2E63FfC1F9f8F2731D3F48DF89Df; address constant public SENIOR_MEMBERLIST = 0x1Bc55bcAf89f514CE5a8336bEC7429a99e804910; address constant public SENIOR_OPERATOR = 0xEDCD9e36017689c6Fc51C65c517f488E3Cb6C381; address constant public SENIOR_TOKEN = 0xd511397f79b112638ee3B6902F7B53A0A23386C4; address constant public SENIOR_TRANCHE = 0x1940E2A20525B103dCC9884902b0186371227393; address constant public SHELF = 0x5b2b43b3676057e38F332De73A9fCf0F8f6Babf7; address constant public TINLAKE_CURRENCY = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address constant public TITLE = 0x669Db70d3A0D7941F468B0d907E9d90BD7ddA8d1; } interface SpellTinlakeRootLike { function relyContract(address, address) external; } interface SpellMemberlistLike { function updateMember(address, uint) external; } interface SpellReserveLike { function payout(uint currencyAmount) external; } interface DependLike { function depend(bytes32, address) external; } interface FileLike { function file(bytes32, uint) external; function file(bytes32, address) external; } interface AuthLike { function rely(address) external; function deny(address) external; } interface MigrationLike { function migrate(address) external; } interface TrancheLike { function totalSupply() external returns(uint); function totalRedeem() external returns(uint); } interface PoolAdminLike { function relyAdmin(address) external; } interface MgrLike { function lock(uint) external; } interface SpellERC20Like { function balanceOf(address) external view returns (uint256); function transferFrom(address, address, uint) external returns (bool); function approve(address, uint) external; } interface PoolRegistryLike { function file(address pool, bool live, string memory name, string memory data) external; function find(address pool) external view returns (bool live, string memory name, string memory data); } contract TinlakeSpell is Addresses { bool public done; string constant public description = "Tinlake maker integration mainnet spell"; address constant public GOVERNANCE = 0xf3BceA7494D8f3ac21585CA4b0E52aa175c24C25; address constant public POOL_REGISTRY = 0xddf1C516Cf87126c6c610B52FD8d609E67Fb6033; // TODO: set these new swapped addresses address constant public COORDINATOR_NEW = 0x37f3D10Bd18124a16f4DcCA02D41F910E3Aa746A; address constant public ASSESSOR_NEW = 0xf2ED14102ee9D86606Ec24E48e89060ADB6DeFdb; address constant public RESERVE_NEW = 0x86284A692430c25EfF37007c5707a530A6d63A41; address constant public SENIOR_TRANCHE_NEW = 0x7E410F288583BfEe30a306F38e451a93Caaa5C47; address constant public JUNIOR_TRANCHE_NEW = 0x7fe1dBcBEA4e6D3846f5caB67cfC9fce39BF4d71; address constant public POOL_ADMIN = 0xad88b6F193bF31Be0a44A2914809BC517b03D22e; address constant public CLERK = 0xcC2B64dC91245110B513f0ad1393a9720F66B996; // TODO: check these global maker addresses address constant public SPOTTER = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address constant public VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address constant public JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address constant public LIQ = 0x88f88Bb9E66241B73B84f3A6E197FbBa487b1E30; address constant public END = 0xBB856d1742fD182a90239D7AE85706C2FE4e5922; // TODO: set these pool specific maker addresses address constant public URN = 0xeF1699548717aa4Cf47aD738316280b56814C821; address constant public RWA_GEM = 0x873F2101047A62F84456E3B2B13df2287925D3F9; address constant public MAKER_MGR = 0xe1ed3F588A98bF8a3744f4BF74Fd8540e81AdE3f; // TODO: set these address constant public POOL_ADMIN1 = 0xd60f7CFC1E051d77031aC21D9DB2F66fE54AE312; address constant public POOL_ADMIN2 = 0x71d9f8CFdcCEF71B59DD81AB387e523E2834F2b8; address constant public POOL_ADMIN3 = 0x46a71eEf8DbcFcbAC7A0e8D5d6B634A649e61fb8; address constant public POOL_ADMIN4 = 0xa7Aa917b502d86CD5A23FFbD9Ee32E013015e069; address constant public POOL_ADMIN5 = 0x9eDec77dd2651Ce062ab17e941347018AD4eAEA9; address constant public POOL_ADMIN6 = 0xEf270f8877Aa1875fc13e78dcA31f3235210368f; address constant public AO_POOL_ADMIN = 0x384bE790Ac9526D1103EfC520d733AD64618D90d; // TODO: check these uint constant public ASSESSOR_MIN_SENIOR_RATIO = 0; uint constant public MAT_BUFFER = 0.01 * 10**27; // TODO set these string constant public SLUG = "harbor-trade-2"; string constant public IPFS_HASH = "QmeZxngmMcMoHDTXY9ovrweykuW9ACK2VqGapyPxPdVRGf"; // permissions to be set function cast() public { require(!done, "spell-already-cast"); done = true; execute(); } function execute() internal { SpellTinlakeRootLike root = SpellTinlakeRootLike(ROOT_CONTRACT); // set spell as ward on the core contract to be able to wire the new contracts correctly root.relyContract(SHELF, address(this)); root.relyContract(COLLECTOR, address(this)); root.relyContract(JUNIOR_TRANCHE, address(this)); root.relyContract(SENIOR_TRANCHE, address(this)); root.relyContract(JUNIOR_OPERATOR, address(this)); root.relyContract(SENIOR_OPERATOR, address(this)); root.relyContract(JUNIOR_TOKEN, address(this)); root.relyContract(SENIOR_TOKEN, address(this)); root.relyContract(JUNIOR_TRANCHE_NEW, address(this)); root.relyContract(SENIOR_TRANCHE_NEW, address(this)); root.relyContract(JUNIOR_MEMBERLIST, address(this)); root.relyContract(SENIOR_MEMBERLIST, address(this)); root.relyContract(CLERK, address(this)); root.relyContract(POOL_ADMIN, address(this)); root.relyContract(ASSESSOR_NEW, address(this)); root.relyContract(COORDINATOR_NEW, address(this)); root.relyContract(RESERVE, address(this)); root.relyContract(RESERVE_NEW, address(this)); root.relyContract(MAKER_MGR, address(this)); // contract migration --> assumption: root contract is already ward on the new contracts migrateAssessor(); migrateCoordinator(); migrateReserve(); migrateSeniorTranche(); migrateJuniorTranche(); integrateAdapter(); setupPoolAdmin(); // for mkr integration: set minSeniorRatio in Assessor to 0 FileLike(ASSESSOR_NEW).file("minSeniorRatio", ASSESSOR_MIN_SENIOR_RATIO); updateRegistry(); } function migrateAssessor() internal { MigrationLike(ASSESSOR_NEW).migrate(ASSESSOR); // migrate dependencies DependLike(ASSESSOR_NEW).depend("navFeed", FEED); DependLike(ASSESSOR_NEW).depend("juniorTranche", JUNIOR_TRANCHE_NEW); DependLike(ASSESSOR_NEW).depend("seniorTranche", SENIOR_TRANCHE_NEW); DependLike(ASSESSOR_NEW).depend("reserve", RESERVE_NEW); DependLike(ASSESSOR_NEW).depend("lending", CLERK); // migrate permissions AuthLike(ASSESSOR_NEW).rely(COORDINATOR_NEW); AuthLike(ASSESSOR_NEW).rely(RESERVE_NEW); } function migrateCoordinator() internal { MigrationLike(COORDINATOR_NEW).migrate(COORDINATOR); // migrate dependencies DependLike(COORDINATOR_NEW).depend("assessor", ASSESSOR_NEW); DependLike(COORDINATOR_NEW).depend("juniorTranche", JUNIOR_TRANCHE_NEW); DependLike(COORDINATOR_NEW).depend("seniorTranche", SENIOR_TRANCHE_NEW); DependLike(COORDINATOR_NEW).depend("reserve", RESERVE_NEW); // migrate permissions AuthLike(JUNIOR_TRANCHE_NEW).rely(COORDINATOR_NEW); AuthLike(JUNIOR_TRANCHE).deny(COORDINATOR); AuthLike(SENIOR_TRANCHE_NEW).rely(COORDINATOR_NEW); AuthLike(SENIOR_TRANCHE).deny(COORDINATOR); } function migrateReserve() internal { MigrationLike(RESERVE_NEW).migrate(RESERVE); // migrate dependencies DependLike(RESERVE_NEW).depend("currency", TINLAKE_CURRENCY); DependLike(RESERVE_NEW).depend("shelf", SHELF); DependLike(RESERVE_NEW).depend("lending", CLERK); DependLike(RESERVE_NEW).depend("pot", RESERVE_NEW); DependLike(SHELF).depend("distributor", RESERVE_NEW); DependLike(SHELF).depend("lender", RESERVE_NEW); DependLike(COLLECTOR).depend("distributor", RESERVE_NEW); DependLike(JUNIOR_TRANCHE).depend("reserve", RESERVE_NEW); // migrate permissions AuthLike(RESERVE_NEW).rely(JUNIOR_TRANCHE_NEW); AuthLike(RESERVE_NEW).rely(SENIOR_TRANCHE_NEW); AuthLike(RESERVE_NEW).rely(ASSESSOR_NEW); // migrate reserve balance SpellERC20Like currency = SpellERC20Like(TINLAKE_CURRENCY); uint balanceReserve = currency.balanceOf(RESERVE); SpellReserveLike(RESERVE).payout(balanceReserve); currency.transferFrom(address(this), RESERVE_NEW, balanceReserve); } function migrateSeniorTranche() internal { TrancheLike tranche = TrancheLike(SENIOR_TRANCHE_NEW); require((tranche.totalSupply() == 0 && tranche.totalRedeem() == 0), "tranche-has-orders"); DependLike(SENIOR_TRANCHE_NEW).depend("reserve", RESERVE_NEW); DependLike(SENIOR_TRANCHE_NEW).depend("coordinator", COORDINATOR_NEW); DependLike(SENIOR_OPERATOR).depend("tranche", SENIOR_TRANCHE_NEW); AuthLike(SENIOR_TOKEN).deny(SENIOR_TRANCHE); AuthLike(SENIOR_TOKEN).rely(SENIOR_TRANCHE_NEW); AuthLike(SENIOR_TRANCHE_NEW).rely(SENIOR_OPERATOR); SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(SENIOR_TRANCHE_NEW, type(uint256).max); } function migrateJuniorTranche() internal { TrancheLike tranche = TrancheLike(JUNIOR_TRANCHE_NEW); require((tranche.totalSupply() == 0 && tranche.totalRedeem() == 0), "tranche-has-orders"); DependLike(JUNIOR_TRANCHE_NEW).depend("reserve", RESERVE_NEW); DependLike(JUNIOR_TRANCHE_NEW).depend("coordinator", COORDINATOR_NEW); DependLike(JUNIOR_OPERATOR).depend("tranche", JUNIOR_TRANCHE_NEW); AuthLike(JUNIOR_TOKEN).deny(JUNIOR_TRANCHE); AuthLike(JUNIOR_TOKEN).rely(JUNIOR_TRANCHE_NEW); AuthLike(JUNIOR_TRANCHE_NEW).rely(JUNIOR_OPERATOR); SpellMemberlistLike(JUNIOR_MEMBERLIST).updateMember(JUNIOR_TRANCHE_NEW, type(uint256).max); } function integrateAdapter() internal { require(SpellERC20Like(RWA_GEM).balanceOf(MAKER_MGR) == 1 ether); // dependencies DependLike(CLERK).depend("assessor", ASSESSOR_NEW); DependLike(CLERK).depend("mgr", MAKER_MGR); DependLike(CLERK).depend("coordinator", COORDINATOR_NEW); DependLike(CLERK).depend("reserve", RESERVE_NEW); DependLike(CLERK).depend("tranche", SENIOR_TRANCHE_NEW); DependLike(CLERK).depend("collateral", SENIOR_TOKEN); DependLike(CLERK).depend("spotter", SPOTTER); DependLike(CLERK).depend("vat", VAT); DependLike(CLERK).depend("jug", JUG); FileLike(CLERK).file("buffer", MAT_BUFFER); // permissions AuthLike(CLERK).rely(COORDINATOR_NEW); AuthLike(CLERK).rely(RESERVE_NEW); AuthLike(SENIOR_TRANCHE_NEW).rely(CLERK); AuthLike(RESERVE_NEW).rely(CLERK); AuthLike(ASSESSOR_NEW).rely(CLERK); // currency SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(CLERK, type(uint256).max); SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(MAKER_MGR, type(uint256).max); // setup mgr AuthLike(MAKER_MGR).rely(CLERK); FileLike(MAKER_MGR).file("urn", URN); FileLike(MAKER_MGR).file("liq", LIQ); FileLike(MAKER_MGR).file("end", END); FileLike(MAKER_MGR).file("owner", CLERK); FileLike(MAKER_MGR).file("pool", SENIOR_OPERATOR); FileLike(MAKER_MGR).file("tranche", SENIOR_TRANCHE_NEW); // lock token MgrLike(MAKER_MGR).lock(1 ether); } function setupPoolAdmin() internal { PoolAdminLike poolAdmin = PoolAdminLike(POOL_ADMIN); // setup dependencies DependLike(POOL_ADMIN).depend("assessor", ASSESSOR_NEW); DependLike(POOL_ADMIN).depend("lending", CLERK); DependLike(POOL_ADMIN).depend("seniorMemberlist", SENIOR_MEMBERLIST); DependLike(POOL_ADMIN).depend("juniorMemberlist", JUNIOR_MEMBERLIST); // setup permissions AuthLike(ASSESSOR_NEW).rely(POOL_ADMIN); AuthLike(CLERK).rely(POOL_ADMIN); AuthLike(JUNIOR_MEMBERLIST).rely(POOL_ADMIN); AuthLike(SENIOR_MEMBERLIST).rely(POOL_ADMIN); // directly relying governance so it can be used to directly add/remove pool admins without going through the root AuthLike(POOL_ADMIN).rely(GOVERNANCE); // setup admins poolAdmin.relyAdmin(POOL_ADMIN1); poolAdmin.relyAdmin(POOL_ADMIN2); poolAdmin.relyAdmin(POOL_ADMIN3); poolAdmin.relyAdmin(POOL_ADMIN4); poolAdmin.relyAdmin(POOL_ADMIN5); poolAdmin.relyAdmin(POOL_ADMIN6); poolAdmin.relyAdmin(AO_POOL_ADMIN); } function updateRegistry() internal { PoolRegistryLike(POOL_REGISTRY).file(ROOT_CONTRACT, true, SLUG, IPFS_HASH); } }
dependencies permissions currency setup mgr lock token
function integrateAdapter() internal { require(SpellERC20Like(RWA_GEM).balanceOf(MAKER_MGR) == 1 ether); DependLike(CLERK).depend("assessor", ASSESSOR_NEW); DependLike(CLERK).depend("mgr", MAKER_MGR); DependLike(CLERK).depend("coordinator", COORDINATOR_NEW); DependLike(CLERK).depend("reserve", RESERVE_NEW); DependLike(CLERK).depend("tranche", SENIOR_TRANCHE_NEW); DependLike(CLERK).depend("collateral", SENIOR_TOKEN); DependLike(CLERK).depend("spotter", SPOTTER); DependLike(CLERK).depend("vat", VAT); DependLike(CLERK).depend("jug", JUG); FileLike(CLERK).file("buffer", MAT_BUFFER); AuthLike(CLERK).rely(COORDINATOR_NEW); AuthLike(CLERK).rely(RESERVE_NEW); AuthLike(SENIOR_TRANCHE_NEW).rely(CLERK); AuthLike(RESERVE_NEW).rely(CLERK); AuthLike(ASSESSOR_NEW).rely(CLERK); SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(CLERK, type(uint256).max); SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(MAKER_MGR, type(uint256).max); AuthLike(MAKER_MGR).rely(CLERK); FileLike(MAKER_MGR).file("urn", URN); FileLike(MAKER_MGR).file("liq", LIQ); FileLike(MAKER_MGR).file("end", END); FileLike(MAKER_MGR).file("owner", CLERK); FileLike(MAKER_MGR).file("pool", SENIOR_OPERATOR); FileLike(MAKER_MGR).file("tranche", SENIOR_TRANCHE_NEW); MgrLike(MAKER_MGR).lock(1 ether); }
2,367,763
./partial_match/1/0x0C0718F3a881dF98d7c8c59c45eFB321fA49C8CC/sources/CollectionCore.sol
Set signer address on the token contract. Setting signer means we are opening the token contract for external accounts to create tokens. Call this to change the signer immediately./
function setSignerAddress(address _signerAddress, bool _enableExternalMinting) external whenNotPaused isApprovedOBO { require(_signerAddress != address(0), "cant be zero"); signerAddress = _signerAddress; enableExternalMinting = _enableExternalMinting; emit NewSignerEvent(signerAddress); }
15,525,471
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds uint256 constant DAYS_IN_THE_YEAR = 365; uint256 constant MAX_INT = type(uint256).max; uint256 constant DECIMALS18 = 10**18; uint256 constant PRECISION = 10**25; uint256 constant PERCENTAGE_100 = 100 * PRECISION; uint256 constant BLOCKS_PER_DAY = 6450; uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365; uint256 constant APY_TOKENS = DECIMALS18; uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION; uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23; uint256 constant EPOCH_DAYS_AMOUNT = 7; // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155HolderUpgradeable.sol"; import "./interfaces/INFTStaking.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./interfaces/ILiquidityMiningStaking.sol"; import "./abstract/AbstractDependant.sol"; import "./Globals.sol"; contract NFTStaking is INFTStaking, OwnableUpgradeable, ERC1155HolderUpgradeable, AbstractDependant { using SafeMath for uint256; using EnumerableSet for EnumerableSet.UintSet; uint256 public constant PLATINUM_NFT_ID = 1; uint256 public constant GOLD_NFT_ID = 2; uint256 public constant SILVER_NFT_ID = 3; uint256 public constant BRONZE_NFT_ID = 4; uint256 public constant PLATINUM_NFT_DISCOUNT = 15 * PRECISION; // 0.15 uint256 public constant GOLD_NFT_DISCOUNT = 10 * PRECISION; // 0.10 uint256 public constant SILVER_NFT_BOOST = 20 * PRECISION; // 0.20 uint256 public constant BRONZE_NFT_BOOST = 10 * PRECISION; // 0.10 IPolicyBookRegistry public policyBookRegistry; ILiquidityMiningStaking public liquidityMiningStakingETH; //ILiquidityMiningStaking public liquidityMiningStakingUSDT; IERC1155 public bmiUtilityNFT; bool public override enabledlockingNFTs; mapping(address => EnumerableSet.UintSet) internal _nftStakerTokens; // staker -> nfts event Locked(address _userAddr, uint256 _nftId); event Unlocked(address _userAddr, uint256 _nftId); modifier onlyPolicyBooks() { require(policyBookRegistry.isPolicyBook(_msgSender()), "NFTS: No access"); _; } function __NFTStaking_init() external initializer { __Ownable_init(); enabledlockingNFTs = true; } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); liquidityMiningStakingETH = ILiquidityMiningStaking( _contractsRegistry.getLiquidityMiningStakingETHContract() ); // liquidityMiningStakingUSDT = ILiquidityMiningStaking( // _contractsRegistry.getLiquidityMiningStakingUSDTContract() // ); bmiUtilityNFT = IERC1155(_contractsRegistry.getBMIUtilityNFTContract()); } function lockNFT(uint256 _nftId) external override { require(!_nftStakerTokens[_msgSender()].contains(_nftId), "NFTS: Same NFT"); bmiUtilityNFT.safeTransferFrom(_msgSender(), address(this), _nftId, 1, ""); _nftStakerTokens[_msgSender()].add(_nftId); if (_nftId == SILVER_NFT_ID || _nftId == BRONZE_NFT_ID) { _setLMStakingRewardMultiplier(); } emit Locked(_msgSender(), _nftId); } function unlockNFT(uint256 _nftId) external override { require(_nftStakerTokens[_msgSender()].contains(_nftId), "NFTS: No NFT locked"); require(!enabledlockingNFTs, "NFTS: Not allowed"); bmiUtilityNFT.safeTransferFrom(address(this), _msgSender(), _nftId, 1, ""); _nftStakerTokens[_msgSender()].remove(_nftId); if (_nftId == SILVER_NFT_ID || _nftId == BRONZE_NFT_ID) { _setLMStakingRewardMultiplier(); } emit Unlocked(_msgSender(), _nftId); } function getUserReductionMultiplier(address user) external view override onlyPolicyBooks returns (uint256) { uint256 _multiplier; if (_nftStakerTokens[user].contains(PLATINUM_NFT_ID)) { _multiplier = PLATINUM_NFT_DISCOUNT; } else if (_nftStakerTokens[user].contains(GOLD_NFT_ID)) { _multiplier = GOLD_NFT_DISCOUNT; } return _multiplier; } // @TODO: we should let DAO to enable/disable locking of the NFTs function enableLockingNFTs(bool _enabledlockingNFTs) external override onlyOwner { enabledlockingNFTs = _enabledlockingNFTs; } /// @notice set reward multiplier for users who staked in LM staking contract based on NFT locked by users function _setLMStakingRewardMultiplier() internal { uint256 _multiplier; if (_nftStakerTokens[_msgSender()].contains(SILVER_NFT_ID)) { _multiplier = SILVER_NFT_BOOST; } else if (_nftStakerTokens[_msgSender()].contains(BRONZE_NFT_ID)) { _multiplier = BRONZE_NFT_BOOST; } liquidityMiningStakingETH.setRewardMultiplier(_msgSender(), _multiplier); // liquidityMiningStakingUSDT.setRewardMultiplier(_msgSender(), _multiplier); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "../interfaces/IContractsRegistry.sol"; abstract contract AbstractDependant { /// @dev keccak256(AbstractDependant.setInjector(address)) - 1 bytes32 private constant _INJECTOR_SLOT = 0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76; modifier onlyInjectorOrZero() { address _injector = injector(); require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector"); _; } function setInjector(address _injector) external onlyInjectorOrZero { bytes32 slot = _INJECTOR_SLOT; assembly { sstore(slot, _injector) } } /// @dev has to apply onlyInjectorOrZero() modifier function setDependencies(IContractsRegistry) external virtual; function injector() public view returns (address _injector) { bytes32 slot = _INJECTOR_SLOT; assembly { _injector := sload(slot) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IContractsRegistry { function getUniswapRouterContract() external view returns (address); function getUniswapBMIToETHPairContract() external view returns (address); function getUniswapBMIToUSDTPairContract() external view returns (address); function getSushiswapRouterContract() external view returns (address); function getSushiswapBMIToETHPairContract() external view returns (address); function getSushiswapBMIToUSDTPairContract() external view returns (address); function getSushiSwapMasterChefV2Contract() external view returns (address); function getWETHContract() external view returns (address); function getUSDTContract() external view returns (address); function getBMIContract() external view returns (address); function getPriceFeedContract() external view returns (address); function getPolicyBookRegistryContract() external view returns (address); function getPolicyBookFabricContract() external view returns (address); function getBMICoverStakingContract() external view returns (address); function getBMICoverStakingViewContract() external view returns (address); function getLegacyRewardsGeneratorContract() external view returns (address); function getRewardsGeneratorContract() external view returns (address); function getBMIUtilityNFTContract() external view returns (address); function getNFTStakingContract() external view returns (address); function getLiquidityMiningContract() external view returns (address); function getClaimingRegistryContract() external view returns (address); function getPolicyRegistryContract() external view returns (address); function getLiquidityRegistryContract() external view returns (address); function getClaimVotingContract() external view returns (address); function getReinsurancePoolContract() external view returns (address); function getLeveragePortfolioViewContract() external view returns (address); function getCapitalPoolContract() external view returns (address); function getPolicyBookAdminContract() external view returns (address); function getPolicyQuoteContract() external view returns (address); function getLegacyBMIStakingContract() external view returns (address); function getBMIStakingContract() external view returns (address); function getSTKBMIContract() external view returns (address); function getVBMIContract() external view returns (address); function getLegacyLiquidityMiningStakingContract() external view returns (address); function getLiquidityMiningStakingETHContract() external view returns (address); function getLiquidityMiningStakingUSDTContract() external view returns (address); function getReputationSystemContract() external view returns (address); function getAaveProtocolContract() external view returns (address); function getAaveLendPoolAddressProvdierContract() external view returns (address); function getAaveATokenContract() external view returns (address); function getCompoundProtocolContract() external view returns (address); function getCompoundCTokenContract() external view returns (address); function getCompoundComptrollerContract() external view returns (address); function getYearnProtocolContract() external view returns (address); function getYearnVaultContract() external view returns (address); function getYieldGeneratorContract() external view returns (address); function getShieldMiningContract() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface ILiquidityMiningStaking { function blocksWithRewardsPassed() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address _account) external view returns (uint256); /// @notice set boost reward multiplier for stakers who locked NFT /// @dev it allows to set reward multiplier of locked NFT even when there is no LPstaking /// @param _account is the user address /// @param _rewardMultiplier is the boost multiplier of locked NFT by user function setRewardMultiplier(address _account, uint256 _rewardMultiplier) external; function earnedSlashed(address _account) external view returns (uint256); function getAPY() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface INFTStaking { /// @notice let user lock NFT, access: ANY /// @param _nftId is the NFT id which locked function lockNFT(uint256 _nftId) external; /// @notice let user unlcok NFT if enabled, access: ANY /// @param _nftId is the NFT id which unlocked function unlockNFT(uint256 _nftId) external; /// @notice get user reduction multiplier for policy premium, access: PolicyBook /// @param _user is the user who locked NFT /// @return reduction multiplier of locked NFT by user function getUserReductionMultiplier(address _user) external view returns (uint256); /// @notice return enabledlockingNFTs state, access: ANY /// if true user can't unlock NFT and vice versa function enabledlockingNFTs() external view returns (bool); /// @notice To enable/disable locking of the NFTs /// @param _enabledlockingNFTs is a state for enable/disbale locking of the NFT function enableLockingNFTs(bool _enabledlockingNFTs) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IPolicyBookFabric { enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS} /// @notice Create new Policy Book contract, access: ANY /// @param _contract is Contract to create policy book for /// @param _contractType is Contract to create policy book for /// @param _description is bmiXCover token desription for this policy book /// @param _projectSymbol replaces x in bmiXCover token symbol /// @param _initialDeposit is an amount user deposits on creation (addLiquidity()) /// @return _policyBook is address of created contract function create( address _contract, ContractType _contractType, string calldata _description, string calldata _projectSymbol, uint256 _initialDeposit, address _shieldMiningToken ) external returns (address); function createLeveragePools( ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IPolicyBookRegistry { struct PolicyBookStats { string symbol; address insuredContract; IPolicyBookFabric.ContractType contractType; uint256 maxCapacity; uint256 totalSTBLLiquidity; uint256 totalLeveragedLiquidity; uint256 stakedSTBL; uint256 APY; uint256 annualInsuranceCost; uint256 bmiXRatio; bool whitelisted; } function policyBooksByInsuredAddress(address insuredContract) external view returns (address); function policyBookFacades(address facadeAddress) external view returns (address); /// @notice Adds PolicyBook to registry, access: PolicyFabric function add( address insuredContract, IPolicyBookFabric.ContractType contractType, address policyBook, address facadeAddress ) external; function whitelist(address policyBookAddress, bool whitelisted) external; /// @notice returns required allowances for the policybooks function getPoliciesPrices( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external view returns (uint256[] memory _durations, uint256[] memory _allowances); /// @notice Buys a batch of policies function buyPolicyBatch( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external; /// @notice Checks if provided address is a PolicyBook function isPolicyBook(address policyBook) external view returns (bool); /// @notice Checks if provided address is a policyBookFacade function isPolicyBookFacade(address _facadeAddress) external view returns (bool); /// @notice Checks if provided address is a user leverage pool function isUserLeveragePool(address policyBookAddress) external view returns (bool); /// @notice Returns number of registered PolicyBooks with certain contract type function countByType(IPolicyBookFabric.ContractType contractType) external view returns (uint256); /// @notice Returns number of registered PolicyBooks, access: ANY function count() external view returns (uint256); function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType) external view returns (uint256); function countWhitelisted() external view returns (uint256); /// @notice Listing registered PolicyBooks with certain contract type, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type function listByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses function list(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); function listByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); function listWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY function listWithStatsByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Listing registered PolicyBooks with stats, access: ANY function listWithStats(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Getting stats from policy books, access: ANY /// @param policyBooks is list of PolicyBooks addresses function stats(address[] calldata policyBooks) external view returns (PolicyBookStats[] memory _stats); /// @notice Return existing Policy Book contract, access: ANY /// @param insuredContract is contract address to lookup for created IPolicyBook function policyBookFor(address insuredContract) external view returns (address); /// @notice Getting stats from policy books, access: ANY /// @param insuredContracts is list of insuredContracts in registry function statsByInsuredContracts(address[] calldata insuredContracts) external view returns (PolicyBookStats[] memory _stats); } // 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.0 <0.8.0; import "../GSN/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 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; 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 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 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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC1155ReceiverUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155HolderUpgradeable is Initializable, ERC1155ReceiverUpgradeable { function __ERC1155Holder_init() internal initializer { __ERC165_init_unchained(); __ERC1155Receiver_init_unchained(); __ERC1155Holder_init_unchained(); } function __ERC1155Holder_init_unchained() internal initializer { } function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC1155ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155ReceiverUpgradeable is Initializable, ERC165Upgradeable, IERC1155ReceiverUpgradeable { function __ERC1155Receiver_init() internal initializer { __ERC165_init_unchained(); __ERC1155Receiver_init_unchained(); } function __ERC1155Receiver_init_unchained() internal initializer { _registerInterface( ERC1155ReceiverUpgradeable(0).onERC1155Received.selector ^ ERC1155ReceiverUpgradeable(0).onERC1155BatchReceived.selector ); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * _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.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.0.0, only sets of type `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]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
@TODO: we should let DAO to enable/disable locking of the NFTs
function enableLockingNFTs(bool _enabledlockingNFTs) external override onlyOwner { enabledlockingNFTs = _enabledlockingNFTs; }
422,459
pragma solidity ^0.4.11; import "./RLP.sol"; contract ProvethVerifier { using RLP for RLP.RLPItem; using RLP for RLP.Iterator; using RLP for bytes; uint256 constant TX_ROOT_HASH_INDEX = 4; struct UnsignedTransaction { uint256 nonce; uint256 gasprice; uint256 startgas; address to; uint256 value; bytes data; bool isContractCreation; } struct SignedTransaction { uint256 nonce; uint256 gasprice; uint256 startgas; address to; uint256 value; bytes data; uint256 v; uint256 r; uint256 s; bool isContractCreation; } function decodeUnsignedTx(bytes rlpUnsignedTx) internal view returns (UnsignedTransaction memory t) { RLP.RLPItem[] memory fields = rlpUnsignedTx.toRLPItem().toList(); require(fields.length == 6); address potentialAddress; bool isContractCreation; if(fields[3].isEmpty()) { potentialAddress = 0x0000000000000000000000000000000000000000; isContractCreation = true; } else { potentialAddress = fields[3].toAddress(); isContractCreation = false; } t = UnsignedTransaction( fields[0].toUint(), // nonce fields[1].toUint(), // gasprice fields[2].toUint(), // startgas potentialAddress, // to fields[4].toUint(), // value fields[5].toData(), // data isContractCreation ); } // TODO(lorenzb): This should actually be pure, not view. Probably because // wrong declarations in RLP.sol. function decodeSignedTx(bytes rlpSignedTx) internal view returns (SignedTransaction memory t) { RLP.RLPItem[] memory fields = rlpSignedTx.toRLPItem().toList(); address potentialAddress; bool isContractCreation; if(fields[3].isEmpty()) { potentialAddress = 0x0000000000000000000000000000000000000000; isContractCreation = true; } else { potentialAddress = fields[3].toAddress(); isContractCreation = false; } t = SignedTransaction( fields[0].toUint(), fields[1].toUint(), fields[2].toUint(), potentialAddress, fields[4].toUint(), fields[5].toData(), fields[6].toUint(), fields[7].toUint(), fields[8].toUint(), isContractCreation ); } function decodeNibbles(bytes compact, uint skipNibbles) internal pure returns (bytes memory nibbles) { require(compact.length > 0); uint length = compact.length * 2; require(skipNibbles <= length); length -= skipNibbles; nibbles = new bytes(length); uint nibblesLength = 0; for (uint i = skipNibbles; i < skipNibbles + length; i += 1) { if (i % 2 == 0) { nibbles[nibblesLength] = bytes1((uint8(compact[i/2]) >> 4) & 0xF); } else { nibbles[nibblesLength] = bytes1((uint8(compact[i/2]) >> 0) & 0xF); } nibblesLength += 1; } assert(nibblesLength == nibbles.length); } function merklePatriciaCompactDecode(bytes compact) internal pure returns (bytes memory nibbles) { require(compact.length > 0); uint first_nibble = uint8(compact[0]) >> 4 & 0xF; uint skipNibbles; if (first_nibble == 0) { skipNibbles = 2; } else if (first_nibble == 1) { skipNibbles = 1; } else if (first_nibble == 2) { skipNibbles = 2; } else if (first_nibble == 3) { skipNibbles = 1; } else { // Not supposed to happen! revert(); } return decodeNibbles(compact, skipNibbles); } function isPrefix(bytes prefix, bytes full) internal pure returns (bool) { if (prefix.length > full.length) { return false; } for (uint i = 0; i < prefix.length; i += 1) { if (prefix[i] != full[i]) { return false; } } return true; } function sharedPrefixLength(uint xsOffset, bytes xs, bytes ys) internal pure returns (uint) { for (uint i = 0; i + xsOffset < xs.length && i < ys.length; i++) { if (xs[i + xsOffset] != ys[i]) { return i; } } return i; } struct Proof { uint256 kind; bytes rlpBlockHeader; bytes32 txRootHash; bytes rlpTxIndex; uint txIndex; bytes mptPath; bytes stackIndexes; RLP.RLPItem[] stack; } function decodeProofBlob(bytes proofBlob) internal view returns (Proof memory proof) { RLP.RLPItem[] memory proofFields = proofBlob.toRLPItem().toList(); proof = Proof( proofFields[0].toUint(), proofFields[1].toBytes(), proofFields[1].toList()[TX_ROOT_HASH_INDEX].toBytes32(), proofFields[2].toBytes(), proofFields[2].toUint(), proofFields[3].toData(), proofFields[4].toData(), proofFields[5].toList() ); } uint8 constant public TX_PROOF_RESULT_PRESENT = 1; uint8 constant public TX_PROOF_RESULT_ABSENT = 2; function txProof( bytes32 blockHash, bytes proofBlob ) public returns ( uint8 result, // see TX_PROOF_RESULT_* uint256 index, uint256 nonce, uint256 gasprice, uint256 startgas, address to, // 20 byte address for "regular" tx, // empty for contract creation tx uint256 value, bytes data, uint256 v, uint256 r, uint256 s, bool isContractCreation ) { SignedTransaction memory t; (result, index, t) = validateTxProof(blockHash, proofBlob); nonce = t.nonce; gasprice = t.gasprice; startgas = t.startgas; to = t.to; value = t.value; data = t.data; v = t.v; r = t.r; s = t.s; isContractCreation = t.isContractCreation; } function validateTxProof( bytes32 blockHash, bytes proofBlob ) internal returns (uint8 result, uint256 index, SignedTransaction memory t) { result = 0; index = 0; Proof memory proof = decodeProofBlob(proofBlob); require(proof.stack.length == proof.stackIndexes.length); if (proof.kind != 1) { revert(); } if (keccak256(proof.rlpBlockHeader) != blockHash) { revert(); } bytes memory rlpTx = validateMPTProof(proof.txRootHash, proof.mptPath, proof.stackIndexes, proof.stack); bytes memory mptKeyNibbles = decodeNibbles(proof.rlpTxIndex, 0); if (rlpTx.length == 0) { // empty node if (isPrefix(proof.mptPath, mptKeyNibbles)) { result = TX_PROOF_RESULT_ABSENT; index = proof.txIndex; return; } else { revert(); } } else { // tx if (isPrefix(proof.mptPath, mptKeyNibbles) && proof.mptPath.length == mptKeyNibbles.length) { result = TX_PROOF_RESULT_PRESENT; index = proof.txIndex; t = decodeSignedTx(rlpTx); return; } else { revert(); } } } function mptHashHash(bytes memory input) internal pure returns (bytes32) { if (input.length < 32) { return keccak256(input); } else { return keccak256(abi.encodePacked(keccak256(abi.encodePacked(input)))); } } function validateMPTProof( bytes32 rootHash, bytes mptPath, bytes stackIndexes, RLP.RLPItem[] memory stack ) internal returns (bytes memory value) { require(stackIndexes.length == stack.length); uint mptPathOffset = 0; bytes32 nodeHashHash; bytes memory rlpNode; RLP.RLPItem[] memory node; RLP.RLPItem memory rlpValue; if (stack.length == 0) { // Root hash of empty tx trie require(rootHash == 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421); return new bytes(0); } for (uint i = 0; i < stack.length; i++) { // We use the fact that an rlp encoded list consists of some // encoding of its length plus the concatenation of its // *rlp-encoded* items. rlpNode = stack[i].toBytes(); if (i == 0 && rootHash != keccak256(rlpNode)) { revert(); } if (i != 0 && nodeHashHash != mptHashHash(rlpNode)) { revert(); } node = stack[i].toList(); if (node.length == 2) { // Extension or Leaf node bytes memory nodePath = merklePatriciaCompactDecode(node[0].toData()); uint prefixLength = sharedPrefixLength(mptPathOffset, mptPath, nodePath); mptPathOffset += prefixLength; if (stackIndexes[i] == 0xff) { // proof claims divergent extension or leaf if (i < stack.length - 1) { // divergent node must come last in proof revert(); } if (prefixLength == nodePath.length) { // node isn't divergent revert(); } if (mptPathOffset != mptPath.length) { // didn't consume entire mptPath revert(); } return new bytes(0); } else if (stackIndexes[i] == 1) { if (prefixLength != nodePath.length) { // node is divergent revert(); } if (i < stack.length - 1) { // not last level if (node[uint(stackIndexes[i])].isData()) { nodeHashHash = keccak256(node[uint(stackIndexes[i])].toData()); } else { nodeHashHash = keccak256(node[uint(stackIndexes[i])].toBytes()); } } else { // didn't consume entire mptPath if (mptPathOffset != mptPath.length) { revert(); } rlpValue = node[uint(stackIndexes[i])]; return rlpValue.toData(); } } else { // an extension/leaf node only has two fields. revert(); } } else if (node.length == 17) { // Branch node if (stackIndexes[i] < 16) { // advance mptPathOffset if (mptPathOffset >= mptPath.length || mptPath[mptPathOffset] != stackIndexes[i]) { revert(); } mptPathOffset += 1; if (i < stack.length - 1) { // not last level if (node[uint(stackIndexes[i])].isData()) { nodeHashHash = keccak256(node[uint(stackIndexes[i])].toData()); } else { nodeHashHash = keccak256(node[uint(stackIndexes[i])].toBytes()); } } else { // last level // must have an empty hash, everything else is invalid if (node[uint(stackIndexes[i])].toData().length != 0) { revert(); } if (mptPathOffset != mptPath.length) { // didn't consume entire mptPath revert(); } return new bytes(0); } } else if (stackIndexes[i] == 16) { // we want the value stored in this node if (i < stack.length - 1) { // value must come last in proof revert(); } if (mptPathOffset != mptPath.length) { // didn't consume entire mptPath revert(); } rlpValue = node[uint(stackIndexes[i])]; return rlpValue.toData(); } else { revert(); } } else { revert(); // This should never happen as we have // already authenticated node at this point. } } // We should never reach this point. revert(); } }
empty for contract creation tx
function txProof( bytes32 blockHash, bytes proofBlob ) public returns ( uint256 index, uint256 nonce, uint256 gasprice, uint256 startgas, uint256 value, bytes data, uint256 v, uint256 r, uint256 s, bool isContractCreation ) { SignedTransaction memory t; (result, index, t) = validateTxProof(blockHash, proofBlob); nonce = t.nonce; gasprice = t.gasprice; startgas = t.startgas; to = t.to; value = t.value; data = t.data; v = t.v; r = t.r; s = t.s; isContractCreation = t.isContractCreation; }
6,404,817
contract AssetVault { // TODO: update to recent Solidity developments // - replace string32 by bytes32 // - replace mappings with counter by arrays as much as possible // - (if possible) replace clumsy "find this or that" logic by functions, for // example getAsset(assetID). // Data structure to hold information about a single asset. struct Asset { // Unique AssetChain ID as used in cryptoledgers where it has been registered. string32 id; // Descriptive name of the asset. // Could be removed once this is purely used as a secure data store. string32 name; // List of verifications confirmed for this asset. mapping (uint => Verification) verifications; // Counter for access to the mapping. uint verificationCount; } // Collection of assets and their count, to be used for one individual owner. struct AssetCollection { mapping (uint => Asset) assets; uint assetCount; } struct Verification { // The user who verified the asset. address verifier; // 1 = ownership // 2 = quality // ... uint type; // Whether the verification has been confirmed. Set to true after processing the verification. bool isConfirmed; // Further data could include date of verification, state of the asset as it was at that point, // etc. However these can all be retracted from the blockchain, assuming we can read the // contract storage history. } // The collection that stores all assets by owner address. mapping (address => AssetCollection) public assetsByOwner; // Mapping from owner address to asset ID, to ensure that assets have only one owner. mapping (string32 => address) public ownerByAssetID; // List of all owners, for iteration. // TODO: replace by array so OwnerCount can be removed. mapping (uint => address) public owners; // Total owners stored in Owners, for iteration. uint public ownerCount; struct TransferRequest{ // TODO: add request date / block height so they can expire string32 assetID; address requester; } // Collection of requests for transfer mapping (uint => TransferRequest) public transferRequests; uint public transferRequestCount; // Constructor function AssetVault() { } // Register an asset. function createAsset(string32 id, string32 name) returns (bool dummyForLayout) { // Check: has the asset already been registered? if(ownerByAssetID[id] != 0x0) // Asset with this ID has already been registered. No action. return; // Good to go. Register the asset. AssetCollection ac = assetsByOwner[tx.origin]; // Add a new owner if the owner wasn't registered before. if(ac.assetCount == 0) owners[ownerCount++] = tx.origin; ownerByAssetID[id] = tx.origin; Asset a = ac.assets[ac.assetCount++]; a.id = id; a.name = name; } // BEGIN plumbing functions to access properties of mappings that contain structs that // contain mappings. function getAssetID(address ownerAddress, uint assetIndex) returns (string32 id){ AssetCollection ac = assetsByOwner[ownerAddress]; return ac.assets[assetIndex].id; } function getAssetName(address ownerAddress, uint assetIndex) returns (string32 name){ AssetCollection ac = assetsByOwner[ownerAddress]; return ac.assets[assetIndex].name; } // Get the index of an asset in its owner's mapping. function getAssetIndex(address ownerAddress, string32 assetID) returns (uint assetIndex){ AssetCollection ac = assetsByOwner[ownerAddress]; assetIndex = 0; while(assetIndex < ac.assetCount){ Asset asset = ac.assets[assetIndex]; if(asset.id == assetID) return; assetIndex++; } // TODO: signal situation that the asset wasn't found (return bool isFound?) } // Plumbing function to get all properties of an asset. // Currently not possible because return type must be a primitive type. function getAsset(address ownerAddress, uint assetIndex) returns (string32 id, string32 name, uint verificationCount) { AssetCollection ac = assetsByOwner[ownerAddress]; Asset a = ac.assets[assetIndex]; id = a.id; name = a.name; verificationCount = a.verificationCount; } // Get an asset by its ID only. Convenience function. //function getAssetByID(string32 assetID) returns (string32 id, string32 name, uint verificationCount) { //} // END plumbing functions to access properties of mappings that contain structs that // contain mappings. // Transfer ownership of an asset to a new owner. To be called by the prospective new owner. function requestTransfer(string32 assetID) returns (bool dummyForLayout) { // Check: is the asset ID valid? if(ownerByAssetID[assetID] == 0x0) { return; } // Check: is the requester the current owner? Then no request. They already own it. if(ownerByAssetID[assetID] == tx.origin) { return; } // Check: prevent duplicate requests. // Is there already a transfer request for this asset by the same requester? Then don't create // a new one. // TODO // Create TransferRequest TransferRequest tr = transferRequests[transferRequestCount++]; tr.assetID = assetID; tr.requester = tx.origin; } // Confirm ownership transfer of an asset to a new owner. To be called by the current owner. function processTransfer(string32 assetID, address newOwner, bool confirm) returns (bool dummyForLayout) { // Check: is the asset ID valid? if(ownerByAssetID[assetID] == 0x0) { return; } // Check: is the sender the current owner of the asset? If not, the sender is not authorized to confirm. if(ownerByAssetID[assetID] != tx.origin) { return; } // Find a TransferRequest for this asset and newOwner address. // TODO: refactor this loop to getTransferRequestIndex(assetID, requesterAddress); uint trIndex = 0; while(trIndex <= transferRequestCount) { TransferRequest tr = transferRequests[trIndex]; if (tr.assetID == assetID && tr.requester == newOwner) { // Correct request found. Effectuate transfer and clear it. // Remove it from the current owners assets. AssetCollection acOwner = assetsByOwner[tx.origin]; uint aIndex = getAssetIndex(tx.origin, assetID); Asset a = acOwner.assets[aIndex]; // If the owner confirms the request, transfer it. In any case delete the request after processing. if(confirm) { // TODO: refactor to private function transferAsset(assetID, currentOwner, newOwner). // Add it to the newOwners assets. AssetCollection acRequester = assetsByOwner[newOwner]; if(acRequester.assetCount==0) // New owner, store it. owners[ownerCount++] = newOwner; // Transfer the whole asset by assigning it to the new mapping. acRequester.assets[acRequester.assetCount++] = a; // BEGIN WORKAROUND // This way of assigning includes the mapping of verifications. However, all properties // of the verifications are set to null. This is likely a bug in Solidity PoC8. // We work around this by deep copying the individual properties. Asset newAsset = acRequester.assets[acRequester.assetCount - 1]; uint verificationIndex = 0; while(verificationIndex < newAsset.verificationCount){ newAsset.verifications[verificationIndex].verifier = a.verifications[verificationIndex].verifier; newAsset.verifications[verificationIndex].type = a.verifications[verificationIndex].type; newAsset.verifications[verificationIndex].isConfirmed = a.verifications[verificationIndex].isConfirmed; verificationIndex++; } // END WORKAROUND // Delete the asset of the old owner. delete acOwner.assets[aIndex]; // Update OwnerByAssetID ownerByAssetID[assetID] = newOwner; } // Delete transfer request delete transferRequests[trIndex]; // COULD DO: remove previous owner from Owners if they don't have any assets left. // Transfer completed, done. return; } trIndex++; } // Check: clean up any other transfer requests for this asset // TODO } // Remove expired transfer requests function cleanTransferRequests() returns (bool dummyForLayout) { // TODO: add a block number to TransferRequest so we can see when it expires. // TODO: implement } // VERIFICATIONS // Request verification of an asset. function requestVerification(string32 assetID, address verifier, uint type) returns (bool dummyForLayout) { // Check: is the asset ID valid? if(ownerByAssetID[assetID] == 0x0) { return; } // Check: is the verifier the current owner? That's not allowed. if(tx.origin == verifier) { return; } // Check: is the requester the current owner? if(ownerByAssetID[assetID] != tx.origin) { return; } // Get the asset. Because functions can't return structs (yet) we need various // function calls and access the mapping directly. Still better than having a while loop // everywhere though. uint aIndex = getAssetIndex(tx.origin, assetID); AssetCollection acOwner = assetsByOwner[ownerByAssetID[assetID]]; Asset a = acOwner.assets[aIndex]; // Add it to the asset verifications Verification v = a.verifications[a.verificationCount++]; v.verifier = verifier; v.type = type; } // Get the index of a specific verification of an asset. function getVerificationIndex(address ownerAddress, string32 assetID, address verifier, uint type) returns (uint verificationIndex) { uint assetIndex = getAssetIndex(ownerAddress, assetID); Asset a = assetsByOwner[ownerAddress].assets[assetIndex]; verificationIndex = 0; while(verificationIndex < a.verificationCount){ Verification v = a.verifications[verificationIndex]; if(v.verifier == verifier && v.type == type) return; verificationIndex++; } // TODO: distinguish between "not found" and "index = 0". Now both give the same result. } // Get info about a Verification of an asset. function getVerification(string32 assetID, uint verificationIndex) returns (address verifier, uint type, bool isConfirmed) { address ownerAddress = ownerByAssetID[assetID]; uint assetIndex = getAssetIndex(ownerAddress, assetID); Asset a = assetsByOwner[ownerAddress].assets[assetIndex]; Verification v = a.verifications[verificationIndex]; verifier = v.verifier; type = v.type; isConfirmed = v.isConfirmed; } // Process a pending verification. To be called by the verifier. function processVerification(string32 assetID, uint type, bool confirm) returns (bool processedCorrectly) { address ownerAddress = ownerByAssetID[assetID]; // Check: is the asset ID valid? if(ownerAddress == 0x0) { return; } // Find the verification. uint assetIndex = getAssetIndex(ownerAddress, assetID); Asset a = assetsByOwner[ownerAddress].assets[assetIndex]; // Try to find a verification request where the caller is the verifier. If not, the caller is not allowed // to process. uint verificationIndex = getVerificationIndex(ownerAddress, assetID, tx.origin, type); // TODO: distinguish between "no such verification" and "index == 0". //if(notExisting) // return; // Get the verificationIndex Verification v = a.verifications[verificationIndex]; // Check: is this a valid verification? (does it exist?) if(v.verifier == 0x0) return; // Check: is the caller the verifier? Only then they may process it. if(v.verifier != tx.origin) return; // Check: already confirmed? Then no action. if(v.isConfirmed) return; if(confirm) { // Want to confirm? Set isConfirm to true. v.isConfirmed = true; } else { // Want to deny? Delete it. delete a.verifications[verificationIndex]; } processedCorrectly = true; } }
Plumbing function to get all properties of an asset. Currently not possible because return type must be a primitive type.
function getAsset(address ownerAddress, uint assetIndex) returns (string32 id, string32 name, uint verificationCount) { AssetCollection ac = assetsByOwner[ownerAddress]; Asset a = ac.assets[assetIndex]; id = a.id; name = a.name; verificationCount = a.verificationCount; }
2,525,636
./full_match/1/0xD842D9651F69cEBc0b2Cffc291fC3D3Fe7b5D226/sources/solidity/contracts/core/USDA.sol
Removes a vault controller from the list _vaultController The vault controller to remove The vault controller is removed from the list but keeps the role as to not brick it
function removeVaultControllerFromList(address _vaultController) external onlyOwner { _vaultControllers.remove(_vaultController); emit VaultControllerRemovedFromList(_vaultController); }
16,421,854
./full_match/73799/0x972B3c7936B1221f59fD44Fa8CD88a474f02D335/sources/project_/contracts/Staking/HBTVault.sol
The entrypoint of funds into the system. People deposit with this function into the vault. The vault is then in charge of sending funds into the strategy./
function deposit(uint256 _amount) public nonReentrant { require(_amount > 0, "amount should be more than zero"); require(depositWhitelist[msg.sender], "Cannot deposit"); strategy.beforeDeposit(); uint256 _pool = balance(); want().safeTransferFrom(msg.sender, address(this), _amount); earn(_amount); uint256 _after = balance(); uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); emit OnDeposit(_amount, msg.sender); }
16,361,865
/** *Submitted for verification at Etherscan.io on 2021-05-13 */ /** * Proof of Work, Jonathan Chomko, 2021 * */ // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol 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)); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol 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; } } // File: @openzeppelin/contracts/access/AccessControl.sol // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract 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; } } // File: @openzeppelin/contracts/utils/Counters.sol pragma solidity >=0.6.0 <0.8.0; /** * @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); } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; // /** // * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension // * @dev See https://eips.ethereum.org/EIPS/eip-721 // */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol 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 IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol 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 EnumerableMap { // 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)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @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); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings 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 => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.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. */ constructor (string memory name_, string memory symbol_) public { _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"); return string(abi.encodePacked(baseURI(), tokenId.toString(), '.json')); } /** * @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 {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.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 = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.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 = ERC721.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(ERC721.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( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.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 { } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // File: contracts/ProofOfWork721.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ProofOfWork721 is Context, ERC721, Ownable, ERC721Burnable { using Counters for Counters.Counter; using SafeMath for uint256; // bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); address payable public withdrawalAddress; //This needs to be the same as the maxNumberOfPieces bool[50] public isTokenMinted; //Token sale control logic Counters.Counter private piecesSold; uint256 public maxNumberOfPieces; uint256 public maxTokenIdForSale; uint256 public minTokenIdForSale; //Standard sale bool public standardSaleActive; uint256 public pricePerPiece; //Dutch Auction uint256 public startBlock; uint256 public startPrice; uint256 public offerPriceDecrement; uint256 public endPrice; uint256 public currentPrice; bool public dutchAuctionActive; event Purchase(address buyer, uint256 price, uint256 tokenId); event MetadataUpdated(string newTokenUriBase); constructor( uint256 givenPricePerPiece, address payable givenWithdrawalAddress, string memory givenTokenUriBase ) public ERC721("Proof of Work", "POW") { pricePerPiece = givenPricePerPiece; withdrawalAddress = givenWithdrawalAddress; _setBaseURI(givenTokenUriBase); maxNumberOfPieces = 50; maxTokenIdForSale = 0; minTokenIdForSale = 1; } //Update metadata base function setMetadataBase(string memory givenTokenUriBase) public onlyOwner{ emit MetadataUpdated(givenTokenUriBase); _setBaseURI(givenTokenUriBase); } //Specify a range of tokens for current sale function setSaleRange(uint256 givenMinTokenIdForSale, uint256 givenMaxTokenIdForSale) public onlyOwner { maxTokenIdForSale = givenMaxTokenIdForSale; minTokenIdForSale = givenMinTokenIdForSale; } //Dutch auction, price decreases each block until it reaches the minimum function startDutchAuction(uint256 givenStartPrice, uint256 givenOfferPriceDecrement, uint256 givenEndPrice) public onlyOwner{ startBlock = block.number; startPrice = givenStartPrice; endPrice = givenEndPrice; currentPrice = givenStartPrice; offerPriceDecrement = givenOfferPriceDecrement; dutchAuctionActive = true; } function endDutchAuction() public onlyOwner{ dutchAuctionActive = false; } //Called by front-end to determine current price function getDutchPrice() external view returns(uint256) { uint256 tempPrice = startPrice - (block.number - startBlock) * offerPriceDecrement; if(tempPrice < endPrice || tempPrice > startPrice){ tempPrice = endPrice; } return tempPrice; } //Dutch auction buy function, calculates appropriate price based on blocks elapsed function buyDutch( uint256 givenTokenId) public payable{ require(dutchAuctionActive, "dutch auction must be active"); currentPrice = startPrice - (block.number - startBlock) * offerPriceDecrement; if(currentPrice < endPrice || currentPrice > startPrice){ currentPrice = endPrice; } require(msg.value >= currentPrice, "must send in correct amount "); mintItem(givenTokenId); } //Standard buying functions are separate //Switch function setSaleActive(bool isActive) public onlyOwner { standardSaleActive = isActive; } function setPrice(uint256 givenPrice) external onlyOwner { pricePerPiece = givenPrice; } function getPrice() external view returns(uint256) { return pricePerPiece; } function buy( uint256 givenTokenId) public payable { require(standardSaleActive || msg.sender == owner(), "sale must be active"); require(msg.value == pricePerPiece, "must send in correct amount"); mintItem(givenTokenId); } //Withdrawal functions function setWithdrawalAddress(address payable givenWithdrawalAddress) public onlyOwner { withdrawalAddress = givenWithdrawalAddress; } function withdrawEth() public onlyOwner { Address.sendValue(withdrawalAddress, address(this).balance); } //Token owner info function tokenInfo(uint256 tokenId) public view returns (address) { return (ownerOf(tokenId)); } function getOwners(uint256 start, uint256 end) public view returns (address[] memory){ address[] memory re = new address[](end - start); for (uint256 i = start; i < end; i++) { if(isTokenMinted[i]){ re[i - start] = ownerOf(i); } } return re; } function mintItem(uint256 givenTokenId) private returns (uint256) { require(givenTokenId <= maxTokenIdForSale, "given token value is greater than sale limit"); require(givenTokenId >= minTokenIdForSale, "given token value is less than sale limit"); require(piecesSold.current() < maxNumberOfPieces, "series is sold out"); emit Purchase(msg.sender, msg.value, givenTokenId); _mint(msg.sender, givenTokenId); isTokenMinted[givenTokenId] = true; piecesSold.increment(); return givenTokenId; } }
Called by front-end to determine current price
function getDutchPrice() external view returns(uint256) { uint256 tempPrice = startPrice - (block.number - startBlock) * offerPriceDecrement; if(tempPrice < endPrice || tempPrice > startPrice){ tempPrice = endPrice; } return tempPrice; }
10,753,175
pragma solidity >=0.5.8 <0.7.0; contract Admin { address adminAddress; constructor () internal { } function isAdmin () public view returns (bool) { return adminAddress == msg.sender; } modifier admin { //require (isAdmin(), "user is not admin"); require (adminAddress == msg.sender, "user is not admin"); _; } } contract Site is Admin { struct Artist { string name; string description; bool enabled; // address payable addr; } struct Feature { uint startTime; uint endTime; int64 lastFeatureId; // -1 if none int64 currentBidId; // -1 if none bool accepted; // artist has approved the top bid for this feature } struct Art { // uint32 id; //uint16 artistId; address artistAddress; bool finished; int64 currentFeatureId; // -1 if none } struct Bid { // uint32 id; int64 lowerBidId; // if this outbids an older bid, otherwise -1 address payable addr; uint amount; string request; } // Artist[] artists; mapping (address => Artist) artists; address[] artistAddresses; Art[] art; Feature[] features; Bid[] bids; uint64 fee; string testMessage; event FeatureCreated (uint64 featureId); event ArtCreated (uint64 artId); // limit to admin function setFee (uint64 _fee) public { fee = _fee; } function getFee () public view returns (uint64) { return fee; } function isArtist () public view returns (bool) { return artists[msg.sender].enabled; } // probably isn't useful. We want to know if msg.sender matches specific artist generally modifier artist { // require (isArtist(), "user is not an artist"); // does not work require (artists[msg.sender].enabled, "user is not an artist"); _; } // change when struct definition changes function getArt (uint i) public view returns (address, bool, int64) { return (art[i].artistAddress, art[i].finished, art[i].currentFeatureId); } function getNumArt () public view returns (uint) { return art.length; } function getNumArtist () public view returns (uint) { return artistAddresses.length; } function getArtist (address artistAddress) public view returns (string memory, string memory, address payable) { Artist memory a = artists[artistAddress]; address payable p = address(uint160(artistAddress)); return (a.name, a.description, p); } function getDisplayFeature (uint16 artId) public view returns (int64) { Art memory thisArt = art[artId]; int64 latestFeature = thisArt.currentFeatureId; if (latestFeature > -1) { if (thisArt.finished) { return latestFeature; } else { return features[uint(latestFeature)].lastFeatureId; } } else { return -1; } } function getFeature (uint64 featureId) public view returns (uint, uint, int64, int64, bool) { Feature memory f = features[uint(featureId)]; return (f.startTime,f.endTime,f.lastFeatureId,f.currentBidId,f.accepted); } //TODO add admin back when fixed function addArtist (address payable _addr) public { // require (adminAddress == msg.sender, "user is not admin"); bool _isAdmin = adminAddress == msg.sender; artists[_addr] = Artist("", "", true); artistAddresses.push(_addr); } function modifyArtistProfile (string memory _name, string memory _description) public { Artist storage artist = artists[msg.sender]; artist.name = _name; artist.description = _description; } //TODO add back artist modifier when fixed function startArt () public { bool isArtistA = isArtist(); bool isArtistB = artists[msg.sender].enabled; art.push(Art(msg.sender, false, -1)); } //TODO add back artist modifier when fixed function startFeature (uint64 artId, uint _endTime) public { Art storage thisArt = art[artId]; //require (thisArt.artistAddress == msg.sender, "can't start a feature for art you don't own!"); Feature memory thisFeature = Feature (now, _endTime, thisArt.currentFeatureId, -1, false); features.push(thisFeature); thisArt.currentFeatureId = int64(features.length - 1); } // starts art with an initial feature already filled in by the artist function startArtWithFeature () public { Feature memory startFeature = Feature (now, now, -1, -1, true); features.push(startFeature); int64 featureId = int64(features.length - 1); emit FeatureCreated(uint64(featureId)); art.push(Art(msg.sender, false, featureId)); emit ArtCreated(uint64(art.length - 1)); } function getBid (uint64 bidId) public view returns (int64, address payable, uint, string memory) { Bid memory b = bids[bidId]; return (b.lowerBidId, b.addr, b.amount, b.request); } // TODO make sure you can't bid on feature auctions that have ended function makeBid (uint64 artId, string memory _request) public payable returns (bool, string memory) { Art memory thisArt = art[artId]; uint actualBid = msg.value - fee; if (thisArt.currentFeatureId > -1) { Feature storage thisFeature = features[uint(thisArt.currentFeatureId)]; if (thisFeature.currentBidId > -1) { Bid memory oldBid = bids[uint(thisFeature.currentBidId)]; if (actualBid > oldBid.amount) { Bid memory newBid = Bid (thisFeature.currentBidId, msg.sender, actualBid, _request); bids.push(newBid); thisFeature.currentBidId = int64(bids.length - 1); return (true, "You're now the top bidder!"); } else { // insufficient bid return (false, "Your bid must be higher than the current maximum bid"); } } else { // very first bid Bid memory newBid = Bid (-1, msg.sender, actualBid, _request); bids.push(newBid); thisFeature.currentBidId = int64(bids.length - 1); return (true, "You've made the very first bid!"); } } else { return (false, "This art isn't open for bidding yet"); } } // TODO make function for artist to cancel bid if they hate the request // TODO make this callable only by artist who owns artwork? function endBidding (uint64 artId) public { Art memory thisArt = art[artId]; // require (thisArt.currentFeatureId > -1, "can't end bidding when there is no current feature"); Feature storage thisFeature = features[uint(thisArt.currentFeatureId)]; // require (now > thisFeature.endTime, "Can't end auction prematurely"); if (thisFeature.currentBidId > -1) { Bid memory winningBid = bids[uint(thisFeature.currentBidId)]; if (winningBid.lowerBidId > -1) { // refund losing bids Bid memory currentBid = winningBid; // assignment should be overwritten immediately for (currentBid = bids[uint(winningBid.lowerBidId)]; currentBid.lowerBidId != -1; currentBid = bids[uint(currentBid.lowerBidId)]) { currentBid.addr.transfer(currentBid.amount); } currentBid.addr.transfer(currentBid.amount); // need one last call for last bid } address payable aa = address(uint160(thisArt.artistAddress)); aa.transfer(winningBid.amount); } else { // there are no bids! } thisFeature.accepted = true; } function nextFeature (uint64 artId, uint endTime) public { endBidding(artId); startFeature(artId, endTime); } function getTestMessage() public view returns (string memory) { return testMessage; } constructor (address _admin) public { adminAddress =_admin; testMessage = "A test has passed"; } function finishArt (uint64 artId) public { endBidding(artId); Art storage thisArt = art[artId]; thisArt.finished = true; } }
TODO add back artist modifier when fixedrequire (thisArt.artistAddress == msg.sender, "can't start a feature for art you don't own!");
function startFeature (uint64 artId, uint _endTime) public { Art storage thisArt = art[artId]; Feature memory thisFeature = Feature (now, _endTime, thisArt.currentFeatureId, -1, false); features.push(thisFeature); thisArt.currentFeatureId = int64(features.length - 1); }
15,794,597
// SPDX-License-Identifier: MIT pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; import {GelatoConditionsStandard} from "../GelatoConditionsStandard.sol"; import {IERC20} from "../../external/IERC20.sol"; import {SafeMath} from "../../external/SafeMath.sol"; import {ILendingPoolCore} from "../../dapp_interfaces/aave/ILendingPoolCore.sol"; import {ILendingPoolAddressesProvider} from "../../dapp_interfaces/aave/ILendingPoolAddressesProvider.sol"; import {ICToken} from "../../dapp_interfaces/compound/ICToken.sol"; contract ConditionCompareCompoundAaveLending is GelatoConditionsStandard { using SafeMath for uint256; ILendingPoolAddressesProvider internal constant lendingPoolAddressesProvider = ILendingPoolAddressesProvider( 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8 ); /// @notice Helper to encode the Condition data field off-chain function getConditionData( ICToken _compoundToken, address _underlyingAsset, uint256 _minSpread, bool _tokenInCompound ) public pure returns (bytes memory) { return abi.encode( _compoundToken, _underlyingAsset, _minSpread, _tokenInCompound ); } /// @notice Gelato Standard Condition function. /// @dev Every Gelato Condition must have this function selector as entry point. /// @param _conditionData The encoded data from getConditionData() function ok( uint256, bytes memory _conditionData, uint256 ) public view virtual override returns (string memory) { ( ICToken _compoundToken, address _underlyingAsset, uint256 _minSpread, bool _tokenInCompound ) = abi.decode(_conditionData, (ICToken, address, uint256, bool)); return compareLendingRate( _compoundToken, _underlyingAsset, _minSpread, _tokenInCompound ); } /** * @dev Compares Compound lending rate vs Aave lending rate and returns "OK" * if one is greater than the other * @param _compoundToken cToken to get the lending rate from * @param _underlyingAsset token or / ETH to get aDAI tokens lending rate from * @param _minSpread Minimum spread both amounts have to differ to return "OK" in ray * @param _tokenInCompound true if user currently holds cTokens, false if aTokens */ function compareLendingRate( ICToken _compoundToken, address _underlyingAsset, uint256 _minSpread, bool _tokenInCompound ) public view returns (string memory) { // Compound // Returned in wad uint256 compRateRay = getCompRateInRay(_compoundToken); // Aave // Returned in ray uint256 aaveRate = getAaveInRay(_underlyingAsset); // If user currently has tokens in Compound, but Aave rate is better, refinance to aave if (_tokenInCompound && aaveRate > compRateRay.add(_minSpread)) return OK; // If user currently has tokens in Aave, but Compound rate is better, refinance to aave if (!_tokenInCompound && compRateRay > aaveRate.add(_minSpread)) return OK; if (_tokenInCompound) return "IR not higher on Aave than on Compound"; if (!_tokenInCompound) return "IR not higher on Compound than on Aave"; } /** * @dev Retrieves lending rate from cToken and converts it into ray * @param _compoundToken cToken to get the lending rate from */ function getCompRateInRay(ICToken _compoundToken) public view returns (uint256 compRateRay) { uint256 compRate = _compoundToken.supplyRatePerBlock(); // convert block based IR to annualized rate compRateRay = compRate.mul(2102400).mul(1e9); } /** * @dev Retrieves lending rate from aToken (in ray) * @param _underlyingAsset token or / ETH to get aDAI tokens lending rate from */ function getAaveInRay(address _underlyingAsset) public view returns (uint256 aaveRate) { // Aave address lendingPool = lendingPoolAddressesProvider.getLendingPoolCore(); // Returned in ray aaveRate = ILendingPoolCore(lendingPool).getReserveCurrentLiquidityRate( _underlyingAsset ); } }
Compares Compound lending rate vs Aave lending rate and returns "OK" if one is greater than the other _compoundToken cToken to get the lending rate from _underlyingAsset token or / ETH to get aDAI tokens lending rate from _minSpread Minimum spread both amounts have to differ to return "OK" in ray _tokenInCompound true if user currently holds cTokens, false if aTokens/ Compound Returned in wad Aave Returned in ray If user currently has tokens in Compound, but Aave rate is better, refinance to aave If user currently has tokens in Aave, but Compound rate is better, refinance to aave
function compareLendingRate( ICToken _compoundToken, address _underlyingAsset, uint256 _minSpread, bool _tokenInCompound ) public view returns (string memory) { uint256 compRateRay = getCompRateInRay(_compoundToken); uint256 aaveRate = getAaveInRay(_underlyingAsset); if (_tokenInCompound && aaveRate > compRateRay.add(_minSpread)) return OK; if (!_tokenInCompound && compRateRay > aaveRate.add(_minSpread)) return OK; if (_tokenInCompound) return "IR not higher on Aave than on Compound"; if (!_tokenInCompound) return "IR not higher on Compound than on Aave"; }
13,046,848
./full_match/11155111/0xb0e9daBA710617b2C398b3987716B2F1f36bB228/sources/AllTypes.sol
Store & retrieve a uint8 val Value to return/
function getUint8(uint8 val) public pure returns (uint8) { return val; }
3,818,908
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributorV3.sol"; import "./interface/IPriceOracle.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; import "./Controller.sol"; /** * @title dForce's lending reward distributor Contract * @author dForce */ contract RewardDistributorV3 is Initializable, Ownable, IRewardDistributorV3 { using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice the controller Controller public controller; /// @notice the global Reward distribution speed uint256 public globalDistributionSpeed; /// @notice the Reward distribution speed of each iToken mapping(address => uint256) public distributionSpeed; /// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa mapping(address => uint256) public distributionFactorMantissa; struct DistributionState { // Token's last updated index, stored as a mantissa uint256 index; // The block number the index was last updated at uint256 block; } /// @notice the Reward distribution supply state of each iToken mapping(address => DistributionState) public distributionSupplyState; /// @notice the Reward distribution borrow state of each iToken mapping(address => DistributionState) public distributionBorrowState; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionSupplierIndex; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionBorrowerIndex; /// @notice the Reward distributed into each account mapping(address => uint256) public reward; /// @notice the Reward token address address public rewardToken; /// @notice whether the reward distribution is paused bool public paused; /// @notice the Reward distribution speed supply side of each iToken mapping(address => uint256) public distributionSupplySpeed; /// @notice the global Reward distribution speed for supply uint256 public globalDistributionSupplySpeed; /** * @dev Throws if called by any account other than the controller. */ modifier onlyController() { require( address(controller) == msg.sender, "onlyController: caller is not the controller" ); _; } /** * @notice Initializes the contract. */ function initialize(Controller _controller) external initializer { require( address(_controller) != address(0), "initialize: controller address should not be zero address!" ); __Ownable_init(); controller = _controller; paused = true; } /** * @notice set reward token address * @dev Admin function, only owner can call this * @param _newRewardToken the address of reward token */ function _setRewardToken(address _newRewardToken) external override onlyOwner { address _oldRewardToken = rewardToken; require( _newRewardToken != address(0) && _newRewardToken != _oldRewardToken, "Reward token address invalid" ); rewardToken = _newRewardToken; emit NewRewardToken(_oldRewardToken, _newRewardToken); } /** * @notice Add the iToken as receipient * @dev Admin function, only controller can call this * @param _iToken the iToken to add as recipient * @param _distributionFactor the distribution factor of the recipient */ function _addRecipient(address _iToken, uint256 _distributionFactor) external override onlyController { distributionFactorMantissa[_iToken] = _distributionFactor; distributionSupplyState[_iToken] = DistributionState({ index: 0, block: block.number }); distributionBorrowState[_iToken] = DistributionState({ index: 0, block: block.number }); emit NewRecipient(_iToken, _distributionFactor); } /** * @notice Pause the reward distribution * @dev Admin function, pause will set global speed to 0 to stop the accumulation */ function _pause() external override onlyOwner { // Set the global distribution speed to 0 to stop accumulation address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], 0); _setDistributionSupplySpeed(_iTokens[i], 0); } _refreshGlobalDistributionSpeeds(); _setPaused(true); } /** * @notice Unpause and set distribution speeds * @dev Admin function * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external override onlyOwner { _setPaused(false); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } /** * @notice Pause/Unpause the reward distribution * @dev Admin function * @param _paused whether to pause/unpause the distribution */ function _setPaused(bool _paused) internal { paused = _paused; emit Paused(_paused); } /** * @notice Set distribution speeds * @dev Admin function, will fail when paused * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSpeeds( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change speeds when paused"); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } function _setDistributionSpeedsInternal( address[] memory _borrowiTokens, uint256[] memory _borrowSpeeds, address[] memory _supplyiTokens, uint256[] memory _supplySpeeds ) internal { _setDistributionBorrowSpeedsInternal(_borrowiTokens, _borrowSpeeds); _setDistributionSupplySpeedsInternal(_supplyiTokens, _supplySpeeds); } /** * @notice Set borrow distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The borrow asset array * @param _borrowSpeeds The borrow speed array */ function _setDistributionBorrowSpeeds( address[] calldata _iTokens, uint256[] calldata _borrowSpeeds ) external onlyOwner { require(!paused, "Can not change borrow speeds when paused"); _setDistributionBorrowSpeedsInternal(_iTokens, _borrowSpeeds); _refreshGlobalDistributionSpeeds(); } /** * @notice Set supply distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSupplySpeeds( address[] calldata _iTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change supply speeds when paused"); _setDistributionSupplySpeedsInternal(_iTokens, _supplySpeeds); _refreshGlobalDistributionSpeeds(); } function _refreshGlobalDistributionSpeeds() internal { address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; uint256 _borrowSpeed; uint256 _supplySpeed; for (uint256 i = 0; i < _len; i++) { _borrowSpeed = _borrowSpeed.add(distributionSpeed[_iTokens[i]]); _supplySpeed = _supplySpeed.add( distributionSupplySpeed[_iTokens[i]] ); } globalDistributionSpeed = _borrowSpeed; globalDistributionSupplySpeed = _supplySpeed; emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed); } function _setDistributionBorrowSpeedsInternal( address[] memory _iTokens, uint256[] memory _borrowSpeeds ) internal { require( _iTokens.length == _borrowSpeeds.length, "Length of _iTokens and _borrowSpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], _borrowSpeeds[i]); } } function _setDistributionSupplySpeedsInternal( address[] memory _iTokens, uint256[] memory _supplySpeeds ) internal { require( _iTokens.length == _supplySpeeds.length, "Length of _iTokens and _supplySpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionSupplySpeed(_iTokens[i], _supplySpeeds[i]); } } function _setDistributionBorrowSpeed(address _iToken, uint256 _borrowSpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update borrow state before updating new speed _updateDistributionState(_iToken, true); distributionSpeed[_iToken] = _borrowSpeed; emit DistributionBorrowSpeedUpdated(_iToken, _borrowSpeed); } function _setDistributionSupplySpeed(address _iToken, uint256 _supplySpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update supply state before updating new speed _updateDistributionState(_iToken, false); distributionSupplySpeed[_iToken] = _supplySpeed; emit DistributionSupplySpeedUpdated(_iToken, _supplySpeed); } /** * @notice Update the iToken's Reward distribution state * @dev Will be called every time when the iToken's supply/borrow changes * @param _iToken The iToken to be updated * @param _isBorrow whether to update the borrow state */ function updateDistributionState(address _iToken, bool _isBorrow) external override { // Skip all updates if it is paused if (paused) { return; } _updateDistributionState(_iToken, _isBorrow); } function _updateDistributionState(address _iToken, bool _isBorrow) internal { require(controller.hasiToken(_iToken), "Token has not been listed"); DistributionState storage state = _isBorrow ? distributionBorrowState[_iToken] : distributionSupplyState[_iToken]; uint256 _speed = _isBorrow ? distributionSpeed[_iToken] : distributionSupplySpeed[_iToken]; uint256 _blockNumber = block.number; uint256 _deltaBlocks = _blockNumber.sub(state.block); if (_deltaBlocks > 0 && _speed > 0) { uint256 _totalToken = _isBorrow ? IiToken(_iToken).totalBorrows().rdiv( IiToken(_iToken).borrowIndex() ) : IERC20Upgradeable(_iToken).totalSupply(); uint256 _totalDistributed = _speed.mul(_deltaBlocks); // Reward distributed per token since last time uint256 _distributedPerToken = _totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0; state.index = state.index.add(_distributedPerToken); } state.block = _blockNumber; } /** * @notice Update the account's Reward distribution state * @dev Will be called every time when the account's supply/borrow changes * @param _iToken The iToken to be updated * @param _account The account to be updated * @param _isBorrow whether to update the borrow state */ function updateReward( address _iToken, address _account, bool _isBorrow ) external override { _updateReward(_iToken, _account, _isBorrow); } function _updateReward( address _iToken, address _account, bool _isBorrow ) internal { require(_account != address(0), "Invalid account address!"); require(controller.hasiToken(_iToken), "Token has not been listed"); uint256 _iTokenIndex; uint256 _accountIndex; uint256 _accountBalance; if (_isBorrow) { _iTokenIndex = distributionBorrowState[_iToken].index; _accountIndex = distributionBorrowerIndex[_iToken][_account]; _accountBalance = IiToken(_iToken) .borrowBalanceStored(_account) .rdiv(IiToken(_iToken).borrowIndex()); // Update the account state to date distributionBorrowerIndex[_iToken][_account] = _iTokenIndex; } else { _iTokenIndex = distributionSupplyState[_iToken].index; _accountIndex = distributionSupplierIndex[_iToken][_account]; _accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account); // Update the account state to date distributionSupplierIndex[_iToken][_account] = _iTokenIndex; } uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex); uint256 _amount = _accountBalance.rmul(_deltaIndex); if (_amount > 0) { reward[_account] = reward[_account].add(_amount); emit RewardDistributed(_iToken, _account, _amount, _accountIndex); } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update */ function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) public override { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, false); _updateDistributionState(_iToken, true); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], false); _updateReward(_iToken, _holders[j], true); } } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update * @param _isBorrow whether to update the borrow state */ function _updateRewards( address[] memory _holders, address[] memory _iTokens, bool _isBorrow ) internal { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, _isBorrow); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], _isBorrow); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _iTokens The _iTokens to claim from */ function claimReward(address[] memory _holders, address[] memory _iTokens) public override { updateRewardBatch(_holders, _iTokens); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _suppliediTokens The _suppliediTokens to claim from * @param _borrowediTokens The _borrowediTokens to claim from */ function claimRewards( address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens ) external override { _updateRewards(_holders, _suppliediTokens, false); _updateRewards(_holders, _borrowediTokens, true); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in all iTokens by the holders * @param _holders The account to claim for */ function claimAllReward(address[] memory _holders) external override { claimReward(_holders, controller.getAlliTokens()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.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 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"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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.6.12; import "./IInterestRateModelInterface.sol"; import "./IControllerInterface.sol"; interface IiToken { function isSupported() external returns (bool); function isiToken() external returns (bool); //---------------------------------- //********* User Interface ********* //---------------------------------- function mint(address recipient, uint256 mintAmount) external; function mintAndEnterMarket(address recipient, uint256 mintAmount) external; function redeem(address from, uint256 redeemTokens) external; function redeemUnderlying(address from, uint256 redeemAmount) external; function borrow(uint256 borrowAmount) external; function repayBorrow(uint256 repayAmount) external; function repayBorrowBehalf(address borrower, uint256 repayAmount) external; function liquidateBorrow( address borrower, uint256 repayAmount, address iTokenCollateral ) external; function flashloan( address recipient, uint256 loanAmount, bytes memory data ) external; function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external; function updateInterest() external returns (bool); function controller() external view returns (address); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function totalBorrows() external view returns (uint256); function borrowBalanceCurrent(address _user) external returns (uint256); function borrowBalanceStored(address _user) external view returns (uint256); function borrowIndex() external view returns (uint256); function getAccountSnapshot(address _account) external view returns ( uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function getCash() external view returns (uint256); //---------------------------------- //********* Owner Actions ********** //---------------------------------- function _setNewReserveRatio(uint256 _newReserveRatio) external; function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external; function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external; function _setController(IControllerInterface _newController) external; function _setInterestRateModel( IInterestRateModelInterface _newInterestRateModel ) external; function _withdrawReserves(uint256 _withdrawAmount) external; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRewardDistributorV3 { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); /// @notice Emitted when iToken's Distribution borrow speed is updated event DistributionBorrowSpeedUpdated(address iToken, uint256 borrowSpeed); /// @notice Emitted when iToken's Distribution supply speed is updated event DistributionSupplySpeedUpdated(address iToken, uint256 supplySpeed); /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; function claimRewards(address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IiToken.sol"; interface IPriceOracle { /** * @notice Get the underlying price of a iToken asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(address _iToken) external view returns (uint256); /** * @notice Get the price of a underlying asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable and whether the price is valid. */ function getUnderlyingPriceAndStatus(address _iToken) external view returns (uint256, bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( !_initialized, "Initializable: contract is already initialized" ); _; _initialized = true; } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 {_setPendingOwner} and {_acceptOwner}. */ contract Ownable { /** * @dev Returns the address of the current owner. */ address payable public owner; /** * @dev Returns the address of the current pending owner. */ address payable public pendingOwner; event NewOwner(address indexed previousOwner, address indexed newOwner); event NewPendingOwner( address indexed oldPendingOwner, address indexed newPendingOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender, "onlyOwner: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal { owner = msg.sender; emit NewOwner(address(0), msg.sender); } /** * @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason. * @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer. * @param newPendingOwner New pending owner. */ function _setPendingOwner(address payable newPendingOwner) external onlyOwner { require( newPendingOwner != address(0) && newPendingOwner != pendingOwner, "_setPendingOwner: New owenr can not be zero address and owner has been set!" ); // Gets current owner. address oldPendingOwner = pendingOwner; // Sets new pending owner. pendingOwner = newPendingOwner; emit NewPendingOwner(oldPendingOwner, newPendingOwner); } /** * @dev Accepts the admin rights, but only for pendingOwenr. */ function _acceptOwner() external { require( msg.sender == pendingOwner, "_acceptOwner: Only for pending owner!" ); // Gets current values for events. address oldOwner = owner; address oldPendingOwner = pendingOwner; // Set the new contract owner. owner = pendingOwner; // Clear the pendingOwner. pendingOwner = address(0); emit NewOwner(oldOwner, owner); emit NewPendingOwner(oldPendingOwner, pendingOwner); } uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; library SafeRatioMath { using SafeMathUpgradeable for uint256; uint256 private constant BASE = 10**18; uint256 private constant DOUBLE = 10**36; function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.add(y.sub(1)).div(y); } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).div(BASE); } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).div(y); } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).add(y.sub(1)).div(y); } function tmul( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256 result) { result = x.mul(y).mul(z).div(DOUBLE); } 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 rounding. 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) } } } } } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "./interface/IControllerInterface.sol"; import "./interface/IPriceOracle.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributor.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; /** * @title dForce's lending controller Contract * @author dForce */ contract Controller is Initializable, Ownable, IControllerInterface { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @dev EnumerableSet of all iTokens EnumerableSetUpgradeable.AddressSet internal iTokens; struct Market { /* * 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 in [0, 0.9], and stored as a mantissa. */ uint256 collateralFactorMantissa; /* * Multiplier representing the most one can borrow the asset. * For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor. * When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value * Must be between (0, 1], and stored as a mantissa. */ uint256 borrowFactorMantissa; /* * The borrow capacity of the asset, will be checked in beforeBorrow() * -1 means there is no limit on the capacity * 0 means the asset can not be borrowed any more */ uint256 borrowCapacity; /* * The supply capacity of the asset, will be checked in beforeMint() * -1 means there is no limit on the capacity * 0 means the asset can not be supplied any more */ uint256 supplyCapacity; // Whether market's mint is paused bool mintPaused; // Whether market's redeem is paused bool redeemPaused; // Whether market's borrow is paused bool borrowPaused; } /// @notice Mapping of iTokens to corresponding markets mapping(address => Market) public markets; struct AccountData { // Account's collateral assets EnumerableSetUpgradeable.AddressSet collaterals; // Account's borrowed assets EnumerableSetUpgradeable.AddressSet borrowed; } /// @dev Mapping of accounts' data, including collateral and borrowed assets mapping(address => AccountData) internal accountsData; /** * @notice Oracle to query the price of a given asset */ address public priceOracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; // closeFactorMantissa must be strictly greater than this value uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; // liquidationIncentiveMantissa must be no less than this value uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 // collateralFactorMantissa must not exceed this value uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0 // borrowFactorMantissa must not exceed this value uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0 /** * @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency */ address public pauseGuardian; /// @notice whether global transfer is paused bool public transferPaused; /// @notice whether global seize is paused bool public seizePaused; /** * @notice the address of reward distributor */ address public rewardDistributor; /** * @dev Check if called by owner or pauseGuardian, and only owner can unpause */ modifier checkPauser(bool _paused) { require( msg.sender == owner || (msg.sender == pauseGuardian && _paused), "Only owner and guardian can pause and only owner can unpause" ); _; } /** * @notice Initializes the contract. */ function initialize() external initializer { __Ownable_init(); } /*********************************/ /******** Security Check *********/ /*********************************/ /** * @notice Ensure this is a Controller contract. */ function isController() external view override returns (bool) { return true; } /*********************************/ /******** Admin Operations *******/ /*********************************/ /** * @notice Admin function to add iToken into supported markets * Checks if the iToken already exsits * Will `revert()` if any check fails * @param _iToken The _iToken to add * @param _collateralFactor The _collateralFactor of _iToken * @param _borrowFactor The _borrowFactor of _iToken * @param _supplyCapacity The _supplyCapacity of _iToken * @param _distributionFactor The _distributionFactor of _iToken */ function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external override onlyOwner { require(IiToken(_iToken).isSupported(), "Token is not supported"); // Market must not have been listed, EnumerableSet.add() will return false if it exsits require(iTokens.add(_iToken), "Token has already been listed"); require( _collateralFactor <= collateralFactorMaxMantissa, "Collateral factor invalid" ); require( _borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Underlying price is unavailable" ); markets[_iToken] = Market({ collateralFactorMantissa: _collateralFactor, borrowFactorMantissa: _borrowFactor, borrowCapacity: _borrowCapacity, supplyCapacity: _supplyCapacity, mintPaused: false, redeemPaused: false, borrowPaused: false }); IRewardDistributor(rewardDistributor)._addRecipient( _iToken, _distributionFactor ); emit MarketAdded( _iToken, _collateralFactor, _borrowFactor, _supplyCapacity, _borrowCapacity, _distributionFactor ); } /** * @notice Sets price oracle * @dev Admin function to set price oracle * @param _newOracle New oracle contract */ function _setPriceOracle(address _newOracle) external override onlyOwner { address _oldOracle = priceOracle; require( _newOracle != address(0) && _newOracle != _oldOracle, "Oracle address invalid" ); priceOracle = _newOracle; emit NewPriceOracle(_oldOracle, _newOracle); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param _newCloseFactorMantissa New close factor, scaled by 1e18 */ function _setCloseFactor(uint256 _newCloseFactorMantissa) external override onlyOwner { require( _newCloseFactorMantissa >= closeFactorMinMantissa && _newCloseFactorMantissa <= closeFactorMaxMantissa, "Close factor invalid" ); uint256 _oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = _newCloseFactorMantissa; emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 */ function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa) external override onlyOwner { require( _newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa && _newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, "Liquidation incentive invalid" ); uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa; emit NewLiquidationIncentive( _oldLiquidationIncentiveMantissa, _newLiquidationIncentiveMantissa ); } /** * @notice Sets the collateralFactor for a iToken * @dev Admin function to set collateralFactor for a iToken * @param _iToken The token to set the factor on * @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18 */ function _setCollateralFactor( address _iToken, uint256 _newCollateralFactorMantissa ) external override onlyOwner { _checkiTokenListed(_iToken); require( _newCollateralFactorMantissa <= collateralFactorMaxMantissa, "Collateral factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set collateral factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa; _market.collateralFactorMantissa = _newCollateralFactorMantissa; emit NewCollateralFactor( _iToken, _oldCollateralFactorMantissa, _newCollateralFactorMantissa ); } /** * @notice Sets the borrowFactor for a iToken * @dev Admin function to set borrowFactor for a iToken * @param _iToken The token to set the factor on * @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18 */ function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa) external override onlyOwner { _checkiTokenListed(_iToken); require( _newBorrowFactorMantissa > 0 && _newBorrowFactorMantissa <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set borrow factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa; _market.borrowFactorMantissa = _newBorrowFactorMantissa; emit NewBorrowFactor( _iToken, _oldBorrowFactorMantissa, _newBorrowFactorMantissa ); } /** * @notice Sets the borrowCapacity for a iToken * @dev Admin function to set borrowCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newBorrowCapacity The new borrow capacity */ function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldBorrowCapacity = _market.borrowCapacity; _market.borrowCapacity = _newBorrowCapacity; emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity); } /** * @notice Sets the supplyCapacity for a iToken * @dev Admin function to set supplyCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newSupplyCapacity The new supply capacity */ function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldSupplyCapacity = _market.supplyCapacity; _market.supplyCapacity = _newSupplyCapacity; emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity); } /** * @notice Sets the pauseGuardian * @dev Admin function to set pauseGuardian * @param _newPauseGuardian The new pause guardian */ function _setPauseGuardian(address _newPauseGuardian) external override onlyOwner { address _oldPauseGuardian = pauseGuardian; require( _newPauseGuardian != address(0) && _newPauseGuardian != _oldPauseGuardian, "Pause guardian address invalid" ); pauseGuardian = _newPauseGuardian; emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian); } /** * @notice pause/unpause mint() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllMintPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setMintPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause mint() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setMintPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setMintPausedInternal(_iToken, _paused); } function _setMintPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].mintPaused = _paused; emit MintPaused(_iToken, _paused); } /** * @notice pause/unpause redeem() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllRedeemPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setRedeemPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause redeem() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setRedeemPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setRedeemPausedInternal(_iToken, _paused); } function _setRedeemPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); } /** * @notice pause/unpause borrow() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllBorrowPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setBorrowPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause borrow() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setBorrowPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setBorrowPausedInternal(_iToken, _paused); } function _setBorrowPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause global transfer() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setTransferPaused(bool _paused) external override checkPauser(_paused) { _setTransferPausedInternal(_paused); } function _setTransferPausedInternal(bool _paused) internal { transferPaused = _paused; emit TransferPaused(_paused); } /** * @notice pause/unpause global seize() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setSeizePaused(bool _paused) external override checkPauser(_paused) { _setSeizePausedInternal(_paused); } function _setSeizePausedInternal(bool _paused) internal { seizePaused = _paused; emit SeizePaused(_paused); } /** * @notice pause/unpause all actions iToken, including mint/redeem/borrow * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setiTokenPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setiTokenPausedInternal(_iToken, _paused); } function _setiTokenPausedInternal(address _iToken, bool _paused) internal { Market storage _market = markets[_iToken]; _market.mintPaused = _paused; emit MintPaused(_iToken, _paused); _market.redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); _market.borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setProtocolPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { address _iToken = _iTokens.at(i); _setiTokenPausedInternal(_iToken, _paused); } _setTransferPausedInternal(_paused); _setSeizePausedInternal(_paused); } /** * @notice Sets Reward Distributor * @dev Admin function to set reward distributor * @param _newRewardDistributor new reward distributor */ function _setRewardDistributor(address _newRewardDistributor) external override onlyOwner { address _oldRewardDistributor = rewardDistributor; require( _newRewardDistributor != address(0) && _newRewardDistributor != _oldRewardDistributor, "Reward Distributor address invalid" ); rewardDistributor = _newRewardDistributor; emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor); } /*********************************/ /******** Poclicy Hooks **********/ /*********************************/ /** * @notice Hook function before iToken `mint()` * Checks if the account should be allowed to mint the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the mint against * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken */ function beforeMint( address _iToken, address _minter, uint256 _mintAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.mintPaused, "Token mint has been paused"); // Check the iToken's supply capacity, -1 means no limit uint256 _totalSupplyUnderlying = IERC20Upgradeable(_iToken).totalSupply().rmul( IiToken(_iToken).exchangeRateStored() ); require( _totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity, "Token supply capacity reached" ); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _minter, false ); } /** * @notice Hook function after iToken `mint()` * Will `revert()` if any operation fails * @param _iToken The iToken being minted * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken * @param _mintedAmount The amount of iToken being minted */ function afterMint( address _iToken, address _minter, uint256 _mintAmount, uint256 _mintedAmount ) external override { _iToken; _minter; _mintAmount; _mintedAmount; } /** * @notice Hook function before iToken `redeem()` * Checks if the account should be allowed to redeem the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the redeem against * @param _redeemer The account which would redeem iToken * @param _redeemAmount The amount of iToken to redeem */ function beforeRedeem( address _iToken, address _redeemer, uint256 _redeemAmount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!markets[_iToken].redeemPaused, "Token redeem has been paused"); _redeemAllowed(_iToken, _redeemer, _redeemAmount); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _redeemer, false ); } /** * @notice Hook function after iToken `redeem()` * Will `revert()` if any operation fails * @param _iToken The iToken being redeemed * @param _redeemer The account which redeemed iToken * @param _redeemAmount The amount of iToken being redeemed * @param _redeemedUnderlying The amount of underlying being redeemed */ function afterRedeem( address _iToken, address _redeemer, uint256 _redeemAmount, uint256 _redeemedUnderlying ) external override { _iToken; _redeemer; _redeemAmount; _redeemedUnderlying; } /** * @notice Hook function before iToken `borrow()` * Checks if the account should be allowed to borrow the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the borrow against * @param _borrower The account which would borrow iToken * @param _borrowAmount The amount of underlying to borrow */ function beforeBorrow( address _iToken, address _borrower, uint256 _borrowAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.borrowPaused, "Token borrow has been paused"); if (!hasBorrowed(_borrower, _iToken)) { // Unlike collaterals, borrowed asset can only be added by iToken, // rather than enabled by user directly. require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just add it _addToBorrowed(_borrower, _iToken); } // Check borrower's equity (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount); require(_shortfall == 0, "Account has some shortfall"); // Check the iToken's borrow capacity, -1 means no limit uint256 _totalBorrows = IiToken(_iToken).totalBorrows(); require( _totalBorrows.add(_borrowAmount) <= _market.borrowCapacity, "Token borrow capacity reached" ); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); } /** * @notice Hook function after iToken `borrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being borrewd * @param _borrower The account which borrowed iToken * @param _borrowedAmount The amount of underlying being borrowed */ function afterBorrow( address _iToken, address _borrower, uint256 _borrowedAmount ) external override { _iToken; _borrower; _borrowedAmount; } /** * @notice Hook function before iToken `repayBorrow()` * Checks if the account should be allowed to repay the given iToken * for the borrower. Will `revert()` if any check fails * @param _iToken The iToken to verify the repay against * @param _payer The account which would repay iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); _payer; _repayAmount; } /** * @notice Hook function after iToken `repayBorrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being repaid * @param _payer The account which would repay * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying being repaied */ function afterRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Remove _iToken from borrowed list if new borrow balance is 0 if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) { // Only allow called by iToken as we are going to remove this token from borrower's borrowed list require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just remove it _removeFromBorrowed(_borrower, _iToken); } _payer; _repayAmount; } /** * @notice Hook function before iToken `liquidateBorrow()` * Checks if the account should be allowed to liquidate the given iToken * for the borrower. Will `revert()` if any check fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be liqudate with * @param _liquidator The account which would repay the borrowed iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repayAmount ) external override { // Tokens must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); (, uint256 _shortfall, , ) = calcAccountEquity(_borrower); require(_shortfall > 0, "Account does not have shortfall"); // Only allowed to repay the borrow balance's close factor uint256 _borrowBalance = IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower); uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa); require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed"); _liquidator; } /** * @notice Hook function after iToken `liquidateBorrow()` * Will `revert()` if any operation fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _liquidator The account which would repay and seize * @param _borrower The account which has borrowed * @param _repaidAmount The amount of underlying being repaied * @param _seizedAmount The amount of collateral being seized */ function afterLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repaidAmount, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _repaidAmount; _seizedAmount; // Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance // No need to check whether should remove from borrowed asset list } /** * @notice Hook function before iToken `seize()` * Checks if the liquidator should be allowed to seize the collateral iToken * Will `revert()` if any check fails * @param _iTokenCollateral The collateral iToken to be seize * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid the borrowed iToken * @param _borrower The account which has borrowed * @param _seizeAmount The amount of collateral iToken to seize */ function beforeSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizeAmount ) external override { require(!seizePaused, "Seize has been paused"); // Markets must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); // Sanity Check the controllers require( IiToken(_iTokenBorrowed).controller() == IiToken(_iTokenCollateral).controller(), "Controller mismatch between Borrowed and Collateral" ); // Update the Reward Distribution Supply state on collateral IRewardDistributor(rewardDistributor).updateDistributionState( _iTokenCollateral, false ); // Update reward of liquidator and borrower on collateral IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _liquidator, false ); IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _borrower, false ); _seizeAmount; } /** * @notice Hook function after iToken `seize()` * Will `revert()` if any operation fails * @param _iTokenCollateral The collateral iToken to be seized * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid and seized * @param _borrower The account which has borrowed * @param _seizedAmount The amount of collateral being seized */ function afterSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _seizedAmount; } /** * @notice Hook function before iToken `transfer()` * Checks if the transfer should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be transfered * @param _from The account to be transfered from * @param _to The account to be transfered to * @param _amount The amount to be transfered */ function beforeTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!transferPaused, "Transfer has been paused"); // Check account equity with this amount to decide whether the transfer is allowed _redeemAllowed(_iToken, _from, _amount); // Update the Reward Distribution supply state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); // Update reward of from and to IRewardDistributor(rewardDistributor).updateReward( _iToken, _from, false ); IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false); } /** * @notice Hook function after iToken `transfer()` * Will `revert()` if any operation fails * @param _iToken The iToken was transfered * @param _from The account was transfer from * @param _to The account was transfer to * @param _amount The amount was transfered */ function afterTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { _iToken; _from; _to; _amount; } /** * @notice Hook function before iToken `flashloan()` * Checks if the flashloan should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be flashloaned * @param _to The account flashloaned transfer to * @param _amount The amount to be flashloaned */ function beforeFlashloan( address _iToken, address _to, uint256 _amount ) external override { // Flashloan share the same pause state with borrow require(!markets[_iToken].borrowPaused, "Token borrow has been paused"); _checkiTokenListed(_iToken); _to; _amount; // Update the Reward Distribution Borrow state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); } /** * @notice Hook function after iToken `flashloan()` * Will `revert()` if any operation fails * @param _iToken The iToken was flashloaned * @param _to The account flashloan transfer to * @param _amount The amount was flashloaned */ function afterFlashloan( address _iToken, address _to, uint256 _amount ) external override { _iToken; _to; _amount; } /*********************************/ /***** Internal Functions *******/ /*********************************/ function _redeemAllowed( address _iToken, address _redeemer, uint256 _amount ) private view { _checkiTokenListed(_iToken); // No need to check liquidity if _redeemer has not used _iToken as collateral if (!accountsData[_redeemer].collaterals.contains(_iToken)) { return; } (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0); require(_shortfall == 0, "Account has some shortfall"); } /** * @dev Check if _iToken is listed */ function _checkiTokenListed(address _iToken) private view { require(iTokens.contains(_iToken), "Token has not been listed"); } /*********************************/ /** Account equity calculation ***/ /*********************************/ /** * @notice Calculates current account equity * @param _account The account to query equity of * @return account equity, shortfall, collateral value, borrowed value. */ function calcAccountEquity(address _account) public view override returns ( uint256, uint256, uint256, uint256 ) { return calcAccountEquityWithEffect(_account, address(0), 0, 0); } /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `iTokenBalance` is the number of iTokens the account owns in the collateral, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountEquityLocalVars { uint256 sumCollateral; uint256 sumBorrowed; uint256 iTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 underlyingPrice; uint256 collateralValue; uint256 borrowValue; } /** * @notice Calculates current account equity plus some token and amount to effect * @param _account The account to query equity of * @param _tokenToEffect The token address to add some additional redeeem/borrow * @param _redeemAmount The additional amount to redeem * @param _borrowAmount The additional amount to borrow * @return account euqity, shortfall, collateral value, borrowed value plus the effect. */ function calcAccountEquityWithEffect( address _account, address _tokenToEffect, uint256 _redeemAmount, uint256 _borrowAmount ) internal view virtual returns ( uint256, uint256, uint256, uint256 ) { AccountEquityLocalVars memory _local; AccountData storage _accountData = accountsData[_account]; // Calculate value of all collaterals // collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor // collateralValue = balance * collateralValuePerToken // sumCollateral += collateralValue uint256 _len = _accountData.collaterals.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.collaterals.at(i)); _local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf( _account ); _local.exchangeRateMantissa = _token.exchangeRateStored(); if (_tokenToEffect == address(_token) && _redeemAmount > 0) { _local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); _local.collateralValue = _local .iTokenBalance .mul(_local.underlyingPrice) .rmul(_local.exchangeRateMantissa) .rmul(markets[address(_token)].collateralFactorMantissa); _local.sumCollateral = _local.sumCollateral.add( _local.collateralValue ); } // Calculate all borrowed value // borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor // sumBorrowed += borrowValue _len = _accountData.borrowed.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.borrowed.at(i)); _local.borrowBalance = _token.borrowBalanceStored(_account); if (_tokenToEffect == address(_token) && _borrowAmount > 0) { _local.borrowBalance = _local.borrowBalance.add(_borrowAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); // borrowFactorMantissa can not be set to 0 _local.borrowValue = _local .borrowBalance .mul(_local.underlyingPrice) .rdiv(markets[address(_token)].borrowFactorMantissa); _local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue); } // Should never underflow return _local.sumCollateral > _local.sumBorrowed ? ( _local.sumCollateral - _local.sumBorrowed, uint256(0), _local.sumCollateral, _local.sumBorrowed ) : ( uint256(0), _local.sumBorrowed - _local.sumCollateral, _local.sumCollateral, _local.sumBorrowed ); } /** * @notice Calculate amount of collateral iToken to seize after repaying an underlying amount * @dev Used in liquidation * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _actualRepayAmount The amount of underlying token liquidator has repaied * @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized */ function liquidateCalculateSeizeTokens( address _iTokenBorrowed, address _iTokenCollateral, uint256 _actualRepayAmount ) external view virtual override returns (uint256 _seizedTokenCollateral) { /* Read oracle prices for borrowed and collateral assets */ uint256 _priceBorrowed = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed); uint256 _priceCollateral = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral); require( _priceBorrowed != 0 && _priceCollateral != 0, "Borrowed or Collateral asset price is invalid" ); uint256 _valueRepayPlusIncentive = _actualRepayAmount.mul(_priceBorrowed).rmul( liquidationIncentiveMantissa ); // Use stored value here as it is view function uint256 _exchangeRateMantissa = IiToken(_iTokenCollateral).exchangeRateStored(); // seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral // valuePerTokenCollateral = exchangeRateMantissa * priceCollateral _seizedTokenCollateral = _valueRepayPlusIncentive .rdiv(_exchangeRateMantissa) .div(_priceCollateral); } /*********************************/ /*** Account Markets Operation ***/ /*********************************/ /** * @notice Returns the markets list the account has entered * @param _account The address of the account to query * @return _accountCollaterals The markets list the account has entered */ function getEnteredMarkets(address _account) external view override returns (address[] memory _accountCollaterals) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.collaterals.length(); _accountCollaterals = new address[](_len); for (uint256 i = 0; i < _len; i++) { _accountCollaterals[i] = _accountData.collaterals.at(i); } } /** * @notice Add markets to `msg.sender`'s markets list for liquidity calculations * @param _iTokens The list of addresses of the iToken markets to be entered * @return _results Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _enterMarket(_iTokens[i], msg.sender); } } /** * @notice Only expect to be called by iToken contract. * @dev Add the market to the account's markets list for liquidity calculations * @param _account The address of the account to modify */ function enterMarketFromiToken(address _account) external override { require( _enterMarket(msg.sender, _account), "enterMarketFromiToken: Only can be called by a supported iToken!" ); } /** * @notice Add the market to the account's markets list for liquidity calculations * @param _iToken The market to enter * @param _account The address of the account to modify * @return True if entered successfully, false for non-listed market or other errors */ function _enterMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return false; } // add() will return false if iToken is in account's market list if (accountsData[_account].collaterals.add(_iToken)) { emit MarketEntered(_iToken, _account); } return true; } /** * @notice Returns whether the given account has entered the market * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has entered the market, otherwise false. */ function hasEnteredMarket(address _account, address _iToken) external view override returns (bool) { return accountsData[_account].collaterals.contains(_iToken); } /** * @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations * @param _iTokens The list of addresses of the iToken to exit * @return _results Success indicators for whether each corresponding market was exited */ function exitMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _exitMarket(_iTokens[i], msg.sender); } } /** * @notice Remove the market to the account's markets list for liquidity calculations * @param _iToken The market to exit * @param _account The address of the account to modify * @return True if exit successfully, false for non-listed market or other errors */ function _exitMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return true; } // Account has not entered this market, skip it if (!accountsData[_account].collaterals.contains(_iToken)) { return true; } // Get the iToken balance uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account); // Check account's equity if all balance are redeemed // which means iToken can be removed from collaterals _redeemAllowed(_iToken, _account, _balance); // Have checked account has entered market before accountsData[_account].collaterals.remove(_iToken); emit MarketExited(_iToken, _account); return true; } /** * @notice Returns the asset list the account has borrowed * @param _account The address of the account to query * @return _borrowedAssets The asset list the account has borrowed */ function getBorrowedAssets(address _account) external view override returns (address[] memory _borrowedAssets) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.borrowed.length(); _borrowedAssets = new address[](_len); for (uint256 i = 0; i < _len; i++) { _borrowedAssets[i] = _accountData.borrowed.at(i); } } /** * @notice Add the market to the account's borrowed list for equity calculations * @param _iToken The iToken of underlying to borrow * @param _account The address of the account to modify */ function _addToBorrowed(address _account, address _iToken) internal { // add() will return false if iToken is in account's market list if (accountsData[_account].borrowed.add(_iToken)) { emit BorrowedAdded(_iToken, _account); } } /** * @notice Returns whether the given account has borrowed the given iToken * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has borrowed the iToken, otherwise false. */ function hasBorrowed(address _account, address _iToken) public view override returns (bool) { return accountsData[_account].borrowed.contains(_iToken); } /** * @notice Remove the iToken from the account's borrowed list * @param _iToken The iToken to remove * @param _account The address of the account to modify */ function _removeFromBorrowed(address _account, address _iToken) internal { // remove() will return false if iToken does not exist in account's borrowed list if (accountsData[_account].borrowed.remove(_iToken)) { emit BorrowedRemoved(_iToken, _account); } } /*********************************/ /****** General Information ******/ /*********************************/ /** * @notice Return all of the iTokens * @return _alliTokens The list of iToken addresses */ function getAlliTokens() public view override returns (address[] memory _alliTokens) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); _alliTokens = new address[](_len); for (uint256 i = 0; i < _len; i++) { _alliTokens[i] = _iTokens.at(i); } } /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) public view override returns (bool) { return iTokens.contains(_iToken); } } // 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, 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; } } // 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.12; /** * @title dForce Lending Protocol's InterestRateModel Interface. * @author dForce Team. */ interface IInterestRateModelInterface { function isInterestRateModel() external view returns (bool); /** * @dev 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. * @param reserves The total amnount of reserves the market has. * @return The borrow rate per block (as a percentage, and scaled by 1e18). */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @dev 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. * @param reserves The total amnount of reserves the market has. * @param reserveRatio The current reserve factor the market has. * @return The supply rate per block (as a percentage, and scaled by 1e18). */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveRatio ) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IControllerAdminInterface { /// @notice Emitted when an admin supports a market event MarketAdded( address iToken, uint256 collateralFactor, uint256 borrowFactor, uint256 supplyCapacity, uint256 borrowCapacity, uint256 distributionFactor ); function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external; /// @notice Emitted when new price oracle is set event NewPriceOracle(address oldPriceOracle, address newPriceOracle); function _setPriceOracle(address newOracle) external; /// @notice Emitted when close factor is changed by admin event NewCloseFactor( uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa ); function _setCloseFactor(uint256 newCloseFactorMantissa) external; /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive( uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa ); function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external; /// @notice Emitted when iToken's collateral factor is changed by admin event NewCollateralFactor( address iToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa ); function _setCollateralFactor( address iToken, uint256 newCollateralFactorMantissa ) external; /// @notice Emitted when iToken's borrow factor is changed by admin event NewBorrowFactor( address iToken, uint256 oldBorrowFactorMantissa, uint256 newBorrowFactorMantissa ); function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa) external; /// @notice Emitted when iToken's borrow capacity is changed by admin event NewBorrowCapacity( address iToken, uint256 oldBorrowCapacity, uint256 newBorrowCapacity ); function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity) external; /// @notice Emitted when iToken's supply capacity is changed by admin event NewSupplyCapacity( address iToken, uint256 oldSupplyCapacity, uint256 newSupplyCapacity ); function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity) external; /// @notice Emitted when pause guardian is changed by admin event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); function _setPauseGuardian(address newPauseGuardian) external; /// @notice Emitted when mint is paused/unpaused by admin or pause guardian event MintPaused(address iToken, bool paused); function _setMintPaused(address iToken, bool paused) external; function _setAllMintPaused(bool paused) external; /// @notice Emitted when redeem is paused/unpaused by admin or pause guardian event RedeemPaused(address iToken, bool paused); function _setRedeemPaused(address iToken, bool paused) external; function _setAllRedeemPaused(bool paused) external; /// @notice Emitted when borrow is paused/unpaused by admin or pause guardian event BorrowPaused(address iToken, bool paused); function _setBorrowPaused(address iToken, bool paused) external; function _setAllBorrowPaused(bool paused) external; /// @notice Emitted when transfer is paused/unpaused by admin or pause guardian event TransferPaused(bool paused); function _setTransferPaused(bool paused) external; /// @notice Emitted when seize is paused/unpaused by admin or pause guardian event SeizePaused(bool paused); function _setSeizePaused(bool paused) external; function _setiTokenPaused(address iToken, bool paused) external; function _setProtocolPaused(bool paused) external; event NewRewardDistributor( address oldRewardDistributor, address _newRewardDistributor ); function _setRewardDistributor(address _newRewardDistributor) external; } interface IControllerPolicyInterface { function beforeMint( address iToken, address account, uint256 mintAmount ) external; function afterMint( address iToken, address minter, uint256 mintAmount, uint256 mintedAmount ) external; function beforeRedeem( address iToken, address redeemer, uint256 redeemAmount ) external; function afterRedeem( address iToken, address redeemer, uint256 redeemAmount, uint256 redeemedAmount ) external; function beforeBorrow( address iToken, address borrower, uint256 borrowAmount ) external; function afterBorrow( address iToken, address borrower, uint256 borrowedAmount ) external; function beforeRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function afterRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function beforeLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external; function afterLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repaidAmount, uint256 seizedAmount ) external; function beforeSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizeAmount ) external; function afterSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizedAmount ) external; function beforeTransfer( address iToken, address from, address to, uint256 amount ) external; function afterTransfer( address iToken, address from, address to, uint256 amount ) external; function beforeFlashloan( address iToken, address to, uint256 amount ) external; function afterFlashloan( address iToken, address to, uint256 amount ) external; } interface IControllerAccountEquityInterface { function calcAccountEquity(address account) external view returns ( uint256, uint256, uint256, uint256 ); function liquidateCalculateSeizeTokens( address iTokenBorrowed, address iTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256); } interface IControllerAccountInterface { function hasEnteredMarket(address account, address iToken) external view returns (bool); function getEnteredMarkets(address account) external view returns (address[] memory); /// @notice Emitted when an account enters a market event MarketEntered(address iToken, address account); function enterMarkets(address[] calldata iTokens) external returns (bool[] memory); function enterMarketFromiToken(address _account) external; /// @notice Emitted when an account exits a market event MarketExited(address iToken, address account); function exitMarkets(address[] calldata iTokens) external returns (bool[] memory); /// @notice Emitted when an account add a borrow asset event BorrowedAdded(address iToken, address account); /// @notice Emitted when an account remove a borrow asset event BorrowedRemoved(address iToken, address account); function hasBorrowed(address account, address iToken) external view returns (bool); function getBorrowedAssets(address account) external view returns (address[] memory); } interface IControllerInterface is IControllerAdminInterface, IControllerPolicyInterface, IControllerAccountEquityInterface, IControllerAccountInterface { /** * @notice Security checks when updating the comptroller of a market, always expect to return true. */ function isController() external view returns (bool); /** * @notice Return all of the iTokens * @return The list of iToken addresses */ function getAlliTokens() external view returns (address[] memory); /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) external view returns (bool); } // 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(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRewardDistributor { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); function _setGlobalDistributionSpeeds( uint256 borrowSpeed, uint256 supplySpeed ) external; /// @notice Emitted when iToken's Distribution speed is updated event DistributionSpeedsUpdated( address iToken, uint256 borrowSpeed, uint256 supplySpeed ); function updateDistributionSpeed() external; /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function _setDistributionFactors( address[] calldata iToken, uint256[] calldata distributionFactors ) external; function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); }
Unpause and set distribution speeds Admin function _borrowiTokens The borrow asset array _borrowSpeeds The borrow speed array _supplyiTokens The supply asset array _supplySpeeds The supply speed array/
function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external override onlyOwner { _setPaused(false); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); }
1,317,992
./full_match/1/0x7A40F0d4674baD90D8Dd0c4D355E52347d861931/sources/contracts/MZS.sol
List NFTs owned by address/
function listNFTs(address _owner) external view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; }
17,012,867
./partial_match/42/0x2b335a9234b405724FD5De8e072C66ed1b34D847/sources/P2PLending.sol
require(balances[msg.sender] >= amount, 'Not enough money on your BankAccount');loans[msg.sender].openLoan = false;delete loans[msg.sender];
function repayLoan() payable public{ require(isBorrower(msg.sender), 'You are not an Borrower'); require(hasOngoingLoan[msg.sender] == true, 'You do not have an ongoing Loan'); require(ifLoanOpen(msg.sender) == true, 'You have already paid your debt'); address payable reciever = (loans[msg.sender].investor); loans[msg.sender].original_amount -= msg.value; transfer(reciever, msg.value); hasOngoingInvestment[reciever] = false; hasOngoingLoan[msg.sender] = false; emit PayBack(msg.sender, reciever, msg.value, loans[msg.sender].original_amount, now); ifLoanOpen(msg.sender); }
8,879,192
./partial_match/1/0x508efB44A06a64Bd4020e8c5e8Ecf1A9236C75aE/sources/tokenWhitelistable.sol
Checks whether a token is available. return bool available or not.
function _isTokenAvailable(address _a) internal view returns (bool) { (, , , bool available, , , ) = _getTokenInfo(_a); return available; }
3,598,120
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; import "./Types.sol"; import "./Validator.sol"; import "./Proofs.sol"; import "./Commitment.sol"; library ClientState { //struct definition struct Data { string chain_id; Fraction.Data trust_level; int64 trusting_period; int64 unbonding_period; int64 max_clock_drift; Height.Data latest_height; ProofSpec.Data[] proof_specs; MerklePrefix.Data merkle_prefix; uint64 time_delay; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[10] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_chain_id(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_trust_level(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_trusting_period(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_unbonding_period(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_max_clock_drift(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_latest_height(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_proof_specs(pointer, bs, nil(), counters); } else if (fieldId == 8) { pointer += _read_merkle_prefix(pointer, bs, r, counters); } else if (fieldId == 9) { pointer += _read_time_delay(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.proof_specs = new ProofSpec.Data[](counters[7]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_chain_id(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_trust_level(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_trusting_period(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_unbonding_period(pointer, bs, nil(), counters); } else if (fieldId == 5) { pointer += _read_max_clock_drift(pointer, bs, nil(), counters); } else if (fieldId == 6) { pointer += _read_latest_height(pointer, bs, nil(), counters); } else if (fieldId == 7) { pointer += _read_proof_specs(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_merkle_prefix(pointer, bs, nil(), counters); } else if (fieldId == 9) { pointer += _read_time_delay(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_chain_id( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.chain_id = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trust_level( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Fraction.Data memory x, uint256 sz) = _decode_Fraction(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.trust_level = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trusting_period( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.trusting_period = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_unbonding_period( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.unbonding_period = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_clock_drift( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.max_clock_drift = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_latest_height( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Height.Data memory x, uint256 sz) = _decode_Height(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.latest_height = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_proof_specs( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ProofSpec.Data memory x, uint256 sz) = _decode_ProofSpec(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.proof_specs[r.proof_specs.length - counters[7]] = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_merkle_prefix( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (MerklePrefix.Data memory x, uint256 sz) = _decode_MerklePrefix(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.merkle_prefix = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_time_delay( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[9] += 1; } else { r.time_delay = x; if (counters[9] > 0) counters[9] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Fraction(uint256 p, bytes memory bs) internal pure returns (Fraction.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Fraction.Data memory r, ) = Fraction._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Height(uint256 p, bytes memory bs) internal pure returns (Height.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Height.Data memory r, ) = Height._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ProofSpec(uint256 p, bytes memory bs) internal pure returns (ProofSpec.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ProofSpec.Data memory r, ) = ProofSpec._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_MerklePrefix(uint256 p, bytes memory bs) internal pure returns (MerklePrefix.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (MerklePrefix.Data memory r, ) = MerklePrefix._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (bytes(r.chain_id).length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Fraction._encode_nested(r.trust_level, pointer, bs); if (r.trusting_period != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.trusting_period, pointer, bs); } if (r.unbonding_period != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.unbonding_period, pointer, bs); } if (r.max_clock_drift != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.max_clock_drift, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.latest_height, pointer, bs); if (r.proof_specs.length != 0) { for(i = 0; i < r.proof_specs.length; i++) { pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += ProofSpec._encode_nested(r.proof_specs[i], pointer, bs); } } pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += MerklePrefix._encode_nested(r.merkle_prefix, pointer, bs); if (r.time_delay != 0) { pointer += ProtoBufRuntime._encode_key( 9, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.time_delay, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length); e += 1 + ProtoBufRuntime._sz_lendelim(Fraction._estimate(r.trust_level)); e += 1 + ProtoBufRuntime._sz_int64(r.trusting_period); e += 1 + ProtoBufRuntime._sz_int64(r.unbonding_period); e += 1 + ProtoBufRuntime._sz_int64(r.max_clock_drift); e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.latest_height)); for(i = 0; i < r.proof_specs.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(ProofSpec._estimate(r.proof_specs[i])); } e += 1 + ProtoBufRuntime._sz_lendelim(MerklePrefix._estimate(r.merkle_prefix)); e += 1 + ProtoBufRuntime._sz_uint64(r.time_delay); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (bytes(r.chain_id).length != 0) { return false; } if (r.trusting_period != 0) { return false; } if (r.unbonding_period != 0) { return false; } if (r.max_clock_drift != 0) { return false; } if (r.proof_specs.length != 0) { return false; } if (r.time_delay != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.chain_id = input.chain_id; Fraction.store(input.trust_level, output.trust_level); output.trusting_period = input.trusting_period; output.unbonding_period = input.unbonding_period; output.max_clock_drift = input.max_clock_drift; Height.store(input.latest_height, output.latest_height); for(uint256 i7 = 0; i7 < input.proof_specs.length; i7++) { output.proof_specs.push(input.proof_specs[i7]); } MerklePrefix.store(input.merkle_prefix, output.merkle_prefix); output.time_delay = input.time_delay; } //array helpers for ProofSpecs /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addProofSpecs(Data memory self, ProofSpec.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ ProofSpec.Data[] memory tmp = new ProofSpec.Data[](self.proof_specs.length + 1); for (uint256 i = 0; i < self.proof_specs.length; i++) { tmp[i] = self.proof_specs[i]; } tmp[self.proof_specs.length] = value; self.proof_specs = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ClientState library ConsensusState { //struct definition struct Data { Timestamp.Data timestamp; bytes root; bytes next_validators_hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_root(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_next_validators_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.timestamp = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_root( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.root = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_next_validators_hash( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.next_validators_hash = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (r.root.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.root, pointer, bs); } if (r.next_validators_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.next_validators_hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(r.root.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.next_validators_hash.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.root.length != 0) { return false; } if (r.next_validators_hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { Timestamp.store(input.timestamp, output.timestamp); output.root = input.root; output.next_validators_hash = input.next_validators_hash; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ConsensusState library Header { //struct definition struct Data { SignedHeader.Data signed_header; ValidatorSet.Data validator_set; Height.Data trusted_height; ValidatorSet.Data trusted_validators; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_signed_header(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_validator_set(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_trusted_height(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_trusted_validators(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signed_header( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (SignedHeader.Data memory x, uint256 sz) = _decode_SignedHeader(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.signed_header = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_set( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ValidatorSet.Data memory x, uint256 sz) = _decode_ValidatorSet(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.validator_set = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trusted_height( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Height.Data memory x, uint256 sz) = _decode_Height(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.trusted_height = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_trusted_validators( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ValidatorSet.Data memory x, uint256 sz) = _decode_ValidatorSet(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.trusted_validators = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_SignedHeader(uint256 p, bytes memory bs) internal pure returns (SignedHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (SignedHeader.Data memory r, ) = SignedHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ValidatorSet(uint256 p, bytes memory bs) internal pure returns (ValidatorSet.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ValidatorSet.Data memory r, ) = ValidatorSet._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Height(uint256 p, bytes memory bs) internal pure returns (Height.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Height.Data memory r, ) = Height._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += SignedHeader._encode_nested(r.signed_header, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ValidatorSet._encode_nested(r.validator_set, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.trusted_height, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ValidatorSet._encode_nested(r.trusted_validators, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(SignedHeader._estimate(r.signed_header)); e += 1 + ProtoBufRuntime._sz_lendelim(ValidatorSet._estimate(r.validator_set)); e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.trusted_height)); e += 1 + ProtoBufRuntime._sz_lendelim(ValidatorSet._estimate(r.trusted_validators)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { SignedHeader.store(input.signed_header, output.signed_header); ValidatorSet.store(input.validator_set, output.validator_set); Height.store(input.trusted_height, output.trusted_height); ValidatorSet.store(input.trusted_validators, output.trusted_validators); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Header library Fraction { //struct definition struct Data { uint64 numerator; uint64 denominator; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_numerator(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_denominator(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_numerator( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.numerator = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_denominator( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.denominator = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.numerator != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.numerator, pointer, bs); } if (r.denominator != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.denominator, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.numerator); e += 1 + ProtoBufRuntime._sz_uint64(r.denominator); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.numerator != 0) { return false; } if (r.denominator != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.numerator = input.numerator; output.denominator = input.denominator; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Fraction
The decoder for reading a field p The offset of bytes array to start decode bs The bytes array to be decoded r The in-memory struct counters The counters for repeated fields return The number of bytes decoded/ if `r` is NULL, then only counting the number of fields./
function _read_trust_level( uint256 p, bytes memory bs, Data memory r, uint[10] memory counters ) internal pure returns (uint) { (Fraction.Data memory x, uint256 sz) = _decode_Fraction(p, bs); if (isNil(r)) { counters[2] += 1; r.trust_level = x; if (counters[2] > 0) counters[2] -= 1; } return sz; }
5,547,547
pragma solidity 0.8.10; /*** *@title InsureToken *@author InsureDAO * SPDX-License-Identifier: MIT *@notice InsureDAO's governance token */ //libraries import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/pool/IOwnership.sol"; contract InsureToken is IERC20 { event UpdateMiningParameters( uint256 time, uint256 rate, uint256 supply, int256 miningepoch ); event SetMinter(address minter); event SetAdmin(address admin); event SetRate(uint256 rate); string public name; string public symbol; uint256 public constant decimals = 18; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) allowances; uint256 public total_supply; address public minter; IOwnership public immutable ownership; //General constants uint256 constant YEAR = 86400 * 365; // Allocation within 5years: // ========== // * Team & Development: 24% // * Liquidity Mining: 40% // * Investors: 10% // * Foundation Treasury: 14% // * Community Treasury: 10% // ========== // // After 5years: // ========== // * Liquidity Mining: 40%~ (Mint fixed amount every year) // // Mint 2_800_000 INSURE every year. // 6th year: 1.32% inflation rate // 7th year: 1.30% inflation rate // 8th year: 1.28% infration rate // so on // ========== // Supply parameters uint256 constant INITIAL_SUPPLY = 126_000_000; //will be vested uint256 constant RATE_REDUCTION_TIME = YEAR; uint256[6] public RATES = [ (28_000_000 * 10**18) / YEAR, //epoch 0 (22_400_000 * 10**18) / YEAR, //epoch 1 (16_800_000 * 10**18) / YEAR, //epoch 2 (11_200_000 * 10**18) / YEAR, //epoch 3 (5_600_000 * 10**18) / YEAR, //epoch 4 (2_800_000 * 10**18) / YEAR //epoch 5~ ]; uint256 constant RATE_DENOMINATOR = 10**18; uint256 constant INFLATION_DELAY = 86400; // Supply variables int256 public mining_epoch; uint256 public start_epoch_time; uint256 public rate; uint256 public start_epoch_supply; uint256 public emergency_minted; modifier onlyOwner() { require( ownership.owner() == msg.sender, "Caller is not allowed to operate" ); _; } /*** * @notice Contract constructor * @param _name Token full name * @param _symbol Token symbol */ constructor( string memory _name, string memory _symbol, address _ownership ) { uint256 _init_supply = INITIAL_SUPPLY * RATE_DENOMINATOR; name = _name; symbol = _symbol; balanceOf[msg.sender] = _init_supply; total_supply = _init_supply; ownership = IOwnership(_ownership); emit Transfer(address(0), msg.sender, _init_supply); unchecked { start_epoch_time = block.timestamp + INFLATION_DELAY - RATE_REDUCTION_TIME; mining_epoch = -1; } rate = 0; start_epoch_supply = _init_supply; } /*** *@dev Update mining rate and supply at the start of the epoch * Any modifying mining call must also call this */ function _update_mining_parameters() internal { uint256 _rate = rate; uint256 _start_epoch_supply = start_epoch_supply; start_epoch_time += RATE_REDUCTION_TIME; unchecked { mining_epoch += 1; } if (mining_epoch == 0) { _rate = RATES[uint256(mining_epoch)]; } else if (mining_epoch < int256(6)) { _start_epoch_supply += RATES[uint256(mining_epoch) - 1] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[uint256(mining_epoch)]; } else { _start_epoch_supply += RATES[5] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[5]; } rate = _rate; emit UpdateMiningParameters( block.timestamp, _rate, _start_epoch_supply, mining_epoch ); } /*** * @notice Update mining rate and supply at the start of the epoch * @dev Callable by any address, but only once per epoch * Total supply becomes slightly larger if this function is called late */ function update_mining_parameters() external { require( block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME, "dev: too soon!" ); _update_mining_parameters(); } /*** *@notice Get timestamp of the current mining epoch start * while simultaneously updating mining parameters *@return Timestamp of the epoch */ function start_epoch_time_write() external returns (uint256) { uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time; } else { return _start_epoch_time; } } /*** *@notice Get timestamp of the next mining epoch start * while simultaneously updating mining parameters *@return Timestamp of the next epoch */ function future_epoch_time_write() external returns (uint256) { uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time + RATE_REDUCTION_TIME; } else { return _start_epoch_time + RATE_REDUCTION_TIME; } } function _available_supply() internal view returns (uint256) { return start_epoch_supply + ((block.timestamp - start_epoch_time) * rate) + emergency_minted; } /*** *@notice Current number of tokens in existence (claimed or unclaimed) */ function available_supply() external view returns (uint256) { return _available_supply(); } /*** *@notice How much supply is mintable from start timestamp till end timestamp *@param start Start of the time interval (timestamp) *@param end End of the time interval (timestamp) *@return Tokens mintable from `start` till `end` */ function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; // Special case if end is in future (not yet minted) epoch if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_epoch += 1; _current_rate = RATES[uint256(_current_epoch)]; } else { _current_epoch += 1; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i; i < 999; ) { // InsureDAO will not work in 1000 years. if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { break; // We should never get here but what if... } else if (current_start < _current_epoch_time) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch == 0) { _current_rate = 0; } else { _current_rate = _current_epoch < 5 ? RATES[uint256(_current_epoch) - 1] : RATES[5]; } _current_epoch -= 1; assert(_current_rate <= RATES[0]); // This should never happen unchecked { ++i; } } return _to_mint; } /*** *@notice Total number of tokens in existence. */ function totalSupply() external view override returns (uint256) { return total_supply; } /*** *@notice Check the amount of tokens that an owner allowed to a spender *@param _owner The address which owns the funds *@param _spender The address which will spend the funds *@return uint256 specifying the amount of tokens still available for the spender */ function allowance(address _owner, address _spender) external view override returns (uint256) { return allowances[_owner][_spender]; } /*** *@notice Transfer `_value` tokens from `msg.sender` to `_to` *@dev Vyper does not allow underflows, so the subtraction in * this function will revert on an insufficient balance *@param _to The address to transfer to *@param _value The amount to be transferred *@return bool success */ function transfer(address _to, uint256 _value) external override returns (bool) { require(_to != address(0), "transfers to 0x0 are not allowed"); uint256 _fromBalance = balanceOf[msg.sender]; require(_fromBalance >= _value, "transfer amount exceeds balance"); unchecked { balanceOf[msg.sender] = _fromBalance - _value; } balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } /*** * @notice Transfer `_value` tokens from `_from` to `_to` * @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 * @return bool success */ function transferFrom( address _from, address _to, uint256 _value ) external override returns (bool) { require(_from != address(0), "transfer from the zero address"); require(_to != address(0), "transfer to the zero address"); uint256 currentAllowance = allowances[_from][msg.sender]; require(currentAllowance >= _value, "transfer amount exceeds allow"); unchecked { allowances[_from][msg.sender] -= _value; } uint256 _fromBalance = balanceOf[_from]; require(_fromBalance >= _value, "transfer amount exceeds balance"); unchecked { balanceOf[_from] -= _value; } balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "approve from the zero address"); require(spender != address(0), "approve to the zero address"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** *@notice Approve `_spender` to transfer `_value` tokens on behalf of `msg.sender` *@param _spender The address which will spend the funds *@param _value The amount of tokens to be spent *@return bool success */ function approve(address _spender, uint256 _value) external override returns (bool) { _approve(msg.sender, _spender, _value); return true; } function increaseAllowance(address _spender, uint256 addedValue) external returns (bool) { _approve( msg.sender, _spender, allowances[msg.sender][_spender] + addedValue ); return true; } function decreaseAllowance(address _spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = allowances[msg.sender][_spender]; require( currentAllowance >= subtractedValue, "decreased allowance below zero" ); unchecked { _approve(msg.sender, _spender, currentAllowance - subtractedValue); } return true; } /*** *@notice Mint `_value` tokens and assign them to `_to` *@dev Emits a Transfer event originating from 0x00 *@param _to The account that will receive the created tokens *@param _value The amount that will be created *@return bool success */ function mint(address _to, uint256 _value) external returns (bool) { require(msg.sender == minter, "dev: minter only"); require(_to != address(0), "dev: zero address"); _mint(_to, _value); return true; } function _mint(address _to, uint256 _value) internal { uint256 _total_supply = total_supply + _value; require( _total_supply <= _available_supply(), "exceeds allowable mint amount" ); if (block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); } total_supply = _total_supply; balanceOf[_to] += _value; emit Transfer(address(0), _to, _value); } /** *@notice Burn `_value` tokens belonging to `msg.sender` *@dev Emits a Transfer event with a destination of 0x00 *@param _value The amount that will be burned *@return bool success */ function burn(uint256 _value) external returns (bool) { require( balanceOf[msg.sender] >= _value, "_value > balanceOf[msg.sender]" ); unchecked { balanceOf[msg.sender] -= _value; } total_supply -= _value; emit Transfer(msg.sender, address(0), _value); return true; } /*** *@notice Change the token name and symbol to `_name` and `_symbol` *@dev Only callable by the admin account *@param _name New token name *@param _symbol New token symbol */ function set_name(string memory _name, string memory _symbol) external onlyOwner { name = _name; symbol = _symbol; } /*** *@notice Set the minter address *@dev Only callable once, when minter has not yet been set *@param _minter Address of the minter */ function set_minter(address _minter) external onlyOwner { require(minter == address(0), "can set the minter at creation"); minter = _minter; emit SetMinter(_minter); } /*** *@notice Set the new rate for the infration after 5 years. *@dev input must be the number of INSURE to be minted per second. *@param _rate mint amount per second */ function set_rate(uint256 _rate) external onlyOwner { require(_rate < RATES[5], "Decrease Only"); RATES[5] = _rate; emit SetRate(_rate); } /*** * @notice Emergency minting only when CDS couldn't afford the insolvency. * @dev * @param _amountOut token amount needed. token is defiend whithin converter. * @param _to CDS address */ function emergency_mint(uint256 _amount, address _to) external returns (bool) { require(msg.sender == minter, "dev: minter only"); //mint emergency_minted += _amount; _mint(_to, _amount); return true; } }
How much supply is mintable from start timestamp till end timestamp start Start of the time interval (timestamp) end End of the time interval (timestamp)return Tokens mintable from `start` till `end`/ Special case if end is in future (not yet minted) epoch InsureDAO will not work in 1000 years.
function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_epoch += 1; _current_rate = RATES[uint256(_current_epoch)]; _current_epoch += 1; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i; i < 999; ) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch == 0) { _current_rate = 0; _current_rate = _current_epoch < 5 ? RATES[uint256(_current_epoch) - 1] : RATES[5]; } _current_epoch -= 1; unchecked { ++i; } } return _to_mint; }
14,114,007
./full_match/1/0x95f808db51579f9c7AC13e0B73075DB86016d0C6/sources/contracts/UnicusNft.sol
Returns all the bidder who participated in this Auction owner_ owner of the Auction Calling conditions: - Only the owner of the smart contract i.e Unicus platform can invoke this return address of the all the bidder who placed the bids for this Auction./
function getAllBidders(address owner_) public view returns(address[] memory ) { require(owner_ == _owner, "Only Auction owner can perform this operation"); return _bidders; }
3,154,425
pragma solidity ^0.4.18; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract TokenERC20 is owned { // Public variables of the token string public name; string public symbol; uint8 public decimals = 8; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /* Returns total supply of issued tokens */ function totalSupply() constant public returns (uint256 supply) { return totalSupply; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { // Master Lock: Allow transfer by other users only after 1511308799 if (msg.sender != owner) require(now > 1511308799); _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } } contract CDRTToken is TokenERC20 { uint256 public buyBackPrice; // Snapshot of PE balances by Ethereum Address and by year mapping (uint256 => mapping (address => uint256)) public snapShot; // This is time for next Profit Equivalent uint256 public nextPE = 1539205199; // List of Team and Founders account's frozen till 15 November 2018 mapping (address => uint256) public frozenAccount; // List of all years when snapshots were made uint[] internal yearsPast = [17]; // Holds current year PE balance uint256 public peBalance; // Holds full Buy Back balance uint256 public bbBalance; // Holds unclaimed PE balance from last periods uint256 internal peLastPeriod; // All ever used in transactions Ethereum Addresses' positions in list mapping (address => uint256) internal ownerPos; // Total number of Ethereum Addresses used in transactions uint256 internal pos; // All ever used in transactions Ethereum Addresses list mapping (uint256 => address) internal addressList; /* Handles incoming payments to contract's address */ function() payable public { } /* Initializes contract with initial supply tokens to the creator of the contract */ function CDRTToken( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} /* Internal insertion in list of all Ethereum Addresses used in transactions, called by contract */ function _insert(address _to) internal { if (ownerPos[_to] == 0) { pos++; addressList[pos] = _to; ownerPos[_to] = pos; } } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(frozenAccount[_from] < now); // Check if sender is frozen _insert(_to); balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } /** * @notice Freezes from sending & receiving tokens. For users protection can't be used after 1542326399 * and will not allow corrections. * * Will set freeze to 1542326399 * * @param _from Founders and Team account we are freezing from sending * */ function freezeAccount(address _from) onlyOwner public { require(now < 1542326400); require(frozenAccount[_from] == 0); frozenAccount[_from] = 1542326399; } /** * @notice Allow owner to set tokens price for Buy-Back Campaign. Can not be executed until 1539561600 * * @param _newPrice market value of 1 CDRT Token * */ function setPrice(uint256 _newPrice) onlyOwner public { require(now > 1539561600); buyBackPrice = _newPrice; } /** * @notice Contract owner can take snapshot of current balances and issue PE to each balance * * @param _year year of the snapshot to take, must be greater than existing value * * @param _nextPE set new Profit Equivalent date * */ function takeSnapshot(uint256 _year, uint256 _nextPE) onlyOwner public { require(_year > yearsPast[yearsPast.length-1]); uint256 reward = peBalance / totalSupply; for (uint256 k=1; k <= pos; k++){ snapShot[_year][addressList[k]] = balanceOf[addressList[k]] * reward; } yearsPast.push(_year); peLastPeriod += peBalance; // Transfer new balance to unclaimed peBalance = 0; // Zero current balance; nextPE = _nextPE; } /** * @notice Allow user to claim his PE on his Ethereum Address. Should be called manualy by user * */ function claimProfitEquivalent() public{ uint256 toPay; for (uint k=0; k <= yearsPast.length-1; k++){ toPay += snapShot[yearsPast[k]][msg.sender]; snapShot[yearsPast[k]][msg.sender] = 0; } msg.sender.transfer(toPay); peLastPeriod -= toPay; } /** * @notice Allow user to sell CDRT tokens and destroy them. Can not be executed until 1539561600 * * @param _qty amount to sell and destroy */ function execBuyBack(uint256 _qty) public{ require(now > 1539561600); uint256 toPay = _qty*buyBackPrice; require(balanceOf[msg.sender] >= _qty); // check if user has enough CDRT Tokens require(buyBackPrice > 0); // check if sale price set require(bbBalance >= toPay); require(frozenAccount[msg.sender] < now); // Check if sender is frozen msg.sender.transfer(toPay); bbBalance -= toPay; burn(_qty); } /** * @notice Allow owner to set balances * * */ function setBalances(uint256 _peBalance, uint256 _bbBalance) public{ peBalance = _peBalance; bbBalance = _bbBalance; } }
Allow owner to set balances/
function setBalances(uint256 _peBalance, uint256 _bbBalance) public{ peBalance = _peBalance; bbBalance = _bbBalance; }
6,489,321
// SPDX-License-Identifier: MIT /* MIT License Copyright (c) 2020 Hydro Money 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. */ pragma solidity 0.6.12; /** * @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 ERC20 interface */ interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); 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); } /** * @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 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; } /** * @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 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; } } /** * @title Hydro ERC20-BEP20 Swap Contract */ contract HydroTokenSwap is Ownable { using SafeMath for uint256; uint256 public contractTotalAmountSwapped; address constant Hydro_ADDRESS= 0x946112efaB61C3636CBD52DE2E1392D7A75A6f01; address Main_ADDRESS= 0x4aE8bfB81205837DE1437De26D02E5ca87694714; bool public isActive; struct User { address userAdd; uint256 totalAmountSwapped; } //a mapping to keep the details of users mapping(address => User) public userDetails; //main event that is emitted after a successful deposit event SwapDeposit(address indexed depositor, uint256 outputAmount); //check if the contract is open to swaps function isSwapActive() public view returns (bool) { return isActive; } //make sure contract is open to swaps modifier hasActiveSwap { require(isSwapActive(), "Swapping is currently paused"); _; } /** * @dev Allows the user to deposit some amount of Hydro tokens. Records user/swap data and emits a SwapDeposit event. * @param amount Amount of input tokens to be swapped. */ function swap( uint256 amount) external hasActiveSwap { require(amount > 0, "Input amount must be positive."); uint256 outputAmount = amount; require(outputAmount > 0, "Amount too small."); require(IERC20(Hydro_ADDRESS).transferFrom(msg.sender, Main_ADDRESS, amount), "Transferring Hydro tokens from user failed"); userDetails[msg.sender].totalAmountSwapped+=amount; userDetails[msg.sender].userAdd=msg.sender; contractTotalAmountSwapped+=amount; emit SwapDeposit(msg.sender,amount); } function totalAmountSwappedInContract(address _user) public view returns(uint256){ return userDetails[_user].totalAmountSwapped; } function grossAmountSwapped() public view returns(uint256){ return contractTotalAmountSwapped; } //allow the owner to activate the escrow contract function openEscrow() public onlyOwner hasActiveSwap returns(bool){ isActive=true; } //allow the owner to deactivate the escrow contract function closeEscrow() public onlyOwner returns(bool){ isActive=false; } //allow owner to rescue any tokens sent to the contract function transferOut(address _token) public onlyOwner returns(bool){ IERC20 token= IERC20(_token); uint256 balance= token.balanceOf(address(this)); require(token.transfer(msg.sender,balance),"HydroSwap: Token Transfer error"); return true; } /** !!!!!!!!!!!!!!!!!! !!!!!CAUTION!!!!!! !!!!!!!!!!!!!!!!!! **/ //allow owner to change central wallet function changeCentralWallet(address _newWallet) public onlyOwner returns(bool){ require(_newWallet!=address(0),"Error: Burn address not supported"); Main_ADDRESS=_newWallet; return true; } }
check if the contract is open to swaps
function isSwapActive() public view returns (bool) { return isActive; }
548,821
/* Copyright (c) 2018 ZSC Dev Team */ pragma solidity ^0.4.21; import "./object.sol"; contract DBNode { function getNodeType() public view returns (bytes32); function getBalance(address _adr) public view returns (uint256); function getLockedAmount(address _tokenAdr) public view returns (uint); function getTransactionInfoByIndex(uint _index) public view returns (uint, uint, uint, address, address); function executeTransaction(address _tokenAdr, address _dest, uint _amount) public; function setERC20TokenAddress(address _tokenAdr) public; function numTransactions() public view returns (uint); function lockWallet(address _tokenAdr, uint _amount) public; function unlockWallet(address _tokenAdr, uint _amount) public; function addParameter(bytes32 _parameter) public returns (bool); //function removeParameter(bytes32 _parameter) public returns (bool); function setParameter(bytes32 _parameter, bytes32 _value) public returns (bool); function getParameter(bytes32 _parameter) public view returns (bytes32); function numParameters() public view returns (uint); function getParameterNameByIndex(uint _index) public view returns (bytes32); function setAgreementStatus(bytes32 _tag, bytes32 receiver) public returns (bool); //function configureHandlers() public returns (bool); //function getHandler(bytes32 _type) public view returns (address); function bindAgreement(address _adr) public; function numAgreements() public view returns (uint); function numTemplates() public view returns (uint); function getAgreementByIndex(uint _index) public view returns (address); function getTemplateByIndex(uint _index) public view returns (address); function numChildren() public view returns(uint); function getChildByIndex(uint _index) public view returns(address); function addChild(address _node) public returns (address); //function getMiningInfoByIndex(bool _isReward, uint _index) public view returns (uint, uint); //function numMiningInfo(bool _isReward) public view returns (uint); //function addSignature(address _sigAdr) public returns (bool); //function getAgreementInfo() public view returns (bytes32, bytes32, uint, uint, bytes32, uint); function simulatePayforInsurance() public returns (uint); } contract DBFactory { function setDatabase(address _adr) public; function createNode(bytes32 _nodeName, address _parent, address _creator) public returns (address); function numFactoryNodes() public view returns (uint); function getFactoryNodeNameByIndex(uint _index) public view returns (bytes32); } contract DBDatabase { function delegateFactory(address _adr, uint _priority) public; function getNode(bytes32 _name) public view returns (address); function getRootNode() public view returns (address); function destroyNode(address _node) public returns (bool); function checkeNodeByAddress(address _adr) public view returns (bool); function _addNode(address _node) public ; } contract DBModule { function numOfTokens() public view returns (uint); function getTokenAddress(bytes32 _symbol) public view returns (address); function getTokenInfoByIndex(uint _index) public view returns (bytes32, bytes32, bytes32, uint, address); function getTokenInfoBySymbol(bytes32 _symbol) public view returns (bytes32, bytes32, bytes32, uint, address); function isTokenPosable(bytes32 _symbol) public view returns (bool); function isTokenTradeable(bytes32 _symbol) public view returns (bool); /*ERC721 for miner robot begin*/ //function balanceOf(address _owner) public view returns (uint); //function tokenOfOwnerByIndex(address _owner, uint _index) public view returns (uint); //function getRobotInfo(uint _robotId) public view returns (bytes32, uint, uint, uint, uint, uint, uint); //function getExtraEffect(uint _robotId) public view returns (uint _extraSp, uint _extraUpgradProb); //function getLevelInfo(uint _index) public view returns (uint, uint, uint, uint); //function createRobot(address _user, uint _level) public returns (uint); //function activeRobot(address _user, uint _robotId, uint _durationInDays, uint _totalZSC) public returns (uint); //function publishRobot(address _seller, uint _robotId, uint _price) public; //function cancelAuction(address _seller, uint _robotId) public; //function purchaseRobot(address _buyer, uint _robotId) public returns (address, uint); //function getReward(address _user, uint _robotId) public view returns (uint); //function claimReward(address _user, uint _robotId) public returns (uint, uint); //function numSellingRobots() public view returns (uint); //function getSellingRobotByIndex(uint _index) public view returns (uint, uint, uint, uint, address); //function safeTransferFrom(address _from, address _to, uint _tokenId) public; /*ERC721 for miner robot end*/ } contract ControlBase is Object { address private bindedAdm_; bytes32 internal dbName_ = "zsc"; mapping(bytes32 => address) private databases_; mapping(bytes32 => address) private factories_; mapping(bytes32 => address) private modules_; bytes32 private allocatedTokenSymbol_; uint private allocatedToken_; uint private allocatedETH_; address internal paymentReceiver_; mapping(address => bool) private walletAdrs_; function ControlBase(bytes32 _name) public Object(_name) { } ////////////////////////////////// function registerUserNode(address _creator, bytes32 _userName, bytes32 _type) internal; function registerEntityNode(address _creator, bytes32 _endName) internal; function checkAllowed(address _sender) public view; function checkMatched(address _sender, bytes32 _enName) public view; function getMappedName(address _sender) public view returns (bytes32); function getBindedWalletAddress(bytes32 _enName) public view returns (address); function createUserNode(bytes32 _factoryType, bytes32 _userName, address _extraAdr) public returns (address); ////////////////////////////////// function preallocateZSCToTester(address _userWalletAdr) internal { if (allocatedToken_ > 0) { address tokenContractAdr = getDBModule("gm-token").getTokenAddress(allocatedTokenSymbol_); uint remaingZSC = ERC20Interface(tokenContractAdr).balanceOf(address(this)); if (remaingZSC > allocatedToken_) { ERC20Interface(tokenContractAdr).transfer(_userWalletAdr, allocatedToken_); } } if (allocatedETH_ > 0) { uint remaingETH = address(this).balance; if (remaingETH > allocatedETH_) { require(_userWalletAdr.call.value(allocatedETH_)()); } } } function mapFactoryDatabase(address _factoryAdr, bytes32 _dbName, uint _priority) internal { address dbAdr = databases_[_dbName]; DBFactory(_factoryAdr).setDatabase(dbAdr); DBDatabase(dbAdr).delegateFactory(_factoryAdr, _priority); } function getComponent(bytes32 _type, bytes32 _name) internal view returns (address) { if (_type == "factory") { return factories_[_name]; } else if (_type == "database") { return databases_[_name]; } else if (_type == "module") { return modules_[_name]; } else { revert(); } } function getDBFactory(bytes32 _name) internal view returns (DBFactory) { return DBFactory(getComponent("factory", _name)); } function getDBDatabase(bytes32 _name) internal view returns (DBDatabase) { return DBDatabase(getComponent("database", _name)); } function getDBModule(bytes32 _name) internal view returns (DBModule) { return DBModule(getComponent("module", _name)); } function getDBNode(bytes32 _db, bytes32 _nodeName) internal view returns (DBNode) { return DBNode(getDBDatabase(_db).getNode(_nodeName)); } function duplicateNode(address _nodeSrcAdr, address _nodeDstAdr) internal returns (bool) { //require(_nodeSrcAdr != address(0) && _nodeDstAdr != address(0)); bytes32 tempPara; bytes32 tempValue; uint paraNos = DBNode(_nodeSrcAdr).numParameters(); for (uint i = 0; i < paraNos; ++i) { tempPara = DBNode(_nodeSrcAdr).getParameterNameByIndex(i); tempValue = DBNode(_nodeSrcAdr).getParameter(tempPara); DBNode(_nodeDstAdr).addParameter(tempPara); DBNode(_nodeDstAdr).setParameter(tempPara, tempValue); } return true; } function formatWalletName(bytes32 _userName) internal pure returns (bytes32) { string memory str; str = PlatString.append(_userName, "-wat"); return PlatString.tobytes32(str); } function enableWallet(bytes32 _walletName, address _enAdr, address _creator) internal returns (address) { require(address(getDBNode(dbName_, _walletName)) == 0); address walletAdr = getDBFactory("wallet-adv").createNode(_walletName, _enAdr, _creator); require(walletAdr != 0); walletAdrs_[walletAdr] = true; return walletAdr; } ////////////////////////////////////// ////////////////////////////////////// function initControlApis(address _adm) public { checkDelegate(msg.sender, 1); require (_adm != 0); bindedAdm_ = _adm; setDelegate(bindedAdm_, 1); addLog("initControlApis ", true); } function setPaymentReceiver(address _receiver) public { checkDelegate(msg.sender, 1); require(_receiver != address(0)); paymentReceiver_ = _receiver; } function setPreallocateAmountToTester(uint _ethAmount, bytes32 _tokenSymbol, uint _tokenAmount) public { checkDelegate(msg.sender, 1); allocatedTokenSymbol_ = _tokenSymbol; if (_ethAmount > 0) { allocatedETH_ = _ethAmount.mul(1 ether);} if (_tokenAmount > 0) { allocatedToken_ = _tokenAmount.mul(1 ether); } } function addSystemComponent(bytes32 _type, bytes32 _name, address _adr) public returns (bool) { bool ret = false; checkDelegate(msg.sender, 1); require(_adr != address(0)); addLog("addComponent ", true); addLog(PlatString.bytes32ToString(_type), false); addLog(" ", false); addLog(PlatString.bytes32ToString(_name), false); if (_type == "factory") { factories_[_name] = _adr; mapFactoryDatabase(_adr, dbName_, 1); } else if (_type == "database") { databases_[_name] = _adr; } else if (_type == "module") { setDelegate(_adr, 1); modules_[_name] = _adr; } else { revert(); } return ret; } function doesWalletExist(address _wallet) public view returns (bool) { return walletAdrs_[_wallet]; } ////////////////////////////////////// ////////////////////////////////////// function submitTransfer(bytes32 _tokenSymbol, address _dest, uint256 _amount) public { checkAllowed(msg.sender); require(_amount > 0); bytes32 userName = getMappedName(msg.sender); address walletAdr = getBindedWalletAddress(userName); require(walletAdr != address(0)); address tokenContractAdr = getDBModule("gm-token").getTokenAddress(_tokenSymbol); DBNode(walletAdr).executeTransaction(tokenContractAdr, _dest, _amount); } function getModuleAdress(bytes32 _name) public view returns (address) { return modules_[_name]; } //------2018-07-18: new verstion: YYA------ function getUserWalletAddress() public view returns (address) { //checkAllowed(msg.sender); bytes32 userName = getMappedName(msg.sender); return getBindedWalletAddress(userName); } function numOfTokens() public view returns (uint) { return getDBModule("gm-token").numOfTokens(); } function getTokenBalanceInfoBySymbol(bytes32 _symbol) public view returns (string) { //checkAllowed(msg.sender); bytes32 userName = getMappedName(msg.sender); bytes32 status; bytes32 tokenName; bytes32 tokenSymbol; uint tokenDecimals; address tokenAdr; address userWalletAdr; uint tokenBalance; uint lockedAmount; userWalletAdr = getBindedWalletAddress(userName); (status, tokenName, tokenSymbol, tokenDecimals, tokenAdr) = getDBModule("gm-token").getTokenInfoBySymbol(_symbol); tokenBalance = DBNode(userWalletAdr).getBalance(tokenAdr); lockedAmount = DBNode(userWalletAdr).getLockedAmount(tokenAdr); string memory str =""; str = PlatString.append(str, "info?status=", PlatString.bytes32ToString(status), "&"); str = PlatString.append(str, "symbol=", PlatString.bytes32ToString(tokenSymbol), "&"); str = PlatString.append(str, "balance=", PlatString.uintToString(tokenBalance), "&"); str = PlatString.append(str, "locked=", PlatString.uintToString(lockedAmount), "&"); str = PlatString.append(str, "adr=", PlatString.addressToString(tokenAdr), "&"); return str; } function getTokenBalanceInfoByIndex(uint _index) public view returns (string) { //checkAllowed(msg.sender); bytes32 userName = getMappedName(msg.sender); bytes32 status; bytes32 tokenName; bytes32 tokenSymbol; uint tokenDecimals; address tokenAdr; address userWalletAdr; uint tokenBalance; uint lockedAmount; userWalletAdr = getBindedWalletAddress(userName); (status, tokenName, tokenSymbol, tokenDecimals, tokenAdr) = getDBModule("gm-token").getTokenInfoByIndex(_index); tokenBalance = DBNode(userWalletAdr).getBalance(tokenAdr); lockedAmount = DBNode(userWalletAdr).getLockedAmount(tokenAdr); string memory str =""; str = PlatString.append(str, "info?status=", PlatString.bytes32ToString(status), "&"); str = PlatString.append(str, "symbol=", PlatString.bytes32ToString(tokenSymbol), "&"); str = PlatString.append(str, "balance=", PlatString.uintToString(tokenBalance), "&"); str = PlatString.append(str, "locked=", PlatString.uintToString(lockedAmount), "&"); str = PlatString.append(str, "adr=", PlatString.addressToString(tokenAdr), "&"); return str; } }
------2018-07-18: new verstion: YYA------checkAllowed(msg.sender);
function getUserWalletAddress() public view returns (address) { bytes32 userName = getMappedName(msg.sender); return getBindedWalletAddress(userName); }
13,015,363
./full_match/80001/0x66975AD8595E9268c705E33A971Af2111C96e4a0/sources/contracts/FallbackTest.sol
results in test.x becoming == 1. address(test) will not allow to call ``send`` directly, since ``test`` has no payable fallback function. It has to be converted to the ``address payable`` type to even allow calling ``send`` on it. If someone sends Ether to that contract, the transfer will fail, i.e. this returns false here.
function callTest(Test test) public returns (bool) { (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); require(success); address payable testPayable = payable(address(test)); return testPayable.send(0.002 ether); }
5,621,056
./full_match/4/0x90Fa288ac57A13478Ae2A6ff4EcaC3e08658f1aF/sources/contracts/TradingContract.sol
Function that created a Path in order to perform transactions with the UniswapV2Router. The directPath booleanwill define if the trading will happen directly (true) or though WBNB (false). If there is no LP between thebaseToken and the PairedToken a direct trade is not possible.
function createPath(address _tokenIn,address _tokenOut) internal view returns (address[] memory) { address[] memory path; if (directPath) { path = new address[](2); path[0] = _tokenIn; path[1] = _tokenOut; if (_tokenIn == WETHAddress || _tokenOut == WETHAddress) { path = new address[](2); path[0] = _tokenIn; path[1] = _tokenOut; path = new address[](3); path[0] = _tokenIn; path[1] = WETHAddress; path[2] = _tokenOut; } } return path; }
756,210
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "hardhat/console.sol"; import "@openzeppelin/contracts/governance/TimelockController.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import { IMembership } from "../interfaces/IMembership.sol"; import { ITreasury } from "../interfaces/ITreasury.sol"; import { IModule } from "../interfaces/IModule.sol"; import { Errors } from "../libraries/Errors.sol"; import { DataTypes } from "../libraries/DataTypes.sol"; /** * @title Core Module * @notice The core module consists of a multi-signature contract and a time lock. * The application module can authorize and pull assets from the vault by inheriting this core module. */ abstract contract Module is Context, IModule { using EnumerableSet for EnumerableSet.UintSet; string public NAME; string public DESCRIPTION; address public immutable membership; address public immutable share; TimelockController public immutable timelock; mapping(bytes32 => mapping(uint256 => bool)) public isConfirmed; address[] private _proposers = [address(this)]; address[] private _executors = [address(this)]; EnumerableSet.UintSet private _operators; mapping(bytes32 => DataTypes.MicroProposal) private _proposals; constructor( string memory name, string memory description, address membershipTokenAddress, uint256[] memory operators, uint256 timelockDelay ) { NAME = name; DESCRIPTION = description; membership = membershipTokenAddress; share = IMembership(membershipTokenAddress).shareToken(); timelock = new TimelockController(timelockDelay, _proposers, _executors); _updateOperators(operators); } modifier onlyOperator() { if (!_operators.contains(getMembershipTokenId(_msgSender()))) revert Errors.NotOperator(); _; } modifier onlyTimelock() { if (_msgSender() != address(timelock)) revert Errors.NotTimelock(); _; } // @dev Shortcut view methods designed for inherited submodules. function listOperators() public view virtual returns (uint256[] memory) { return _operators.values(); } function getMembershipTokenId(address account) internal view returns (uint256) { return IMembership(membership).tokenOfOwnerByIndex(account, 0); } function getAddressByMemberId(uint256 tokenId) internal view returns (address) { return IMembership(membership).ownerOf(tokenId); } function getProposal(bytes32 id) internal view returns (DataTypes.MicroProposal memory) { return _proposals[id]; } /** * @dev Pull payments * Pull available payments from DAO's treasury contract, * to this module's timelock contract */ function pullPayments( uint256 eth, address[] memory tokens, uint256[] memory amounts ) internal virtual { bool nothingToPull = eth == 0 && tokens.length == 0 && amounts.length == 0; if (!nothingToPull) { ITreasury(IMembership(membership).treasury()).pullModulePayment( eth, tokens, amounts ); } } /** * @dev Propose MicroProposal * Propose a micro-proposal, Use the same algorithm as timelock for hash id */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description, bytes32 referId ) public virtual onlyOperator returns (bytes32 id) { bytes32 _id = timelock.hashOperationBatch( targets, values, calldatas, 0, keccak256(bytes(description)) ); _proposals[_id] = DataTypes.MicroProposal( DataTypes.ProposalStatus.Pending, 0, targets, values, calldatas, description, referId ); emit ModuleProposalCreated( address(this), _id, _msgSender(), block.timestamp ); return _id; } /** * @dev Confirm MicroProposal * Confirm a micro-proposal */ function confirm(bytes32 id) public virtual onlyOperator { if (_proposals[id].status != DataTypes.ProposalStatus.Pending) revert Errors.InvalidProposalStatus(); uint256 _tokenId = getMembershipTokenId(_msgSender()); if (isConfirmed[id][_tokenId]) revert Errors.AlreadyConfirmed(); _proposals[id].confirmations++; isConfirmed[id][_tokenId] = true; emit ModuleProposalConfirmed( address(this), id, _msgSender(), block.timestamp ); } /** * @dev Schedule MicroProposal * schedule a micro-proposal, Requires confirmation from all operators */ function schedule(bytes32 id) public virtual onlyOperator { DataTypes.MicroProposal memory _proposal = _proposals[id]; if (_proposal.status != DataTypes.ProposalStatus.Pending) revert Errors.InvalidProposalStatus(); if (_proposal.confirmations < _operators.length()) revert Errors.NotEnoughConfirmations(); _beforeSchedule(id, _proposal.referId); timelock.scheduleBatch( _proposal.targets, _proposal.values, _proposal.calldatas, 0, keccak256(bytes(_proposal.description)), timelock.getMinDelay() ); _afterSchedule(id, _proposal.referId); _proposals[id].status = DataTypes.ProposalStatus.Scheduled; emit ModuleProposalScheduled( address(this), id, _msgSender(), block.timestamp ); } /** * @dev Execute MicroProposal * execute a micro-proposal, execution can be allowed when the period set by the timelock has expired. * The executor must be the operator. */ function execute(bytes32 id) public virtual onlyOperator { DataTypes.MicroProposal memory _proposal = _proposals[id]; if (_proposal.status != DataTypes.ProposalStatus.Scheduled) revert Errors.InvalidProposalStatus(); _beforeExecute(id, _proposal.referId); timelock.executeBatch( _proposal.targets, _proposal.values, _proposal.calldatas, 0, keccak256(bytes(_proposal.description)) ); _proposals[id].status = DataTypes.ProposalStatus.Executed; emit ModuleProposalExecuted( address(this), id, _msgSender(), block.timestamp ); } /** * @dev Cancel MicroProposal * cancel a micro-proposal, It is not possible to cancel a proposal that has already been executed. * If the proposal is scheduled by the timelock, call the cancel method of the timelock. */ function cancel(bytes32 id) public virtual onlyOperator { DataTypes.MicroProposal memory _proposal = _proposals[id]; if (_proposal.status == DataTypes.ProposalStatus.Executed) revert Errors.InvalidProposalStatus(); if (_proposal.status == DataTypes.ProposalStatus.Scheduled) { timelock.cancel(id); } emit ModuleProposalCancelled( address(this), id, _msgSender(), block.timestamp ); delete _proposals[id]; } function _beforeExecute(bytes32 id, bytes32 referId) internal virtual {} function _beforeSchedule(bytes32 id, bytes32 referId) internal virtual {} function _afterSchedule(bytes32 id, bytes32 referId) internal virtual {} function _updateOperators(uint256[] memory operators_) private { for (uint256 i = 0; i < operators_.length; i++) { _operators.add(operators_[i]); } } }
Shortcut view methods designed for inherited submodules.
function listOperators() public view virtual returns (uint256[] memory) { return _operators.values(); }
1,763,522
./full_match/8453/0xF0363DBD4Efb76fC72Aa4df7D8b956269c9052A6/sources/contracts/scribes/Allowance.sol
getRedeemableTrancheCount This method will determine the number of tranches that are available and solvent for redemption. allowanceId the allowance to introspect return the number of tranches that are available and solvent for payment./ get the allowance likely invalid allowance ID make sure that it is enabled make sure that it is time for a distribution if its exhausted, then the answer is zero return the number of solvent tranches
function getRedeemableTrancheCount(bytes32 allowanceId) public view returns (uint256) { Allowance storage a = allowances[allowanceId]; return getSolventTrancheCount(a); }
11,538,588
/** Etherus presale contract */ pragma solidity ^0.4.21; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; 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 SafeMath * @dev Math operations with safety checks that throw 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 automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @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 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); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @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. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * Mintable token */ contract MintableToken is StandardToken, Ownable { uint public totalSupply = 0; address private minter; bool public mintingEnabled = true; modifier onlyMinter() { require(minter == msg.sender); _; } function setMinter(address _minter) public onlyOwner { minter = _minter; } function mint(address _to, uint _amount) public onlyMinter { require(mintingEnabled); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Transfer(address(0x0), _to, _amount); } function stopMinting() public onlyMinter { mintingEnabled = false; } } contract EtherusPreSale is Ownable { using SafeMath for uint; // Constants // ========= uint private constant fractions = 1e18; uint private constant millions = 1e6*fractions; uint private constant CAP = 15*millions; uint private constant SALE_CAP = 5*millions; uint private constant ETR_USD_PRICE = 400; //in cents uint public ethPrice = 40000; //in cents // Events // ====== event AltBuy(address holder, uint tokens, string txHash); event Buy(address holder, uint tokens); event RunSale(); event PauseSale(); event FinishSale(); event PriceSet(uint USDPerETH); // State variables // =============== MintableToken public token; address authority; //An account to control the contract on behalf of the owner address robot; //An account to purchase tokens for altcoins bool public isOpen = false; // Constructor // =========== function EtherusPreSale(address _token, address _multisig, address _authority, address _robot) public { token = MintableToken(_token); authority = _authority; robot = _robot; transferOwnership(_multisig); } // Public functions // ================ /** * Gets the bonus in percents for the specified sum */ function getBonus(uint ethSum) public view returns (uint){ uint usdSum = ethSum.mul(ethPrice).div(fractions); if(usdSum >= 1e6*100) return 100; if(usdSum >= 5e5*100) return 80; if(usdSum >= 2.5e5*100) return 70; if(usdSum >= 2e5*100) return 60; if(usdSum >= 1.5e5*100) return 50; if(usdSum >= 1.25e5*100) return 40; if(usdSum >= 1e5*100) return 30; if(usdSum >= 7.5e4*100) return 20; if(usdSum >= 5e4*100) return 10; return 0; } /** * Computes number of tokens with bonus for the specified ether. Correctly * adds bonuses if the sum is large enough to belong to several bonus intervals */ function getTokensAmount(uint etherVal) public view returns (uint) { uint bonus = getBonus(etherVal); uint tokens = etherVal.mul(ethPrice).mul(100 + bonus).div(ETR_USD_PRICE*100); return tokens; } function buy(address to) public payable onlyOpen { uint amount = msg.value; uint tokens = getTokensAmountUnderCap(amount); owner.transfer(amount); token.mint(to, tokens); Buy(to, tokens); } function () public payable{ buy(msg.sender); } // Modifiers // ================= modifier onlyAuthority() { require(msg.sender == authority || msg.sender == owner); _; } modifier onlyRobot() { require(msg.sender == robot); _; } modifier onlyOpen() { require(isOpen); _; } // Priveleged functions // ==================== /** * Used to buy tokens for altcoins. * Robot may call it before TokenSale officially starts to migrate early investors */ function buyAlt(address to, uint etherAmount, string _txHash) public onlyRobot { uint tokens = getTokensAmountUnderCap(etherAmount); token.mint(to, tokens); AltBuy(to, tokens, _txHash); } function setAuthority(address _authority) public onlyOwner { authority = _authority; } function setRobot(address _robot) public onlyAuthority { robot = _robot; } function setPrice(uint usdPerEther) public onlyAuthority { //Ether is not expected to rate less than $1 and more than $100000 during presale require(1*100 <= usdPerEther && usdPerEther <= 100000*100); ethPrice = usdPerEther; PriceSet(ethPrice); } // SALE state management: start / pause / finalize // -------------------------------------------- function open(bool _open) public onlyAuthority { isOpen = _open; if (_open) { RunSale(); } else { PauseSale(); } } function finalize() public onlyAuthority { uint diff = CAP.sub(token.totalSupply()); if(diff > 0) //The unsold capacity moves to team token.mint(owner, diff); token.stopMinting(); selfdestruct(owner); FinishSale(); } // Private functions // ========================= /** * Gets tokens for specified ether provided that they are still under the cap */ function getTokensAmountUnderCap(uint etherAmount) private view returns (uint){ uint tokens = getTokensAmount(etherAmount); require(tokens > 0); require(tokens.add(token.totalSupply()) <= SALE_CAP); return tokens; } }
Gets the bonus in percents for the specified sum/
function getBonus(uint ethSum) public view returns (uint){ uint usdSum = ethSum.mul(ethPrice).div(fractions); if(usdSum >= 1e6*100) return 100; if(usdSum >= 5e5*100) return 80; if(usdSum >= 2.5e5*100) return 70; if(usdSum >= 2e5*100) return 60; if(usdSum >= 1.5e5*100) return 50; if(usdSum >= 1.25e5*100) return 40; if(usdSum >= 1e5*100) return 30; if(usdSum >= 7.5e4*100) return 20; if(usdSum >= 5e4*100) return 10; return 0; }
13,038,635
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.9; // code below expects that integer overflows will revert import "./AreaNFT.sol"; import "./RandomDropVending.sol"; import "./Utilities/PlusCodes.sol"; import "./Vendor/openzeppelin-contracts-3dadd40034961d5ca75fa209a4188b01d7129501/access/Ownable.sol"; /// @title Area main contract, 🌐 the earth on the blockchain, 📌 geolocation NFTs /// @notice This contract is responsible for initial allocation and non-fungible tokens. /// ⚠️ Bad things will happen if the reveals do not happen a sufficient amount for more than ~60 minutes. /// @author William Entriken contract Area is Ownable, AreaNFT, RandomDropVending { /// @param inventorySize inventory for code length 4 tokens for sale (normally 43,200) /// @param teamAllocation how many set aside for team /// @param pricePerPack the cost in Wei for each pack /// @param packSize how many drops can be purchased at a time /// @param name ERC721 contract name /// @param symbol ERC721 symbol name /// @param baseURI prefix for all token URIs /// @param priceToSplit value (in Wei) required to split Area tokens constructor( uint256 inventorySize, uint256 teamAllocation, uint256 pricePerPack, uint32 packSize, string memory name, string memory symbol, string memory baseURI, uint256 priceToSplit ) RandomDropVending(inventorySize, teamAllocation, pricePerPack, packSize) AreaNFT(name, symbol, baseURI, priceToSplit) { } /// @notice Start the sale function beginSale() external onlyOwner { _beginSale(); } /// @notice In case of emergency, the number of allocations set aside for the team can be adjusted /// @param teamAllocation the new allocation amount function setTeamAllocation(uint256 teamAllocation) external onlyOwner { _setTeamAllocation(teamAllocation); } /// @notice A quantity of Area tokens that were committed by anybody and are now mature are revealed /// @param revealsLeft up to how many reveals will occur function reveal(uint32 revealsLeft) external onlyOwner { RandomDropVending._reveal(revealsLeft); } /// @notice Takes some of the code length 4 codes that are not near the poles and assigns them. Team is unable to /// take tokens until all other tokens are allocated from sale. /// @param recipient the account that is assigned the tokens /// @param quantity how many to assign function mintTeamAllocation(address recipient, uint256 quantity) external onlyOwner { RandomDropVending._takeTeamAllocation(recipient, quantity); } /// @notice Takes some of the code length 2 codes that are near the poles and assigns them. Team is unable to take /// tokens until all other tokens are allocated from sale. /// @param recipient the account that is assigned the tokens /// @param indexFromOne a number in the closed range [1, 54] function mintWaterAndIceReserve(address recipient, uint256 indexFromOne) external onlyOwner { require(RandomDropVending._inventoryForSale() == 0, "Cannot take during sale"); uint256 tokenId = PlusCodes.getNthCodeLength2CodeNearPoles(indexFromOne); AreaNFT._mint(recipient, tokenId); } /// @notice Pay the bills function withdrawBalance() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /// @dev Convert a Plus Code token ID to an ASCII (and UTF-8) string /// @param plusCode the Plus Code token ID to format /// @return the ASCII (and UTF-8) string showing the Plus Code token ID function tokenIdToString(uint256 plusCode) external pure returns(string memory) { return PlusCodes.toString(plusCode); } /// @dev Convert ASCII string to a Plus Code token ID /// @param stringPlusCode the ASCII (UTF-8) Plus Code token ID /// @return plusCode the Plus Code token ID representing the provided ASCII string function stringToTokenId(string memory stringPlusCode) external pure returns(uint256 plusCode) { return PlusCodes.fromString(stringPlusCode); } /// @inheritdoc RandomDropVending function _revealCallback(address recipient, uint256 allocation) internal override(RandomDropVending) { uint256 tokenId = PlusCodes.getNthCodeLength4CodeNotNearPoles(allocation); AreaNFT._mint(recipient, tokenId); } } // 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: Apache-2.0 pragma solidity 0.8.9; /* Quick reference of valid Plus Codes (full code) formats, where D is some Plus Codes digit * * Code length 2: DD000000+ * Code length 4: DDDD0000+ * Code length 6: DDDDDD00+ * Code length 8: DDDDDDDD+ * Code length 10: DDDDDDDD+DD * Code length 11: DDDDDDDD+DDD * Code length 12: DDDDDDDD+DDDD * Code length 13: DDDDDDDD+DDDDD * Code length 14: DDDDDDDD+DDDDDD * Code length 15: DDDDDDDD+DDDDDDD */ /// @title Part of Area, 🌐 the earth on the blockchain, 📌 geolocation NFTs /// @notice Utilities for working with a subset (upper case and no higher than code length 12) of Plus Codes /// @dev A Plus Code is a character string representing GPS coordinates. See complete specification at /// https://github.com/google/open-location-code. /// We encode this string using ASCII, little endian, into a 256-bit integer. Following is an example code /// length 8 Plus Code: /// String: 2 2 2 2 0 0 0 0 + /// Hex: 0x000000000000000000000000000000000000000000000032323232303030302B /// @author William Entriken library PlusCodes { struct ChildTemplate { uint256 setBits; // Every child is guaranteed to set these bits uint32 childCount; // How many children are there, either 20 or 400 uint32 digitsLocation; // How many bits must the child's significant digit(s) be left-shifted before adding // (oring) to `setBits`? } /// @dev Plus Codes digits use base-20, these are the constituent digits bytes20 private constant _PLUS_CODES_DIGITS = bytes20("23456789CFGHJMPQRVWX"); /// @notice Get the Plus Code at a certain index from the list of all code level 4 Plus Codes which are not near the /// north or south poles /// @dev Code length 4 Plus Codes represent 1 degree latitude by 1 degree longitude. We consider 40 degrees from /// the South Pole and 20 degrees from the North Pole as "near". Therefore 360 × 120 = 43,200 Plus Codes are /// here. /// @param indexFromOne a number in the closed range [1, 43,200] /// @return plusCode the n-th (one-indexed) Plus Code from the alphabetized list of all code length 4 Plus Codes /// which are not "near" a pole function getNthCodeLength4CodeNotNearPoles(uint256 indexFromOne) internal pure returns (uint256 plusCode) { require((indexFromOne >= 1) && (indexFromOne <= 43200), "Out of range"); uint256 indexFromZero = indexFromOne - 1; // In the half-open range [0, 43,200) plusCode = uint256(uint40(bytes5("0000+"))); // 0x000000000000000000000000000000000000000000000000000000303030302B; // Least significant digit can take any of 20 values plusCode |= uint256(uint8(_PLUS_CODES_DIGITS[indexFromZero % 20])) << 8*5; // 0x0000000000000000000000000000000000000000000000000000__303030302B; indexFromZero /= 20; // Next digit can take any of 20 values plusCode |= uint256(uint8(_PLUS_CODES_DIGITS[indexFromZero % 20])) << 8*6; // 0x00000000000000000000000000000000000000000000000000____303030302B; indexFromZero /= 20; // Next digit can take any of 18 values (18 × 20 degrees = 360 degrees) plusCode |= uint256(uint8(_PLUS_CODES_DIGITS[indexFromZero % 18])) << 8*7; // 0x000000000000000000000000000000000000000000000000______303030302B; indexFromZero /= 18; // Most significant digit can be not the lowest 2 nor highest 1 (6 options) plusCode |= uint256(uint8(_PLUS_CODES_DIGITS[2 + indexFromZero])) << 8*8; // 0x0000000000000000000000000000000000000000000000________303030302B; } /// @notice Get the Plus Code at a certain index from the list of all code level 2 Plus Codes which are near the /// north or south poles /// @dev Code length 2 Plus Codes represent 20 degrees latitude by 20 degrees longitude. We consider 40 degrees /// from the South Pole and 20 degrees from the North Pole as "near". Therefore 360 × 60 ÷ 20 ÷ 20 = 54 Plus /// Codes are here. /// @param indexFromOne a number in the closed range [1, 54] /// @return plusCode the n-th (one-indexed) Plus Code from the alphabetized list of all code length 2 Plus Codes /// which are "near" a pole function getNthCodeLength2CodeNearPoles(uint256 indexFromOne) internal pure returns (uint256 plusCode) { require((indexFromOne >= 1) && (indexFromOne <= 54), "Out of range"); uint256 indexFromZero = indexFromOne - 1; // In the half-open range [0, 54) plusCode = uint256(uint56(bytes7("000000+"))); // 0x000000000000000000000000000000000000000000000000003030303030302B; // Least significant digit can take any of 18 values (18 × 20 degrees = 360 degrees) plusCode |= uint256(uint8(_PLUS_CODES_DIGITS[indexFromZero % 18])) << 8*7; // 0x000000000000000000000000000000000000000000000000__3030303030302B; indexFromZero /= 18; // Most significant digit determines latitude if (indexFromZero <= 1) { // indexFromZero ∈ {0, 1}, this is the 40 degrees near South Pole plusCode |= uint256(uint8(_PLUS_CODES_DIGITS[indexFromZero])) << 8*8; // 0x0000000000000000000000000000000000000000000000____3030303030302B; } else { // indexFromZero = 2, this is the 20 degrees near North Pole plusCode |= uint256(uint8(_PLUS_CODES_DIGITS[8])) << 8*8; // 0x000000000000000000000000000000000000000000000043__3030303030302B; } } /// @notice Find the Plus Code representing `childCode` plus some more area if input is a valid Plus Code; otherwise /// revert /// @param childCode a Plus Code /// @return parentCode the Plus Code representing the smallest area which contains the `childCode` area plus some /// additional area function getParent(uint256 childCode) internal pure returns (uint256 parentCode) { uint8 childCodeLength = getCodeLength(childCode); if (childCodeLength == 2) { revert("Code length 2 Plus Codes do not have parents"); } if (childCodeLength == 4) { return childCode & 0xFFFF00000000000000 | 0x3030303030302B; } if (childCodeLength == 6) { return childCode & 0xFFFFFFFF0000000000 | 0x303030302B; } if (childCodeLength == 8) { return childCode & 0xFFFFFFFFFFFF000000 | 0x30302B; } if (childCodeLength == 10) { return childCode >> 8*2; } // childCodeLength ∈ {11, 12} return childCode >> 8*1; } /// @notice Create a template for enumerating Plus Codes that are a portion of `parentCode` if input is a valid Plus /// Code; otherwise revert /// @dev A "child" is a Plus Code representing the largest area which contains some of the `parentCode` area /// minus some area. /// @param parentCode a Plus Code to operate on /// @return childTemplate bit pattern and offsets every child will have function getChildTemplate(uint256 parentCode) internal pure returns (ChildTemplate memory) { uint8 parentCodeLength = getCodeLength(parentCode); if (parentCodeLength == 2) { return ChildTemplate(parentCode & 0xFFFF0000FFFFFFFFFF, 400, 8*5); // DD__0000+ } if (parentCodeLength == 4) { return ChildTemplate(parentCode & 0xFFFFFFFF0000FFFFFF, 400, 8*3); // DDDD__00+ } if (parentCodeLength == 6) { return ChildTemplate(parentCode & 0xFFFFFFFFFFFF0000FF, 400, 8*1); // DDDDDD__+ } if (parentCodeLength == 8) { return ChildTemplate(parentCode << 8*2, 400, 0); // DDDDDDDD+__ } if (parentCodeLength == 10) { return ChildTemplate(parentCode << 8*1, 20, 0); // DDDDDDDD+DD_ } if (parentCodeLength == 11) { return ChildTemplate(parentCode << 8*1, 20, 0); // DDDDDDDD+DDD_ } revert("Plus Codes with code length greater than 12 not supported"); } /// @notice Find a child Plus Code based on a template /// @dev A "child" is a Plus Code representing the largest area which contains some of a "parent" area minus some /// area. /// @param indexFromZero which child (zero-indexed) to generate, must be less than `template.childCount` /// @param template tit pattern and offsets to generate child function getNthChildFromTemplate(uint32 indexFromZero, ChildTemplate memory template) internal pure returns (uint256 childCode) { // This may run in a 400-wide loop (for Transfer events), keep it tight // These bits are guaranteed childCode = template.setBits; // Add rightmost digit uint8 rightmostDigit = uint8(_PLUS_CODES_DIGITS[indexFromZero % 20]); childCode |= uint256(rightmostDigit) << template.digitsLocation; // 0xTEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEML=ATE; // Do we need to add a second digit? if (template.childCount == 400) { uint8 secondDigit = uint8(_PLUS_CODES_DIGITS[indexFromZero / 20]); childCode |= uint256(secondDigit) << (template.digitsLocation + 8*1); // 0xTEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEM==ATE; } } /// @dev Returns 2, 4, 6, 8, 10, 11, or 12 for valid Plus Codes, otherwise reverts /// @param plusCode the Plus Code to format /// @return the code length function getCodeLength(uint256 plusCode) internal pure returns(uint8) { if (bytes1(uint8(plusCode)) == "+") { // Code lengths 2, 4, 6 and 8 are the only ones that end with the format separator (+) and they have exactly // 9 characters. require((plusCode >> 8*9) == 0, "Too many characters in Plus Code"); _requireValidDigit(plusCode, 8); _requireValidDigit(plusCode, 7); require(bytes1(uint8(plusCode >> 8*8)) <= "C", "Beyond North Pole"); require(bytes1(uint8(plusCode >> 8*7)) <= "V", "Beyond antimeridian"); if (bytes7(uint56(plusCode & 0xFFFFFFFFFFFFFF)) == "000000+") { return 2; } _requireValidDigit(plusCode, 6); _requireValidDigit(plusCode, 5); if (bytes5(uint40(plusCode & 0xFFFFFFFFFF)) == "0000+") { return 4; } _requireValidDigit(plusCode, 4); _requireValidDigit(plusCode, 3); if (bytes3(uint24(plusCode & 0xFFFFFF)) == "00+") { return 6; } _requireValidDigit(plusCode, 2); _requireValidDigit(plusCode, 1); return 8; } // Only code lengths 10, 11 and 12 (or more) don't end with a format separator. _requireValidDigit(plusCode, 0); _requireValidDigit(plusCode, 1); if (bytes1(uint8(plusCode >> 8*2)) == "+") { require(getCodeLength(plusCode >> 8*2) == 8, "Invalid before +"); return 10; } _requireValidDigit(plusCode, 2); if (bytes1(uint8(plusCode >> 8*3)) == "+") { require(getCodeLength(plusCode >> 8*3) == 8, "Invalid before +"); return 11; } _requireValidDigit(plusCode, 3); if (bytes1(uint8(plusCode >> 8*4)) == "+") { require(getCodeLength(plusCode >> 8*4) == 8, "Invalid before +"); return 12; } revert("Code lengths greater than 12 are not supported"); } /// @dev Convert a Plus Code to an ASCII (and UTF-8) string /// @param plusCode the Plus Code to format /// @return the ASCII (and UTF-8) string showing the Plus Code function toString(uint256 plusCode) internal pure returns(string memory) { getCodeLength(plusCode); bytes memory retval = new bytes(0); while (plusCode > 0) { retval = abi.encodePacked(uint8(plusCode % 2**8), retval); plusCode >>= 8; } return string(retval); } /// @dev Convert ASCII string to a Plus Code /// @param stringPlusCode the ASCII (UTF-8) Plus Code /// @return plusCode the Plus Code representing the provided ASCII string function fromString(string memory stringPlusCode) internal pure returns(uint256 plusCode) { bytes memory bytesPlusCode = bytes(stringPlusCode); for (uint index=0; index<bytesPlusCode.length; index++) { plusCode = (plusCode << 8) + uint8(bytesPlusCode[index]); } PlusCodes.getCodeLength(plusCode); } /// @dev Reverts if the given byte is not a valid Plus Codes digit function _requireValidDigit(uint256 plusCode, uint8 offsetFromRightmostByte) private pure { uint8 digit = uint8(plusCode >> (8 * offsetFromRightmostByte)); for (uint256 index = 0; index < 20; index++) { if (uint8(_PLUS_CODES_DIGITS[index]) == digit) { return; } } revert("Not a valid Plus Codes digit"); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.9; // code below expects that integer overflows will revert import "./Utilities/LazyArray.sol"; import "./Utilities/PlusCodes.sol"; import "./Utilities/CommitQueue.sol"; /// @title Area commit-reveal drop contract, 🌐 the earth on the blockchain, 📌 geolocation NFTs /// @notice This contract assigns all code length 4 Plus Codes to participants with randomness provided by a /// commit-reveal mechanism. ⚠️ Bad things will happen if the reveals do not happen a sufficient amount for more /// than ~60 minutes. /// @dev Each commit must be revealed (by the next committer or a benevolent revealer) to ensure that the intended /// randomness for that, and subsequent, commits are used. /// @author William Entriken abstract contract RandomDropVending { using CommitQueue for CommitQueue.Self; CommitQueue.Self private _commitQueue; using LazyArray for LazyArray.Self; LazyArray.Self private _dropInventoryIntegers; uint256 private immutable _pricePerPack; uint32 private immutable _packSize; bool private _saleDidNotBeginYet; uint256 private _teamAllocation; /// @notice Some code length 4 Plus Codes were purchased, but not yet revealed /// @param buyer who purchased /// @param quantity how many were purchased event Purchased(address buyer, uint32 quantity); /// @param inventorySize integers [1, quantity] are available /// @param teamAllocation_ how many set aside for team /// @param pricePerPack_ the cost in Wei for each pack /// @param packSize_ how many drops can be purchased at a time constructor(uint256 inventorySize, uint256 teamAllocation_, uint256 pricePerPack_, uint32 packSize_) { require((inventorySize - teamAllocation_) % packSize_ == 0, "Pack size must evenly divide sale quantity"); require(inventorySize > teamAllocation_, "None for sale, no fun"); _dropInventoryIntegers.initialize(inventorySize); _teamAllocation = teamAllocation_; _pricePerPack = pricePerPack_; _packSize = packSize_; _saleDidNotBeginYet = true; } /// @notice A quantity of code length 4 Areas are committed for the benefit of the message sender, to be revealed /// soon later. And a quantity of code length 4 Areas that were committed by anybody and are now mature are /// revealed. /// @dev ⚠️ If a commitment is made and is mature more than ~60 minutes without being revealed, then assignment /// will use randomness from the then-current block hash, rather than the intended block hash. /// @param benevolence how many reveals will be attempted in addition to the number of commits function purchaseTokensAndReveal(uint32 benevolence) external payable { require(msg.value == _pricePerPack, "Did not send correct Ether amount"); require(_inventoryForSale() >= _packSize, "Sold out"); require(msg.sender == tx.origin, "Only externally-owned accounts are eligible to purchase"); require(_saleDidNotBeginYet == false, "The sale did not begin yet"); _commit(); _reveal(_packSize + benevolence); // overflow reverts } /// @notice Important numbers about the drop /// @return inventoryForSale how many more can be committed for sale /// @return queueCount how many were committed but not yet revealed /// @return setAside how many are remaining for team to claim function dropStatistics() external view returns (uint256 inventoryForSale, uint256 queueCount, uint256 setAside) { return ( _inventoryForSale(), _commitQueue.count(), _teamAllocation <= _dropInventoryIntegers.count() ? _teamAllocation : _dropInventoryIntegers.count() ); } /// @notice Start the sale function _beginSale() internal { _saleDidNotBeginYet = false; } /// @notice In case of emergency, the number of allocations set aside for the team can be adjusted /// @param teamAllocation_ the new allocation amount function _setTeamAllocation(uint256 teamAllocation_) internal { _teamAllocation = teamAllocation_; } /// @notice A quantity of integers that were committed by anybody and are now mature are revealed /// @param revealsLeft up to how many reveals will occur function _reveal(uint32 revealsLeft) internal { for (; revealsLeft > 0 && _commitQueue.isMature(); revealsLeft--) { // Get one from queue address recipient; uint64 maturityBlock; (recipient, maturityBlock) = _commitQueue.dequeue(); // Allocate randomly uint256 randomNumber = _random(maturityBlock); uint256 randomIndex = randomNumber % _dropInventoryIntegers.count(); uint allocatedNumber = _dropInventoryIntegers.popByIndex(randomIndex); _revealCallback(recipient, allocatedNumber); } } /// @dev This callback triggers when some drop is revealed. /// @param recipient the beneficiary of the drop /// @param allocation which number was dropped function _revealCallback(address recipient, uint256 allocation) internal virtual; /// @notice Takes some integers (not randomly) in inventory and assigns them. Team does not get tokens until all /// other integers are allocated. /// @param recipient the account that is assigned the integers /// @param quantity how many integers to assign function _takeTeamAllocation(address recipient, uint256 quantity) internal { require(_inventoryForSale() == 0, "Cannot take during sale"); require(quantity <= _dropInventoryIntegers.count(), "Not enough to take"); for (; quantity > 0; quantity--) { uint256 lastIndex = _dropInventoryIntegers.count() - 1; uint256 allocatedNumber = _dropInventoryIntegers.popByIndex(lastIndex); _revealCallback(recipient, allocatedNumber); } } /// @dev Get a random number based on the given block's hash; or some other hash if not available function _random(uint256 blockNumber) internal view returns (uint256) { // Blockhash produces non-zero values only for the input range [block.number - 256, block.number - 1] if (blockhash(blockNumber) != 0) { return uint256(blockhash(blockNumber)); } return uint256(blockhash(((block.number - 1)>>8)<<8)); } /// @notice How many more can be committed for sale function _inventoryForSale() internal view returns (uint256) { uint256 inventoryAvailable = _commitQueue.count() >= _dropInventoryIntegers.count() ? 0 : _dropInventoryIntegers.count() - _commitQueue.count(); return _teamAllocation >= inventoryAvailable ? 0 : inventoryAvailable - _teamAllocation; } /// @notice A quantity of integers are committed for the benefit of the message sender, to be revealed soon later. /// @dev ⚠️ If a commitment is made and is mature more than ~60 minutes without being revealed, then assignment /// will use randomness from the then-current block hash, rather than the intended block hash. function _commit() private { _commitQueue.enqueue(msg.sender, _packSize); emit Purchased(msg.sender, _packSize); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.9; // code below expects that integer overflows will revert import "./Vendor/openzeppelin-contracts-3dadd40034961d5ca75fa209a4188b01d7129501/token/ERC721/ERC721.sol"; import "./Vendor/openzeppelin-contracts-3dadd40034961d5ca75fa209a4188b01d7129501/access/Ownable.sol"; import "./Utilities/PlusCodes.sol"; /// @title Area NFT contract, 🌐 the earth on the blockchain, 📌 geolocation NFTs /// @notice This implementation adds features to the baseline ERC-721 standard: /// - groups of tokens (siblings) are stored efficiently /// - tokens can be split /// @dev This builds on the OpenZeppelin Contracts implementation /// @author William Entriken abstract contract AreaNFT is ERC721, Ownable { // The prefix for all token URIs string internal _baseTokenURI; // Mapping from token ID to owner address mapping(uint256 => address) private _explicitOwners; // Mapping from token ID to owner address, if a token is split mapping(uint256 => address) private _splitOwners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Price to split an area in Wei uint256 private _priceToSplit; /// @dev Contract constructor /// @param name_ ERC721 contract name /// @param symbol_ ERC721 symbol name /// @param baseURI prefix for all token URIs /// @param priceToSplit_ value (in Wei) required to split Area tokens constructor(string memory name_, string memory symbol_, string memory baseURI, uint256 priceToSplit_) ERC721(name_, symbol_) { _baseTokenURI = baseURI; _priceToSplit = priceToSplit_; } /// @notice The owner of an Area Token can irrevocably split it into Plus Codes at one greater level of precision. /// @dev This is the only function with burn functionality. The newly minted tokens do not cause a call to /// onERC721Received on the recipient. /// @param tokenId the token that will be split function split(uint256 tokenId) external payable { require(msg.value == _priceToSplit, "Did not send correct Ether amount"); require(_msgSender() == ownerOf(tokenId), "AreaNFT: split caller is not owner"); _burn(tokenId); // Split. This causes our ownerOf(childTokenId) to return the owner _splitOwners[tokenId] = _msgSender(); // Ghost mint the child tokens // Ghost mint (verb): create N tokens on-chain (i.e. ownerOf returns something) without using N storage slots PlusCodes.ChildTemplate memory template = PlusCodes.getChildTemplate(tokenId); _balances[_msgSender()] += template.childCount; // Solidity 0.8+ for (uint32 index = 0; index < template.childCount; index++) { uint256 childTokenId = PlusCodes.getNthChildFromTemplate(index, template); emit Transfer(address(0), _msgSender(), childTokenId); } } /// @notice Update the price to split Area tokens /// @param newPrice value (in Wei) required to split Area tokens function setPriceToSplit(uint256 newPrice) external onlyOwner { _priceToSplit = newPrice; } /// @notice Update the base URI for token metadata /// @dev All data you need is on-chain via token ID, and metadata is real world data. This Base URI is completely /// optional and is only here to facilitate serving to marketplaces. /// @param baseURI the new URI to prepend to all token URIs function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } /// @inheritdoc ERC721 function approve(address to, uint256 tokenId) public virtual override { address owner = 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); } /// @inheritdoc ERC721 function ownerOf(uint256 tokenId) public view override returns (address owner) { owner = _explicitOwners[tokenId]; if (owner != address(0)) { return owner; } require(_splitOwners[tokenId] == address(0), "AreaNFT: owner query for invalid (split) token"); uint256 parentTokenId = PlusCodes.getParent(tokenId); owner = _splitOwners[parentTokenId]; if (owner != address(0)) { return owner; } revert("ERC721: owner query for nonexistent token"); } /// @inheritdoc ERC721 /// @dev We must override because we need to access the derived `_tokenApprovals` variable that is set by the /// derived`_approved`. function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /// @inheritdoc ERC721 function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /// @inheritdoc ERC721 function _burn(uint256 tokenId) internal virtual override { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _explicitOwners[tokenId]; emit Transfer(owner, address(0), tokenId); } /// @inheritdoc ERC721 function _transfer(address from, address to, uint256 tokenId) internal virtual override { require(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; _explicitOwners[tokenId] = to; emit Transfer(from, to, tokenId); } /// @inheritdoc ERC721 /// @dev We must override because we need the derived `ownerOf` function. function _approve(address to, uint256 tokenId) internal virtual override { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /// @inheritdoc ERC721 function _mint(address to, uint256 tokenId) internal virtual override { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); require(_splitOwners[tokenId] == address(0), "AreaNFT: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _explicitOwners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /// @inheritdoc ERC721 function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual override returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /// @inheritdoc ERC721 function _exists(uint256 tokenId) internal view virtual override returns (bool) { address owner; owner = _explicitOwners[tokenId]; if (owner != address(0)) { return true; } if (_splitOwners[tokenId] != address(0)) { // query for invalid (split) token return false; } if (PlusCodes.getCodeLength(tokenId) > 2) { // It has a parent; This throws if it's not a valid plus code. uint256 parentTokenId = PlusCodes.getParent(tokenId); owner = _splitOwners[parentTokenId]; if (owner != address(0)) { return true; } } return false; } /// @inheritdoc ERC721 function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.9; // code below expects that integer overflows will revert /// @title Part of Area, 🌐 the earth on the blockchain, 📌 geolocation NFTs /// @notice A multi-queue data structure for commits that are waiting to be revealed /// @author William Entriken library CommitQueue { struct Self { // Storage of all elements mapping(uint256 => Element) elements; // The position of the first element if queue is not empty uint32 startIndex; // The queue’s “past the end” position, i.e. one greater than the last valid subscript argument uint32 endIndex; // How many items (sum of Element.quantity) are in the queue uint256 length; } struct Element { // These sizes are chosen to fit in one EVM word address beneficiary; uint64 maturityBlock; uint32 quantity; // this must be greater than zero } /// @notice Adds a new entry to the end of the queue /// @param self the data structure /// @param beneficiary an address associated with the commitment /// @param quantity how many to enqueue function enqueue(Self storage self, address beneficiary, uint32 quantity) internal { require(quantity > 0, "Quantity is missing"); self.elements[self.endIndex] = Element( beneficiary, uint64(block.number), // maturityBlock, hash thereof not yet known quantity ); self.endIndex += 1; self.length += quantity; } /// @notice Removes and returns the first element of the multi-queue; reverts if queue is empty /// @param self the data structure /// @return beneficiary an address associated with the commitment /// @return maturityBlock when this commitment matured function dequeue(Self storage self) internal returns (address beneficiary, uint64 maturityBlock) { require(!_isEmpty(self), "Queue is empty"); beneficiary = self.elements[self.startIndex].beneficiary; maturityBlock = self.elements[self.startIndex].maturityBlock; if (self.elements[self.startIndex].quantity == 1) { delete self.elements[self.startIndex]; self.startIndex += 1; } else { self.elements[self.startIndex].quantity -= 1; } self.length -= 1; } /// @notice Checks whether the first element can be revealed /// @dev Elements are added to the queue in order, so if the first element is not mature than neither are all /// remaining elements. /// @param self the data structure /// @return true if the first element exists and is mature; false otherwise function isMature(Self storage self) internal view returns (bool) { if (_isEmpty(self)) { return false; } return block.number > self.elements[self.startIndex].maturityBlock; } /// @notice Finds how many items are remaining to be dequeued /// @dev This is the sum of Element.quantity. /// @param self the data structure /// @return how many items are in the queue (i.e. how many dequeues can happen) function count(Self storage self) internal view returns (uint256) { return self.length; } /// @notice Whether or not the queue is empty /// @param self the data structure /// @return true if the queue is empty; false otherwise function _isEmpty(Self storage self) private view returns (bool) { return self.startIndex == self.endIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.9; // code below expects that integer overflows will revert /// @title Part of Area, 🌐 the earth on the blockchain, 📌 geolocation NFTs /// @notice A data structure that supports random read and delete access and that efficiently initializes to a range of /// [1, N] /// @author William Entriken library LazyArray { struct Self { // This stores element values and cannot represent an underlying value of zero. // // A zero value at index i represents an element of (i+1). Any other value stored in the array represents an // element of that value. We employ this technique because all storage in Solidity starts at zero. // // e.g. the array [0, 135, 243, 0, 500] represents the values [1, 135, 243, 5, 500]. Then if we remove the 135 // that becomes [0, 500, 243, 0] which represents the values [1, 500, 243, 5]. mapping(uint256 => uint256) elements; // Adding to this value logically appends a sequence to the array ending in `length`. E.g. changing from 0 to 2 // makes [1, 2]. uint256 length; } /// @notice Sets the logical contents to a range of [1, N]. Setting near 2**(256-DIFFICULTY) creates a security /// vulnerability. /// @param self the data structure /// @param initialLength how big to make the range function initialize(Self storage self, uint256 initialLength) internal { require(self.length == 0, "Cannot initialize non-empty structure"); self.length = initialLength; } /// @notice Removes and returns the n-th logical element /// @param self the data structure /// @param index which element (zero indexed) to remove and return /// @return popped the specified element function popByIndex(Self storage self, uint256 index) internal returns (uint256 popped) { popped = getByIndex(self, index); uint256 lastIndex = self.length - 1; // will not underflow b/c prior get if (index < lastIndex) { uint256 lastElement = getByIndex(self, lastIndex); self.elements[index] = lastElement; } delete self.elements[lastIndex]; self.length -= 1; } /// @notice Returns the n-th logical element /// @param self the data structure /// @param index which element (zero indexed) to get /// @return element the specified element function getByIndex(Self storage self, uint256 index) internal view returns (uint256 element) { require(index < self.length, "Out of bounds"); return self.elements[index] == 0 ? index + 1 // revert on overflow : self.elements[index]; } /// @notice Finds how many items remain /// @param self the data structure /// @return the number of remaining items function count(Self storage self) internal view returns (uint256) { return self.length; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); }
Start the sale
function beginSale() external onlyOwner { _beginSale(); }
1,464,325
./full_match/1/0x1403773b2fBada61CE1ebD051DA0AB80dE5A1166/sources/Bebe.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Bebe", "Bebe") { 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 = 10; uint256 _buyDevFee = 20; uint256 _sellMarketingFee = 15; uint256 _sellDevFee = 20; uint256 totalSupply = 900_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(marketingWallet, true); excludeFromFees(devWallet, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(marketingWallet, true); excludeFromMaxTransaction(devWallet, 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);
2,972,386
./full_match/80001/0x7bf7b603a46d57b23d4b94696C53f99CDaC404d0/sources/contracts/extension/Drop.sol
Returns the claim condition at the given uid.
function getClaimConditionById(uint256 _conditionId) external view returns (ClaimCondition memory condition) { condition = claimCondition.conditions[_conditionId]; }
5,597,175
./full_match/1/0xE517aa81408236CF3Fd1170b708741614BeCB631/sources/Users/qijunlin/MyWorkSpace/SolidityWorkSpace/gamer_truffle/contracts/token/GAMERGovernance.sol
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, "GAMER::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; }
4,854,125
pragma solidity ^0.4.23; // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @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); } // File: node_modules/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: node_modules/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: node_modules/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @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 ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. 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, ERC20 _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 ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // 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 Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @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.transfer(_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 for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @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); } } // File: node_modules/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. */ 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: node_modules/openzeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/utils/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev Withdraw tokens only after crowdsale ends. */ function withdrawTokens() public { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } // File: node_modules/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() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts/crowdsale/OraclizeContractInterface.sol /** * @title OraclizeContractInterface * @dev OraclizeContractInterface **/ contract OraclizeContractInterface { function finalize() public; function buyTokensWithLTC(address _ethWallet, string _ltcWallet, uint256 _ltcAmount) public; function buyTokensWithBTC(address _ethWallet, string _btcWallet, uint256 _btcAmount) public; function buyTokensWithBNB(address _ethWallet, string _bnbWallet, uint256 _bnbAmount) public payable; function buyTokensWithBCH(address _ethWallet, string _bchWallet, uint256 _bchAmount) public payable; function getMultiCurrencyInvestorContribution(string _currencyWallet) public view returns(uint256); } // File: contracts/crowdsale/BurnableTokenInterface.sol /** * @title BurnableTokenInterface, defining one single function to burn tokens. * @dev BurnableTokenInterface **/ contract BurnableTokenInterface { /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public; } // File: installed_contracts/oraclize-api/contracts/usingOraclize.sol // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD 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. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> // File: contracts/crowdsale/FiatContractInterface.sol /** * @title FiatContractInterface, defining one single function to get 0,01 $ price. * @dev FiatContractInterface **/ contract FiatContractInterface { function USD(uint _id) view public returns (uint256); } // File: contracts/utils/strings.sol /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.4.14; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } // File: contracts/crowdsale/MultiCurrencyRates.sol /** * @title MultiCurrencyRates * @dev MultiCurrencyRates */ // solium-disable-next-line max-len contract MultiCurrencyRates is usingOraclize, Ownable { using SafeMath for uint256; using strings for *; FiatContractInterface public fiatContract; /** * @param _fiatContract Address of fiatContract */ constructor(address _fiatContract) public { require(_fiatContract != address(0)); fiatContract = FiatContractInterface(_fiatContract); } /** * @dev Set fiat contract * @param _fiatContract Address of new fiatContract */ function setFiatContract(address _fiatContract) public onlyOwner { fiatContract = FiatContractInterface(_fiatContract); } /** * @dev Returns the current 0.01$ => ETH wei rate */ function getUSDCentToWeiRate() internal view returns (uint256) { return fiatContract.USD(0); } /** * @dev Returns the current 0.01$ => BTC satoshi rate */ function getUSDCentToBTCSatoshiRate() internal view returns (uint256) { return fiatContract.USD(1); } /** * @dev Returns the current 0.01$ => LTC satoshi rate */ function getUSDCentToLTCSatoshiRate() internal view returns (uint256) { return fiatContract.USD(2); } /** * @dev Returns the current BNB => 0.01$ rate */ function getBNBToUSDCentRate(string oraclizeResult) internal pure returns (uint256) { return parseInt(parseCurrencyRate(oraclizeResult, "BNB"), 2); } /** * @dev Returns the current BCH => 0.01$ rate */ function getBCHToUSDCentRate(string oraclizeResult) internal pure returns (uint256) { return parseInt(parseCurrencyRate(oraclizeResult, "BCH"), 2); } /** * @dev Parse currency rate from oraclize response * @param oraclizeResult Result from Oraclize with currencies prices * @param _currencyTicker Currency tiker * @return Currency price string in USD */ function parseCurrencyRate(string oraclizeResult, string _currencyTicker) internal pure returns(string) { strings.slice memory response = oraclizeResult.toSlice(); strings.slice memory needle = _currencyTicker.toSlice(); strings.slice memory tickerPrice = response.find(needle).split("}".toSlice()).find(" ".toSlice()).rsplit(" ".toSlice()); return tickerPrice.toString(); } } // File: contracts/crowdsale/PhaseCrowdsaleInterface.sol /** * @title PhaseCrowdsaleInterface * @dev PhaseCrowdsaleInterface */ contract PhaseCrowdsaleInterface { /** * @dev Get phase number depending on the current time */ function getPhaseNumber() public view returns (uint256); /** * @dev Returns the current token price in $ cents depending on the current time */ function getCurrentTokenPriceInCents() public view returns (uint256); /** * @dev Returns the token sale bonus percentage depending on the current time */ function getCurrentBonusPercentage() public view returns (uint256); } // File: contracts/crowdsale/CryptonityCrowdsale.sol /** * @title CryptonityCrowdsale * @dev CryptonityCrowdsale */ // solium-disable-next-line max-len contract CryptonityCrowdsale is TimedCrowdsale, WhitelistedCrowdsale, RefundableCrowdsale, PostDeliveryCrowdsale, MultiCurrencyRates, Pausable { using SafeMath for uint256; OraclizeContractInterface public oraclizeContract; PhaseCrowdsaleInterface public phaseCrowdsale; // Public supply of token uint256 public publicSupply = 60000000 * 1 ether; // Remaining public supply of token for each phase uint256[3] public remainingPublicSupplyPerPhase = [15000000 * 1 ether, 26000000 * 1 ether, 19000000 * 1 ether]; // When tokens will be available for withdraw uint256 public deliveryTime; // A limit for total contributions in USD cents uint256 public cap; // Is goal reached bool public isGoalReached = false; event LogInfo(string description); /** * @param _phasesTime Crowdsale phases time [openingTime, closingTime, secondPhaseStartTime, thirdPhaseStartTime] * @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 * @param _softCapUSDInCents Funding goal in USD cents * @param _hardCapUSDInCents Max amount of USD cents to be contributed * @param _fiatContract FiatContract * @param _phaseCrowdsale info about current phase * @param _oraclizeContract oraclize contract */ constructor( uint256[4] _phasesTime, uint256 _rate, address _wallet, ERC20 _token, uint256 _softCapUSDInCents, uint256 _hardCapUSDInCents, address _fiatContract, address _phaseCrowdsale, address _oraclizeContract ) public Crowdsale(_rate, _wallet, _token) RefundableCrowdsale(_softCapUSDInCents) TimedCrowdsale(_phasesTime[0], _phasesTime[1]) MultiCurrencyRates(_fiatContract) { require(_phasesTime[2] >= _phasesTime[0]); require(_phasesTime[3] >= _phasesTime[2]); require(_phasesTime[1] >= _phasesTime[3]); require(_hardCapUSDInCents > 0); require(_softCapUSDInCents <= _hardCapUSDInCents); cap = _hardCapUSDInCents; // token delivery starts 15 days after the crowdsale ends deliveryTime = _phasesTime[1].add(15 days); oraclizeContract = OraclizeContractInterface(_oraclizeContract); phaseCrowdsale = PhaseCrowdsaleInterface(_phaseCrowdsale); } /** * @dev Reverts if crowdsale is not finalized */ modifier whenFinalized { require(isFinalized); _; } /** * @dev Reverts if caller isn't oraclizeContract */ modifier onlyOraclize { require(msg.sender == address(oraclizeContract)); _; } /** * @dev Get multi currency investor contribution. * @param _currencyWallet Address of currency wallet * @return Amount of currency contribution */ function getMultiCurrencyInvestorContribution(string _currencyWallet) public view returns(uint256) { return oraclizeContract.getMultiCurrencyInvestorContribution(_currencyWallet); } /** * @dev Calculates the sum amount of tokens which were unsold or remaining during all crowdsale phases. * @return The total amount of unsold tokens */ function calculateTotalRemainingPublicSupply() private view returns (uint256) { uint256 totalRemainingPublicSupply = 0; for (uint i = 0; i < remainingPublicSupplyPerPhase.length; i++) { totalRemainingPublicSupply = totalRemainingPublicSupply.add(remainingPublicSupplyPerPhase[i]); } return totalRemainingPublicSupply; } /** * @dev Validation of an incoming purchase. Allowas purchases only when crowdsale is not paused. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { super._preValidatePurchase(_beneficiary, _weiAmount); rate = uint256(1 ether).mul(1 ether).div(getUSDCentToWeiRate()).div(phaseCrowdsale.getCurrentTokenPriceInCents()); } /** * @dev Executed by oraclize when a purchase has been validated and is ready to be executed. * It computes the bonus. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function processPurchase(address _beneficiary, uint256 _tokenAmount) public onlyOraclize onlyWhileOpen isWhitelisted(_beneficiary) { _processPurchase(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * It computes the bonus. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { uint256 totalAmount = _tokenAmount; uint256 bonusPercent = phaseCrowdsale.getCurrentBonusPercentage(); if (bonusPercent > 0) { uint256 bonusAmount = totalAmount.mul(bonusPercent).div(100); // tokens * bonus (%) / 100% totalAmount = totalAmount.add(bonusAmount); } uint256 phaseNumber = phaseCrowdsale.getPhaseNumber(); require(remainingPublicSupplyPerPhase[phaseNumber] >= totalAmount); super._processPurchase(_beneficiary, totalAmount); remainingPublicSupplyPerPhase[phaseNumber] = remainingPublicSupplyPerPhase[phaseNumber].sub(totalAmount); } /** * @dev Withdraw tokens only after the deliveryTime */ function withdrawTokens() public whenFinalized { require(isGoalReached); // solium-disable-next-line security/no-block-members require(now > deliveryTime); super.withdrawTokens(); } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public whenFinalized { require(!isGoalReached); vault.refund(msg.sender); } /** * @dev Token purchase with LTC * @param _ethWallet Address receiving the tokens * @param _ltcWallet LTC address who paid for the tokens * @param _ltcAmount Value in LTC involved in the purchase */ function buyTokensWithLTC(address _ethWallet, string _ltcWallet, uint256 _ltcAmount) public onlyOwner { oraclizeContract.buyTokensWithLTC(_ethWallet, _ltcWallet, _ltcAmount); } /** * @dev Token purchase with BTC * @param _ethWallet Address receiving the tokens * @param _btcWallet BTC address who paid for the tokens * @param _btcAmount Value in BTC involved in the purchase */ function buyTokensWithBTC(address _ethWallet, string _btcWallet, uint256 _btcAmount) public onlyOwner { oraclizeContract.buyTokensWithBTC(_ethWallet, _btcWallet, _btcAmount); } /** * @dev Token purchase with BNB * @param _ethWallet Address receiving the tokens * @param _bnbWallet BNB address who paid for the tokens * @param _bnbAmount Value in BNB involved in the purchase */ function buyTokensWithBNB(address _ethWallet, string _bnbWallet, uint256 _bnbAmount) public payable onlyOwner { oraclizeContract.buyTokensWithBNB.value(msg.value)(_ethWallet, _bnbWallet, _bnbAmount); } /** * @dev Token purchase with BCH * @param _ethWallet Address receiving the tokens * @param _bchWallet BCH address who paid for the tokens * @param _bchAmount Value in BCH involved in the purchase */ function buyTokensWithBCH(address _ethWallet, string _bchWallet, uint256 _bchAmount) public payable onlyOwner { oraclizeContract.buyTokensWithBCH.value(msg.value)(_ethWallet, _bchWallet, _bchAmount); } /** * @dev 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).div(1 ether); // divisor 10^18 to nullify multiplier from _calculateCurrentRate } /** * @dev Finalization logic. * Burn the remaining tokens. * Transfer token ownership to contract owner. */ function finalization() internal { oraclizeContract.finalize(); } /** * @dev Executed by oraclize when multicurrency finalization is calculated * @param _usdRaised usdCent reised with multicurrency */ function finalizationCallback(uint256 _usdRaised) public onlyOraclize { uint256 usdRaised = weiRaised.div(getUSDCentToWeiRate()).add(_usdRaised); if(usdRaised >= goal) { emit LogInfo("Finalization completed"); isGoalReached = true; vault.close(); } else { emit LogInfo("Finalization failed"); vault.enableRefunds(); } uint256 totalRemainingPublicSupply = calculateTotalRemainingPublicSupply(); if (totalRemainingPublicSupply > 0) { BurnableTokenInterface(address(token)).burn(totalRemainingPublicSupply); delete remainingPublicSupplyPerPhase; } Ownable(address(token)).transferOwnership(owner); } }
Finalization logic. Burn the remaining tokens. Transfer token ownership to contract owner./
function finalization() internal { oraclizeContract.finalize(); }
14,097,002
/* Copyright (c) 2019 WhaleChat 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. */ pragma solidity 0.4.25; /// @title Cashier contract /// @dev This is an ERC721-compliant contract whose tokens, called "tickets", allow their buyer to display a /// message in the whales-only rooms in the WhaleChat app. These messages can be used to advertise services. /// Only the the `owner` address of this contract can issue new tickets. The owner of this contract is a /// multisig contract controlled by the WhaleChat token holders. Anybody can buy a ticket. The revenue earned /// from selling tickets is distributed among WhaleChat token holders proportionally to their share /// share of the total token supply. This contract is upgradeable. import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "../node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; import "./Upgradeable.sol"; import "./WcToken.sol"; contract Cashier is ERC721, Ownable, Upgradeable { using SafeMath for uint256; uint256 public constant MAX_MESSAGE_LENGTH = 64; struct Ticket { uint256 numBlocksExpiry; uint256 sellingPrice; string message; uint256 expiryBlock; } mapping(uint256 => Ticket) public tickets; mapping(uint256 => address) public ticketOwner; uint256 public numTickets; WcToken public token; uint256 public cashEarnedSinceLastUpdate; mapping(address => uint256) public withdrawableCash; mapping(address => bool) public withdrawn; event TicketIssued(uint256 indexed ticketId, uint256 numBlocksExpiry, uint256 sellingPrice); event TicketBought(uint256 indexed ticketId, address indexed buyer, uint256 expiryBlock, string message); event TokenDistributionUpdated(); event CashWithdrawn(address withdrawer); constructor(WcToken _token) public { token = _token; } // @dev Issues a new ticket. This function can be called only by the contract owner. // This function is disabled after contract is upgraded. // @param _numBlocksExpiry Number of blocks since the ticket purchase until the ticket with be valid. // @param _sellingPrice The ticket selling price. function issueTicket(uint256 _numBlocksExpiry, uint256 _sellingPrice) external onlyOwner notUpgraded returns (uint256 ticketId) { require(_numBlocksExpiry > 0, "Expiry cannot be zero"); require(_sellingPrice > 0, "Price cannot be zero"); Ticket memory ticket = Ticket({ numBlocksExpiry: _numBlocksExpiry, sellingPrice: _sellingPrice, message: "", expiryBlock: 0 }); ticketId = numTickets; tickets[ticketId] = ticket; numTickets++; emit TicketIssued(ticketId, _numBlocksExpiry, _sellingPrice); return ticketId; } // @dev A ticket is purchased by the caller of this function, which can be anyone. // This function is disabled after contract is upgraded. // @param _ticketId The id of the ticket to be bought. // @param _message The purcharser of this ticket can display a message (e.g. and advertisement) // in the app for other users to read. The message maximum length is MAX_MESSAGE_LENGTH. function buyTicket(uint256 _ticketId, string _message) external payable notUpgraded { require(tickets[_ticketId].numBlocksExpiry != 0, "Invalid ticketId"); require(!_exists(_ticketId), "Ticket was already sold"); require(msg.value == tickets[_ticketId].sellingPrice, "Invalid ticket price"); require(bytes(_message).length < MAX_MESSAGE_LENGTH, "Message is too long"); tickets[_ticketId].expiryBlock = block.number.add(tickets[_ticketId].numBlocksExpiry); tickets[_ticketId].message = _message; _mint(msg.sender, _ticketId); cashEarnedSinceLastUpdate = cashEarnedSinceLastUpdate.add(msg.value); emit TicketBought(_ticketId, msg.sender, tickets[_ticketId].expiryBlock, _message); } // @dev Returns whether or not a ticket is valid. A valid becomes invalid if it was created and it // has not expired yet. // This function is disabled after contract is upgraded. // @param _ticketId The id of the ticket. // @return Whether or not a ticket is valid. function isTicketValid(uint256 _ticketId) external view notUpgraded returns (bool) { require(_exists(_ticketId), "Unknow ticketId"); return block.number < tickets[_ticketId].expiryBlock; } // @dev Returns number of ether a token holder is eligible to withdraw. // If the token distribution has been changed, the function updateTokenDistribution() needs to be called // prior to this to reflect those changes. // This function is disabled after contract is upgraded. // @param _tokenHolder The token holder address. // @return Number of ether. function getWithdrawableCash(address _tokenHolder) external view notUpgraded returns (uint256) { return withdrawableCash[_tokenHolder]; } // @dev Withdraws the corresponding ether to the token holder calling this function. // If the token distribution has been changed, the function updateTokenDistribution() needs to be called // prior to this to reflect those changes. // This function is disabled after contract is upgraded. function withdrawCash() external notUpgraded { require(!withdrawn[msg.sender]); // stop re-entrancy attack withdrawn[msg.sender] = true; msg.sender.transfer(withdrawableCash[msg.sender]); withdrawableCash[msg.sender] = 0; emit CashWithdrawn(msg.sender); } // @dev Updates the token distribution and the withdrawable amounts for a correct earnings distribution. // This function needs to be called before calling `withdrawCash()` and after the token distribution // has been changed. // This function is disabled after contract is upgraded. function updateTokenDistribution() external notUpgraded { uint256 tokenTotalSupply = token.totalSupply(); address[] memory tokenHolders = token.holders(); for (uint256 i = 0; i < tokenHolders.length; i++) { address tokenHolder = tokenHolders[i]; withdrawableCash[tokenHolder] = withdrawableCash[tokenHolder].add( cashEarnedSinceLastUpdate.mul(token.balanceOf(tokenHolder)).div(tokenTotalSupply) ); withdrawn[tokenHolder] = false; } cashEarnedSinceLastUpdate = 0; emit TokenDistributionUpdated(); } }
Returns number of ether a token holder is eligible to withdraw. If the token distribution has been changed, the function updateTokenDistribution() needs to be called prior to this to reflect those changes. This function is disabled after contract is upgraded. _tokenHolder The token holder address. return Number of ether.
function getWithdrawableCash(address _tokenHolder) external view notUpgraded returns (uint256) { return withdrawableCash[_tokenHolder]; }
12,831,862
./partial_match/97/0x99E3c34221A8825BFb44DAE12Dad35596C4aC7c4/sources/MasterChef.sol
Withdraw CAKE tokens from STAKING.
function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accPikaPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safePikaTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accPikaPerShare).div(1e12); syrup.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); }
11,361,656
//Address: 0x4823429dbda52f05f66a2670852b28bd7999e810 //Contract name: KStarCoin //Balance: 0 Ether //Verification Date: 3/2/2018 //Transacion Count: 19 // CODE STARTS HERE pragma solidity ^0.4.18; //>> Reference to https://github.com/Arachnid/solidity-stringutils library strings { struct slice { uint _len; uint _ptr; } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal pure returns (bool) { return self._len == 0; } } //<< Reference to https://github.com/Arachnid/solidity-stringutils //>> Reference to https://github.com/OpenZeppelin/zeppelin-solidity /** * @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) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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 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 { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @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]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @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); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** @title ERC827 interface, an extension of ERC20 token standard Interface of a ERC827 token, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. */ contract ERC827 is ERC20 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } /** @title ERC827, an extension of ERC20 token standard Implementation the ERC827, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. 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 that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens to a specified address and execute a call with the sent data on the same transaction @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens from one address to another and make a contract call on the same transaction @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amout of tokens to be transferred @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * 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. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * 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. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); require(_spender.call(_data)); return true; } } //<< Reference to https://github.com/OpenZeppelin/zeppelin-solidity /** * @title MultiOwnable */ contract MultiOwnable { address public root; mapping (address => address) public owners; // owner => parent of owner /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function MultiOwnable() public { root= msg.sender; owners[root]= root; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owners[msg.sender] != 0); _; } /** * @dev Adding new owners */ function newOwner(address _owner) onlyOwner public returns (bool) { require(_owner != 0); owners[_owner]= msg.sender; return true; } /** * @dev Deleting owners */ function deleteOwner(address _owner) onlyOwner public returns (bool) { require(owners[_owner] == msg.sender || (owners[_owner] != 0 && msg.sender == root)); owners[_owner]= 0; return true; } } /** * @title KStarCoinBasic */ contract KStarCoinBasic is ERC827Token, MultiOwnable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; using strings for *; // KStarCoin Distribution // - Crowdsale : 9%(softcap) ~ 45%(hardcap) // - Reserve: 15% // - Team: 10% // - Advisors & Partners: 5% // - Bounty Program + Ecosystem : 25% ~ 61% uint256 public capOfTotalSupply; uint256 public constant INITIAL_SUPPLY= 30e6 * 1 ether; // Reserve(15) + Team(10) + Advisors&Patners(5) uint256 public crowdsaleRaised; uint256 public constant CROWDSALE_HARDCAP= 45e6 * 1 ether; // Crowdsale(Max 45) /** * @dev Function to increase capOfTotalSupply in the next phase of KStarCoin's ecosystem */ function increaseCap(uint256 _addedValue) onlyOwner public returns (bool) { require(_addedValue >= 100e6 * 1 ether); capOfTotalSupply = capOfTotalSupply.add(_addedValue); return true; } /** * @dev Function to check whether the current supply exceeds capOfTotalSupply */ function checkCap(uint256 _amount) public view returns (bool) { return (totalSupply_.add(_amount) <= capOfTotalSupply); } //> for ERC20 function transfer(address _to, uint256 _value) public returns (bool) { require(super.transfer(_to, _value)); KSC_Send(msg.sender, _to, _value, ""); KSC_Receive(_to, msg.sender, _value, ""); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(super.transferFrom(_from, _to, _value)); KSC_SendTo(_from, _to, _value, ""); KSC_ReceiveFrom(_to, _from, _value, ""); return true; } function approve(address _to, uint256 _value) public returns (bool) { require(super.approve(_to, _value)); KSC_Approve(msg.sender, _to, _value, ""); return true; } // additional StandardToken method of zeppelin-solidity function increaseApproval(address _to, uint _addedValue) public returns (bool) { require(super.increaseApproval(_to, _addedValue)); KSC_ApprovalInc(msg.sender, _to, _addedValue, ""); return true; } // additional StandardToken method of zeppelin-solidity function decreaseApproval(address _to, uint _subtractedValue) public returns (bool) { require(super.decreaseApproval(_to, _subtractedValue)); KSC_ApprovalDec(msg.sender, _to, _subtractedValue, ""); return true; } //< //> for ERC827 function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { return transfer(_to, _value, _data, ""); } function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { return transferFrom(_from, _to, _value, _data, ""); } function approve(address _to, uint256 _value, bytes _data) public returns (bool) { return approve(_to, _value, _data, ""); } // additional StandardToken method of zeppelin-solidity function increaseApproval(address _to, uint _addedValue, bytes _data) public returns (bool) { return increaseApproval(_to, _addedValue, _data, ""); } // additional StandardToken method of zeppelin-solidity function decreaseApproval(address _to, uint _subtractedValue, bytes _data) public returns (bool) { return decreaseApproval(_to, _subtractedValue, _data, ""); } //< //> notation for ERC827 function transfer(address _to, uint256 _value, bytes _data, string _note) public returns (bool) { require(super.transfer(_to, _value, _data)); KSC_Send(msg.sender, _to, _value, _note); KSC_Receive(_to, msg.sender, _value, _note); return true; } function transferFrom(address _from, address _to, uint256 _value, bytes _data, string _note) public returns (bool) { require(super.transferFrom(_from, _to, _value, _data)); KSC_SendTo(_from, _to, _value, _note); KSC_ReceiveFrom(_to, _from, _value, _note); return true; } function approve(address _to, uint256 _value, bytes _data, string _note) public returns (bool) { require(super.approve(_to, _value, _data)); KSC_Approve(msg.sender, _to, _value, _note); return true; } function increaseApproval(address _to, uint _addedValue, bytes _data, string _note) public returns (bool) { require(super.increaseApproval(_to, _addedValue, _data)); KSC_ApprovalInc(msg.sender, _to, _addedValue, _note); return true; } function decreaseApproval(address _to, uint _subtractedValue, bytes _data, string _note) public returns (bool) { require(super.decreaseApproval(_to, _subtractedValue, _data)); KSC_ApprovalDec(msg.sender, _to, _subtractedValue, _note); return true; } //< /** * @dev Function to mint coins * @param _to The address that will receive the minted coins. * @param _amount The amount of coins to mint. * @return A boolean that indicates if the operation was successful. * @dev reference : https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/MintableToken.sol */ function mint(address _to, uint256 _amount) onlyOwner internal returns (bool) { require(_to != address(0)); require(checkCap(_amount)); totalSupply_= totalSupply_.add(_amount); balances[_to]= balances[_to].add(_amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to mint coins * @param _to The address that will receive the minted coins. * @param _amount The amount of coins to mint. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. * @dev reference : https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/MintableToken.sol */ function mint(address _to, uint256 _amount, string _note) onlyOwner public returns (bool) { require(mint(_to, _amount)); KSC_Mint(_to, msg.sender, _amount, _note); return true; } /** * @dev Burns a specific amount of coins. * @param _to The address that will be burned the coins. * @param _amount The amount of coins to be burned. * @return A boolean that indicates if the operation was successful. * @dev reference : https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BurnableToken.sol */ function burn(address _to, uint256 _amount) onlyOwner internal returns (bool) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[_to]= balances[_to].sub(_amount); totalSupply_= totalSupply_.sub(_amount); return true; } /** * @dev Burns a specific amount of coins. * @param _to The address that will be burned the coins. * @param _amount The amount of coins to be burned. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. * @dev reference : https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BurnableToken.sol */ function burn(address _to, uint256 _amount, string _note) onlyOwner public returns (bool) { require(burn(_to, _amount)); KSC_Burn(_to, msg.sender, _amount, _note); return true; } // for crowdsale /** * @dev Function which allows users to buy KStarCoin during the crowdsale period * @param _to The address that will receive the coins. * @param _value The amount of coins to sell. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. */ function sell(address _to, uint256 _value, string _note) onlyOwner public returns (bool) { require(crowdsaleRaised.add(_value) <= CROWDSALE_HARDCAP); require(mint(_to, _value)); crowdsaleRaised= crowdsaleRaised.add(_value); KSC_Buy(_to, msg.sender, _value, _note); return true; } // for buyer with cryptocurrency other than ETH /** * @dev This function is occured when owner mint coins to users as they buy with cryptocurrency other than ETH. * @param _to The address that will receive the coins. * @param _value The amount of coins to mint. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. */ function mintToOtherCoinBuyer(address _to, uint256 _value, string _note) onlyOwner public returns (bool) { require(mint(_to, _value)); KSC_BuyOtherCoin(_to, msg.sender, _value, _note); return true; } // for bounty program /** * @dev Function to reward influencers with KStarCoin * @param _to The address that will receive the coins. * @param _value The amount of coins to mint. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. */ function mintToInfluencer(address _to, uint256 _value, string _note) onlyOwner public returns (bool) { require(mint(_to, _value)); KSC_GetAsInfluencer(_to, msg.sender, _value, _note); return true; } // for KSCPoint (KStarLive ecosystem point) /** * @dev Function to exchange KSCPoint to KStarCoin * @param _to The address that will receive the coins. * @param _value The amount of coins to mint. * @param _note The notation for ethereum blockchain event log system * @return A boolean that indicates if the operation was successful. */ function exchangePointToCoin(address _to, uint256 _value, string _note) onlyOwner public returns (bool) { require(mint(_to, _value)); KSC_ExchangePointToCoin(_to, msg.sender, _value, _note); return true; } // Event functions to log the notation for ethereum blockchain // for initializing event KSC_Initialize(address indexed _src, address indexed _desc, uint256 _value, string _note); // for transfer() event KSC_Send(address indexed _src, address indexed _desc, uint256 _value, string _note); event KSC_Receive(address indexed _src, address indexed _desc, uint256 _value, string _note); // for approve(), increaseApproval(), decreaseApproval() event KSC_Approve(address indexed _src, address indexed _desc, uint256 _value, string _note); event KSC_ApprovalInc(address indexed _src, address indexed _desc, uint256 _value, string _note); event KSC_ApprovalDec(address indexed _src, address indexed _desc, uint256 _value, string _note); // for transferFrom() event KSC_SendTo(address indexed _src, address indexed _desc, uint256 _value, string _note); event KSC_ReceiveFrom(address indexed _src, address indexed _desc, uint256 _value, string _note); // for mint(), burn() event KSC_Mint(address indexed _src, address indexed _desc, uint256 _value, string _note); event KSC_Burn(address indexed _src, address indexed _desc, uint256 _value, string _note); // for crowdsale event KSC_Buy(address indexed _src, address indexed _desc, uint256 _value, string _note); // for buyer with cryptocurrency other than ETH event KSC_BuyOtherCoin(address indexed _src, address indexed _desc, uint256 _value, string _note); // for bounty program event KSC_GetAsInfluencer(address indexed _src, address indexed _desc, uint256 _value, string _note); // for KSCPoint (KStarLive ecosystem point) event KSC_ExchangePointToCoin(address indexed _src, address indexed _desc, uint256 _value, string _note); } /** * @title KStarCoin v1.0 * @author Tae Kim * @notice KStarCoin is an ERC20 (with an alternative of ERC827) Ethereum based token, which will be integrated in KStarLive platform. */ contract KStarCoin is KStarCoinBasic { string public constant name= "KStarCoin"; string public constant symbol= "KSC"; uint8 public constant decimals= 18; // Constructure function KStarCoin() public { totalSupply_= INITIAL_SUPPLY; balances[msg.sender]= INITIAL_SUPPLY; capOfTotalSupply = 100e6 * 1 ether; crowdsaleRaised= 0; Transfer(0x0, msg.sender, INITIAL_SUPPLY); KSC_Initialize(msg.sender, 0x0, INITIAL_SUPPLY, ""); } }
Function to increase capOfTotalSupply in the next phase of KStarCoin's ecosystem/
function increaseCap(uint256 _addedValue) onlyOwner public returns (bool) { require(_addedValue >= 100e6 * 1 ether); capOfTotalSupply = capOfTotalSupply.add(_addedValue); return true; }
952,710
./partial_match/1/0xe7c8537F92b4fEEFdc19bd6b4023dFe79400cb30/sources/BONES.sol
approve token transfer to cover all possible scenarios add the liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniRouterContract), tokenAmount); address(this), tokenAmount, owner(), block.timestamp ); }
2,679,585
/* * Copyright 2020, NTT Communications Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.8.0 <0.9.0; string constant MetemcyberUtil_ContractId = "MetemcyberUtil.sol:MetemcyberUtil"; library MetemcyberUtil { string constant public contractId = MetemcyberUtil_ContractId; uint256 constant public contractVersion = 0; bytes constant private _lowerHexChars = "0123456789abcdef"; bytes1 constant private _b1_0 = bytes1("0"); bytes1 constant private _b1_x = bytes1("x"); bytes1 constant private _b1_X = bytes1("X"); uint8 constant private _u8_f = uint8(bytes1("f")); uint8 constant private _u8_a = uint8(bytes1("a")); uint8 constant private _u8_F = uint8(bytes1("F")); uint8 constant private _u8_A = uint8(bytes1("A")); uint8 constant private _u8_9 = uint8(bytes1("9")); uint8 constant private _u8_0 = uint8(bytes1("0")); uint8 constant private _u8_toLower = _u8_a - _u8_A; function stringToAddress( string memory str ) public pure returns (address addr) { bytes memory bstr = bytes(str); // low-level bytes of UTF8 uint8 offset = 0; uint8 max = 40; // address is 20 byte, 40 letters. uint160 ret = 0; if (bstr.length == 42) { require(bstr[0] == _b1_0 && (bstr[1] == _b1_x || bstr[1] == _b1_X), "invalid input"); offset = 2; max += 2; } else { require(bstr.length == 40, "invalid input length"); } for (uint8 i = offset; i < max; i++) { uint8 u8_i = uint8(bstr[i]); uint8 tmp; if (_u8_a <= u8_i && u8_i <= _u8_f) tmp = u8_i - _u8_a + 10; else if (_u8_A <= u8_i && u8_i <= _u8_F) tmp = u8_i - _u8_A + 10; else if (_u8_0 <= u8_i && u8_i <= _u8_9) tmp = u8_i - _u8_0; else revert("invalid input"); ret = ret * 16 + tmp; } return address(ret); } function addressToString( address addr ) internal pure returns (string memory) { bytes memory baddr = abi.encodePacked(addr); bytes memory bstr = new bytes(42); // 40 letters + 0x bstr[0] = '0'; bstr[1] = 'x'; for (uint8 i = 0; i < 20; i++) { bstr[2+i*2] = _lowerHexChars[uint256(uint8(baddr[i]) >> 4)]; bstr[2+i*2+1] = _lowerHexChars[uint256(uint8(baddr[i]) & 0xF)]; } return string(bstr); // lowercase hex string with leading 0x } function toChecksumAddress( string memory addressString ) public pure returns (string memory) { // for detail, see https://eips.ethereum.org/EIPS/eip-55 bytes memory blower = _toLower(bytes(addressString)); bytes memory bhash = _bytes32ToBytes(keccak256(blower)); bytes memory bfixed = new bytes(42); // 40 letters + 0x bfixed[0] = '0'; bfixed[1] = 'x'; for (uint8 i = 0; i < 40; i++) { if (uint8(blower[i]) <= _u8_9) { // digit bfixed[2+i] = blower[i]; continue; } uint8 u = uint8(bhash[i/2]); if (i % 2 == 0) u >>= 4; // higher half else u &= 0xF; // lower half if (u >= 8) bfixed[2+i] = bytes1(uint8(blower[i]) - _u8_toLower); else bfixed[2+i] = blower[i]; } return string(bfixed); // ChecksumAddress conform to EIP-55 } function isSameStrings( string memory s1, string memory s2 ) internal pure returns (bool isSame) { return ( keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2)) ); } function _bytes32ToBytes( bytes32 source ) internal pure returns (bytes memory) { bytes memory bstr = new bytes(32); for (uint8 i=0; i < 32; i++) bstr[i] = source[i]; return bstr; } function _toLower(bytes memory bstr) internal pure returns (bytes memory) { bytes memory blower = new bytes(40); uint8 offset = 0; if (bstr.length == 42) { require(bstr[0] == _b1_0 && (bstr[1] == _b1_x || bstr[1] == _b1_X), "invalid input"); offset = 2; } else { require(bstr.length == 40, "invalid input length"); } for (uint8 i = 0; i < 40; i++) { uint8 u8_i = uint8(bstr[i + offset]); if (_u8_a <= u8_i && u8_i <= _u8_f) blower[i] = bstr[i + offset]; else if (_u8_A <= u8_i && u8_i <= _u8_F) blower[i] = bytes1(u8_i + _u8_toLower); else if (_u8_0 <= u8_i && u8_i <= _u8_9) blower[i] = bstr[i + offset]; else revert("invalid input"); } return blower; // does not have leading '0x' } }
for detail, see https:eips.ethereum.org/EIPS/eip-55
function toChecksumAddress( string memory addressString ) public pure returns (string memory) { bytes memory blower = _toLower(bytes(addressString)); bytes memory bhash = _bytes32ToBytes(keccak256(blower)); bfixed[0] = '0'; bfixed[1] = 'x'; for (uint8 i = 0; i < 40; i++) { bfixed[2+i] = blower[i]; continue; } uint8 u = uint8(bhash[i/2]); if (i % 2 == 0) else if (u >= 8) bfixed[2+i] = bytes1(uint8(blower[i]) - _u8_toLower); else bfixed[2+i] = blower[i]; }
14,089,824
./full_match/1/0x217f947d7aEad260b20278B6EE399bA768994515/sources/contracts/BrewlabsFarm.sol
Withdraw LP tokens from BrewlabsFarm.
function withdraw(uint256 _pid, uint256 _amount) external payable nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); require(_amount > 0, "Amount should be greator than 0"); _transferPerformanceFee(); if (pool.bonusEndBlock < block.number) { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(pool.allocPoint); pool.allocPoint = 0; updatePool(_pid); } uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { require(availableRewardTokens() >= pending, "Insufficient reward tokens"); safeTokenTransfer(msg.sender, pending); if (totalEarned > pending) { totalEarned = totalEarned.sub(pending); totalEarned = 0; } paidRewards = paidRewards + pending; } uint256 pendingReflection = user.amount.mul(pool.accReflectionPerShare).div(1e12).sub(user.reflectionDebt); pendingReflection = _estimateDividendAmount(pendingReflection); if (pendingReflection > 0 && hasDividend) { if (address(reflectionToken) == address(0x0)) { payable(msg.sender).transfer(pendingReflection); IERC20(reflectionToken).safeTransfer(msg.sender, pendingReflection); } totalReflections = totalReflections.sub(pendingReflection); } if (_amount > 0) { user.amount = user.amount.sub(_amount); if (pool.withdrawFee > 0) { uint256 withdrawFee = _amount.mul(pool.withdrawFee).div(10000); pool.lpToken.safeTransfer(feeAddress, withdrawFee); pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(withdrawFee)); pool.lpToken.safeTransfer(address(msg.sender), _amount); } _calculateTotalStaked(_pid, pool.lpToken, _amount, false); } user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); user.reflectionDebt = user.amount.mul(pool.accReflectionPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
16,565,526
/** *Submitted for verification at Etherscan.io on 2022-04-07 */ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.4; interface Erc20 { function transfer(address, uint256) external returns (bool); function balanceOf(address) external returns (uint256); function transferFrom(address, address, uint256) external returns (bool); } /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /// @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree defined by `root`. /// For this, a `proof` must be provided, containing sibling hashes on the branch from the leaf to the root of the /// tree. Each pair of leaves and each pair of pre-images are assumed to be sorted. /// @param p Array of merkle proofs /// @param r Merkle root /// @param l Candidate 'leaf' of the merkle tree function verify(bytes32[] memory p, bytes32 r, bytes32 l) internal pure returns (bool) { uint256 len = p.length; bytes32 hash = l; for (uint256 i = 0; i < len; i++) { bytes32 element = p[i]; if (hash <= element) { // Hash(current computed hash + current element of the proof) hash = keccak256(abi.encodePacked(hash, element)); } else { // Hash(current element of the proof + current computed hash) hash = keccak256(abi.encodePacked(element, hash)); } } // Check if the computed hash (root) is equal to the provided root return hash == r; } } contract Destributor { mapping (uint256 => bytes32) public merkleRoot; mapping (uint256 => mapping (uint256 => uint256)) private claims; mapping (uint256 => bool) private cancelled; uint256 public distribution; address public immutable token; address public admin; bool public paused; event Distribute(bytes32 merkleRoot, uint256 distribution); event Claim(uint256 index, address owner, uint256 amount); /// @param t Address of an ERC20 token /// @param r Initial merkle root constructor(address t, bytes32 r) { admin = msg.sender; token = t; merkleRoot[0] = r; } /// @notice Generate a new distribution, cancelling the would be current one /// @param f The address of the wallet containing tokens to distribute /// @param t The address that will receive any currently remaining distributions (will normally be the same as from) /// @param a The amount of tokens in the new distribution /// @param r The merkle root associated with the new distribution function distribute(address f, address t, uint256 a, bytes32 r) external authorized(admin) returns (bool) { // remove curent token balance Erc20 erc = Erc20(token); uint256 balance = erc.balanceOf(address(this)); erc.transfer(t, balance); // transfer enough tokens for new distribution erc.transferFrom(f, address(this), a); // we are working with the distribution, eventually bumping it... uint256 current = distribution; // cancel the (to-be) previous distribution cancelled[current] = true; current++; // add the new distribution's merkleRoot merkleRoot[current] = r; distribution = current; // unpause redemptions pause(false); emit Distribute(r, current); return true; } /// @param i An index which to construct a possible claim from /// @param d The distribution to check for a claim function claimed(uint256 i, uint256 d) public view returns (bool) { require(i > 0, 'passed index must be > 0'); uint256 wordIndex = i / 256; uint256 bitIndex = i % 256; uint256 word = claims[d][wordIndex]; uint256 mask = (1 << bitIndex); return word & mask == mask; } /// @param i An index which to construct a claim from /// @param o Owner address of the token being transferred /// @param a Amount being transferred /// @param p array of merkle proofs function claim(uint256 i, address o, uint256 a, bytes32[] calldata p) external returns (bool) { require(!paused, 'claiming is paused'); require(!claimed(i, distribution), 'distribution claimed'); require(!cancelled[distribution], 'distribution cancelled'); // Verify the merkle proof... bytes32 node = keccak256(abi.encodePacked(i, o, a)); require(MerkleProof.verify(p, merkleRoot[distribution], node), 'invalid proof'); // Mark it claimed... uint256 wordIndex = i / 256; uint256 bitIndex = i % 256; claims[distribution][wordIndex] = claims[distribution][wordIndex] | (1 << bitIndex); // send the token... require(Erc20(token).transfer(o, a), 'transfer failed.'); emit Claim(i, o, a); return true; } /// @param a Address of a new admin function transferAdmin(address a) external authorized(admin) returns (bool) { admin = a; return true; } /// @notice Allows admin to pause or unpause claims /// @param b Boolean value to set paused to function pause(bool b) public authorized(admin) returns (bool) { paused = b; return true; } modifier authorized(address a) { require(msg.sender == a, 'sender must be authorized'); _; } }
Generate a new distribution, cancelling the would be current one f The address of the wallet containing tokens to distribute t The address that will receive any currently remaining distributions (will normally be the same as from) a The amount of tokens in the new distribution r The merkle root associated with the new distribution remove curent token balance transfer enough tokens for new distribution we are working with the distribution, eventually bumping it... cancel the (to-be) previous distribution add the new distribution's merkleRoot unpause redemptions
function distribute(address f, address t, uint256 a, bytes32 r) external authorized(admin) returns (bool) { Erc20 erc = Erc20(token); uint256 balance = erc.balanceOf(address(this)); erc.transfer(t, balance); erc.transferFrom(f, address(this), a); uint256 current = distribution; cancelled[current] = true; current++; merkleRoot[current] = r; distribution = current; pause(false); emit Distribute(r, current); return true; }
10,683,607
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; /** * @title XUSD AlphaHomora Strategy * @notice Investment strategy for investing stablecoins via AlphaHomora/CREAM * @author XUSD.fi Inc */ import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IERC20, InitializableAbstractStrategy } from "../utils/InitializableAbstractStrategy.sol"; import { IVault } from "../interfaces/IVault.sol"; import { ICERC20 } from "../interfaces/alphaHomora/ICERC20.sol"; import { ISafeBox } from "../interfaces/alphaHomora/ISafeBox.sol"; import { IAlphaIncentiveDistributor } from "../interfaces/alphaHomora/IAlphaIncentiveDistributor.sol"; contract AlphaHomoraStrategy is InitializableAbstractStrategy { using SafeERC20 for IERC20; address[] public incentiveDistributorAddresses; mapping(address => bytes32[]) internal _proofs; mapping(address => uint256) internal _amounts; function initialize( address _platformAddress, // dead address _vaultAddress, address[] calldata _rewardTokenAddresses, // [ALPHA, WAVAX] address[] calldata _assets, address[] calldata _pTokens, address[] calldata _incentiveDistributorAddresses // [ALPHAcontrollerAddr, WAVAXcontrollerAddr] ) external onlyGovernor initializer { require( _rewardTokenAddresses.length == _incentiveDistributorAddresses.length, "not 1:1 rewards-to-incentives" ); incentiveDistributorAddresses = _incentiveDistributorAddresses; InitializableAbstractStrategy._initialize( _platformAddress, _vaultAddress, _rewardTokenAddresses, _assets, _pTokens ); } event SkippedWithdrawal(address asset, uint256 amount); /** * @dev Collect accumulated WAVAX+ALPHA and send to Vault. */ function collectRewardTokens() external override onlyVault nonReentrant { for (uint256 i = 0; i < rewardTokenAddresses.length; i++) { IAlphaIncentiveDistributor _incentiveDistributor = IAlphaIncentiveDistributor( incentiveDistributorAddresses[i] ); require(_incentiveDistributor.token() == rewardTokenAddresses[i]); uint256 _amount = _amounts[rewardTokenAddresses[i]]; if (_amount == 0) { continue; } bytes32[] memory _proof = _proofs[rewardTokenAddresses[i]]; uint256 _claimed = _incentiveDistributor.claimed(address(this)); if (_claimed < _amount) { /* Claim _amount - _claimed reward tokens */ _incentiveDistributor.claim(address(this), _amount, _proof); /* // Transfer rewards to Vault */ IERC20 rewardToken = IERC20(rewardTokenAddresses[i]); uint256 balance = rewardToken.balanceOf(address(this)); emit RewardTokenCollected( vaultAddress, rewardTokenAddresses[i], balance ); rewardToken.safeTransfer(vaultAddress, balance); } } } /** * @dev Deposit asset into AlphaHomora * @param _asset Address of asset to deposit * @param _amount Amount of asset to deposit */ function deposit(address _asset, uint256 _amount) external override onlyVault nonReentrant { _deposit(_asset, _amount); } /** * @dev Deposit asset into AlphaHomorax * @param _asset Address of asset to deposit * @param _amount Amount of asset to deposit */ function _deposit(address _asset, uint256 _amount) internal { require(_amount > 0, "Must deposit something"); ISafeBox safeBox = _getSafeBoxFor(_asset); emit Deposit(_asset, address(safeBox), _amount); safeBox.deposit(_amount); } /** * @dev Deposit the entire balance of any supported asset into AlphaHomora */ function depositAll() external override onlyVault nonReentrant { for (uint256 i = 0; i < assetsMapped.length; i++) { uint256 balance = IERC20(assetsMapped[i]).balanceOf(address(this)); if (balance > 0) { _deposit(assetsMapped[i], balance); } } } /** * @dev Withdraw asset from AlphaHomora * @param _recipient Address to receive withdrawn asset * @param _asset Address of asset to withdraw * @param _amount Amount of asset to withdraw */ function withdraw( address _recipient, address _asset, uint256 _amount ) external override onlyVault nonReentrant { require(_amount > 0, "Must withdraw something"); require(_recipient != address(0), "Must specify recipient"); ISafeBox safeBox = _getSafeBoxFor(_asset); ICERC20 cToken = _getCTokenFor(_asset); uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _amount); emit Withdrawal(_asset, address(safeBox), cTokensToRedeem); if (cTokensToRedeem == 0) { emit SkippedWithdrawal(_asset, _amount); return; } emit Withdrawal(_asset, address(cToken.underlying()), _amount); uint256 balanceBefore = IERC20(_asset).balanceOf(address(this)); safeBox.withdraw(cTokensToRedeem); uint256 balanceAfter = IERC20(_asset).balanceOf(address(this)); require( _amount <= balanceAfter - balanceBefore, "Did not withdraw enough" ); IERC20(_asset).safeTransfer(_recipient, _amount); } /** * @dev Remove all assets from platform and send all of that asset to Vault contract. */ function withdrawAll() external override onlyVaultOrGovernor nonReentrant { for (uint256 i = 0; i < assetsMapped.length; i++) { IERC20 asset = IERC20(assetsMapped[i]); ISafeBox safeBox = _getSafeBoxFor(assetsMapped[i]); ICERC20 cToken = _getCTokenFor(assetsMapped[i]); uint256 balance = cToken.balanceOf(address(this)); // Redeem entire balance of safeBox if (balance > 0) { safeBox.withdraw(balance); // Transfer entire balance to Vault, including any already held asset.safeTransfer( vaultAddress, asset.balanceOf(address(this)) ); } } } /** * @dev Get the total asset value held in the platform * This includes any interest that was generated since depositing * CREAM exchange rate between the cToken and asset gradually increases, * causing the cToken to be worth more corresponding asset. * @param _asset Address of the asset * @return balance Total value of the asset in the platform */ function checkBalance(address _asset) external view override returns (uint256 balance) { // Balance is always with token cToken decimals address safeBoxAddr = assetToPToken[_asset]; require(safeBoxAddr != address(0)); ISafeBox _safeBox = _getSafeBoxFor(_asset); ICERC20 _cToken = _safeBox.cToken(); balance = _checkBalance(safeBoxAddr, _cToken); } /** * @dev Get the total asset value held in the platform * underlying = (cTokenAmt * exchangeRate) / 1e18 * @param _cToken cToken for which to check balance * @return balance Total value of the asset in the platform */ function _checkBalance(address _safeBox, ICERC20 _cToken) internal view returns (uint256 balance) { uint256 safeBoxBalance = IERC20(_safeBox).balanceOf(address(this)); uint256 exchangeRate = _cToken.exchangeRateStored(); // e.g. 50e8*205316390724364402565641705 / 1e18 = 1.0265..e18 balance = (safeBoxBalance * exchangeRate) / 1e18; } /** * @dev Returns bool indicating whether asset is supported by strategy * @param _asset Address of the asset */ function supportsAsset(address _asset) external view override returns (bool) { return assetToPToken[_asset] != address(0); } /** * @dev Approve the spending of all assets by their corresponding cToken, * if for some reason is it necessary. */ function safeApproveAllTokens() external override { uint256 assetCount = assetsMapped.length; for (uint256 i = 0; i < assetCount; i++) { address asset = assetsMapped[i]; address cToken = assetToPToken[asset]; // Safe approval IERC20(asset).safeApprove(cToken, 0); IERC20(asset).safeApprove(cToken, type(uint256).max); } } /** * @dev Internal method to respond to the addition of new asset / cTokens * We need to approve the cToken and give it permission to spend the asset * @param _asset Address of the asset to approve * @param _cToken The cToken for the approval */ function _abstractSetPToken(address _asset, address _cToken) internal override { // Safe approval IERC20(_asset).safeApprove(_cToken, 0); IERC20(_asset).safeApprove(_cToken, type(uint256).max); } /** * @dev Get the SafeBox token wrap ISafeBox interface for this asset. * Fails if the SafeBbox doesn't exist in our mappings. * @param _asset Address of the asset * @return Corresponding SafeBox to this asset */ function _getSafeBoxFor(address _asset) internal view returns (ISafeBox) { address safeBox = assetToPToken[_asset]; require(safeBox != address(0), "safeBox does not exist"); return ISafeBox(safeBox); } /** * @dev Get the cToken wrapped in the ICERC20 interface for this asset. * Fails if the cToken doesn't exist in our mappings. * @param _asset Address of the asset * @return Corresponding cToken to this asset */ function _getCTokenFor(address _asset) internal view returns (ICERC20) { ISafeBox safeBox = _getSafeBoxFor(_asset); return ICERC20(safeBox.cToken()); } /** * @dev Converts an underlying amount into cToken amount * cTokenAmt = (underlying * 1e18) / exchangeRate * @param _cToken cToken for which to change * @param _underlying Amount of underlying to convert * @return amount Equivalent amount of cTokens */ function _convertUnderlyingToCToken(ICERC20 _cToken, uint256 _underlying) internal view returns (uint256 amount) { uint256 exchangeRate = _cToken.exchangeRateStored(); // e.g. 1e18*1e18 / 205316390724364402565641705 = 50e8 // e.g. 1e8*1e18 / 205316390724364402565641705 = 0.45 or 0 amount = (_underlying * 1e18) / exchangeRate; } /** * @dev Sets the reward amount and merkle proof from off-chain. * @param _rewardTokenAddress The reward token address * @param proof the MerkleProof provided by AlphaHomora * @param amount The accumulated (total) amount of rewards. */ function setProofAndAmount( address _rewardTokenAddress, bytes32[] calldata proof, uint256 amount ) external onlyGovernorOrStrategist { _proofs[_rewardTokenAddress] = proof; _amounts[_rewardTokenAddress] = amount; } function getProofAndAmount(address _rewardTokenAddress) external view returns (bytes32[] memory, uint256) { return (_proofs[_rewardTokenAddress], _amounts[_rewardTokenAddress]); } modifier onlyGovernorOrStrategist() { require( msg.sender == IVault(vaultAddress).strategistAddr() || isGovernor(), "Caller is not the Strategist or Governor" ); _; } }
Converts an underlying amount into cToken amount cTokenAmt = (underlying 1e18) / exchangeRate _cToken cToken for which to change _underlying Amount of underlying to convert return amount Equivalent amount of cTokens/ e.g. 1e181e18 / 205316390724364402565641705 = 50e8 e.g. 1e81e18 / 205316390724364402565641705 = 0.45 or 0
function _convertUnderlyingToCToken(ICERC20 _cToken, uint256 _underlying) internal view returns (uint256 amount) { uint256 exchangeRate = _cToken.exchangeRateStored(); amount = (_underlying * 1e18) / exchangeRate; }
12,813,564
./full_match/42/0x1B39B07fDAF1D6AC7cD7818916A5b41403757Dcb/sources/new_test.sol
Returns the amount of tokens in existence.
function totalSupply() external view returns (uint256);
16,216,524
pragma solidity 0.6.0; 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) { // 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity 0.6.0; 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) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` pnch to * `recipient`, forwarding all available gas and reverting on errors. * */ 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"); } } pragma solidity 0.6.0; library EnumerableMap { // 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 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) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ 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(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(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(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } pragma solidity 0.6.0; library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity 0.6.0; contract Ownable { 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 = msg.sender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "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 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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.0; contract MyFT is Ownable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; /** * @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); // Mapping from eth address to nch address mapping (string => address) public addrs; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.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; // Optional mapping for token URIs mapping(uint256 => string) private tokenURIs; // Base URI string public baseURI; // Token name string private _name; // Token symbol string private _symbol; constructor () public { _name = "BEE-EGG"; _symbol = "BEE-EGG"; } /** * @dev Gets the token name. * @return string representing the token name */ function name() public view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Gets the balance of the specified address. * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0), "NRC721: balance query for the zero address"); return holderTokens[_owner].length(); } function balanceOfWithETHAddr(string memory _ethAddress) public view returns (uint256) { address owner = addrs[_ethAddress]; return balanceOf(owner); } /** * @dev Gets the owner of the specified token ID. * @param _tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { return tokenOwners.get(_tokenId, "NRC721: owner query for nonexistent token"); } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 _tokenId) public view returns (string memory) { require(_exists(_tokenId), "NRC721Metadata: URI query for nonexistent token"); string memory _tokenURI = tokenURIs[_tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(baseURI, _tokenURI)); } } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { return holderTokens[_owner].at(_index); } function tokenOfOwnerByIndexWithEthAddr(string memory _ethAddress, uint256 _index) public view returns (uint256) { address owner = addrs[_ethAddress]; return holderTokens[owner].at(_index); } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { // tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return tokenOwners.length(); } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { (uint256 tokenId, ) = tokenOwners.at(_index); return tokenId; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner, "NRC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "NRC721: approve caller is not owner nor approved for all" ); _approve(_to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { require(_exists(_tokenId), "NRC721: approved query for nonexistent token"); return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param _operator operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _operator, bool _approved) public { require(_operator != msg.sender, "NRC721: approve to caller"); operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev beeMint * call _safeMint to generate new NFT token * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted */ function beeMint(string memory _ethAddress, address _to, uint256 _tokenId) public onlyOwner { // 检查_ethAddress和_nchAddress的绑定关系 address addr = addrs[_ethAddress]; if (addr != address(0)) { require(addr == _to, "eth address and nch address not match"); } _safeMint(_to, _tokenId); addrs[_ethAddress] = _to; } /** * @dev Safely transfers the ownership of a given token ID to another address * Requires the msg.sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { require(_isApprovedOrOwner(msg.sender, _tokenId), "NRC721: transfer caller is not owner nor approved"); _safeTransfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * Requires the msg.sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function _safeTransfer(address _from, address _to, uint256 _tokenId) internal { _transfer(_from, _to, _tokenId); // require(_checkOnNRC721Received(_from, _to, _tokenId, _data), "NRC721: transfer to non NRC721Receiver implementer"); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { require(_exists(_tokenId), "NRC721: operator query for nonexistent token"); address owner = ownerOf(_tokenId); return (_spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted */ function _safeMint(address _to, uint256 _tokenId) internal { _mint(_to, _tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0), "NRC721: mint to the zero address"); require(!_exists(_tokenId), "NRC721: token already minted"); _beforeTokenTransfer(address(0), _to, _tokenId); holderTokens[_to].add(_tokenId); tokenOwners.set(_tokenId, _to); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function _transfer(address _from, address _to, uint256 _tokenId) internal { require(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); holderTokens[_from].remove(_tokenId); holderTokens[_to].add(_tokenId); tokenOwners.set(_tokenId, _to); emit Transfer(_from, _to, _tokenId); } /** * @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 returns (bool) { return tokenOwners.contains(_tokenId); } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. */ function _setTokenURI(uint256 _tokenId, string memory _tokenURI) internal { require(_exists(_tokenId), "NRC721Metadata: 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}. */ function _setBaseURI(string memory _baseURI) internal { baseURI = _baseURI; } // function _checkOnNRC721Received(address _from, address _to, uint256 _tokenId, bytes memory _data) // private returns (bool) // { // if (!_to.isContract()) { // return true; // } // } function _approve(address _to, uint256 _tokenId) private { tokenApprovals[_tokenId] = _to; emit Approval(ownerOf(_tokenId), _to, _tokenId); } function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal { } }
Safely transfers the ownership of a given token ID to another address Requires the msg.sender to be the owner, approved, or operator _from current owner of the token _to address to receive the ownership of the given token ID _tokenId uint256 ID of the token to be transferred/ require(_checkOnNRC721Received(_from, _to, _tokenId, _data), "NRC721: transfer to non NRC721Receiver implementer");
function _safeTransfer(address _from, address _to, uint256 _tokenId) internal { _transfer(_from, _to, _tokenId); }
12,732,124
pragma solidity ^0.4.15; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title * @dev DatTokenSale is a contract for managing a token crowdsale. * DatTokenSale have a start and end date, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a refundable valut * as they arrive. */ contract DatumTokenSale is Ownable { using SafeMath for uint256; address public whiteListControllerAddress; //lookup addresses for whitelist mapping (address => bool) public whiteListAddresses; //lookup addresses for special bonuses mapping (address => uint) public bonusAddresses; //loopup for max token amount per user allowed mapping(address => uint256) public maxAmountAddresses; //loopup for balances mapping(address => uint256) public balances; // start and end date where investments are allowed (both inclusive) uint256 public startDate = 1509282000;//29 Oct 2017 13:00:00 +00:00 UTC //uint256 public startDate = 1509210891;//29 Oct 2017 13:00:00 +00:00 UTC uint256 public endDate = 1511960400; //29 Nov 2017 13:00:00 +00:00 UTC // Minimum amount to participate (wei for internal usage) uint256 public minimumParticipationAmount = 300000000000000000 wei; //0.1 ether // Maximum amount to participate uint256 public maximalParticipationAmount = 1000 ether; //1000 ether // address where funds are collected address wallet; // how many token units a buyer gets per ether uint256 rate = 25000; // amount of raised money in wei uint256 private weiRaised; //flag for final of crowdsale bool public isFinalized = false; //cap for the sale in ether uint256 public cap = 61200 ether; //61200 ether //total tokenSupply uint256 public totalTokenSupply = 1530000000 ether; // amount of tokens sold uint256 public tokensInWeiSold; uint private bonus1Rate = 28750; uint private bonus2Rate = 28375; uint private bonus3Rate = 28000; uint private bonus4Rate = 27625; uint private bonus5Rate = 27250; uint private bonus6Rate = 26875; uint private bonus7Rate = 26500; uint private bonus8Rate = 26125; uint private bonus9Rate = 25750; uint private bonus10Rate = 25375; event Finalized(); /** * @notice Log an event for each funding contributed during the public phase * @notice Events are not logged when the constructor is being executed during * deployment, so the preallocations will not be logged */ event LogParticipation(address indexed sender, uint256 value); /** * @notice Log an event for each funding contributed converted to earned tokens * @notice Events are not logged when the constructor is being executed during * deployment, so the preallocations will not be logged */ event LogTokenReceiver(address indexed sender, uint256 value); /** * @notice Log an event for each funding contributed converted to earned tokens * @notice Events are not logged when the constructor is being executed during * deployment, so the preallocations will not be logged */ event LogTokenRemover(address indexed sender, uint256 value); function DatumTokenSale(address _wallet) payable { wallet = _wallet; } function () payable { require(whiteListAddresses[msg.sender]); require(validPurchase()); buyTokens(msg.value); } // low level token purchase function function buyTokens(uint256 amount) internal { //get ammount in wei uint256 weiAmount = amount; // update state weiRaised = weiRaised.add(weiAmount); // get token amount uint256 tokens = getTokenAmount(weiAmount); tokensInWeiSold = tokensInWeiSold.add(tokens); //fire token receive event LogTokenReceiver(msg.sender, tokens); //update balances for user balances[msg.sender] = balances[msg.sender].add(tokens); //fire eth purchase event LogParticipation(msg.sender,msg.value); //forward funds to wallet forwardFunds(amount); } // manually update the tokens sold count to reserve tokens or update stats if other way bought function reserveTokens(address _address, uint256 amount) { require(msg.sender == whiteListControllerAddress); //update balances for user balances[_address] = balances[_address].add(amount); //fire event LogTokenReceiver(_address, amount); tokensInWeiSold = tokensInWeiSold.add(amount); } //release tokens from sold statistist, used if the account was not verified with KYC function releaseTokens(address _address, uint256 amount) { require(msg.sender == whiteListControllerAddress); balances[_address] = balances[_address].sub(amount); //fire event LogTokenRemover(_address, amount); tokensInWeiSold = tokensInWeiSold.sub(amount); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds(uint256 amount) internal { wallet.transfer(amount); } // should be called after crowdsale ends or to emergency stop the sale function finalize() onlyOwner { require(!isFinalized); Finalized(); isFinalized = true; } function setWhitelistControllerAddress(address _controller) onlyOwner { whiteListControllerAddress = _controller; } function addWhitelistAddress(address _addressToAdd) { require(msg.sender == whiteListControllerAddress); whiteListAddresses[_addressToAdd] = true; } function addSpecialBonusConditions(address _address, uint _bonusPercent, uint256 _maxAmount) { require(msg.sender == whiteListControllerAddress); bonusAddresses[_address] = _bonusPercent; maxAmountAddresses[_address] = _maxAmount; } function removeSpecialBonusConditions(address _address) { require(msg.sender == whiteListControllerAddress); delete bonusAddresses[_address]; delete maxAmountAddresses[_address]; } function addWhitelistAddresArray(address[] _addressesToAdd) { require(msg.sender == whiteListControllerAddress); for (uint256 i = 0; i < _addressesToAdd.length;i++) { whiteListAddresses[_addressesToAdd[i]] = true; } } function removeWhitelistAddress(address _addressToAdd) { require(msg.sender == whiteListControllerAddress); delete whiteListAddresses[_addressToAdd]; } function getTokenAmount(uint256 weiAmount) internal returns (uint256 tokens){ //add bonus uint256 bonusRate = getBonus(); //check for special bonus and override rate if exists if(bonusAddresses[msg.sender] != 0) { uint bonus = bonusAddresses[msg.sender]; //TODO: CALUC SHCHECK bonusRate = rate.add((rate.mul(bonus)).div(100)); } // calculate token amount to be created uint256 weiTokenAmount = weiAmount.mul(bonusRate); return weiTokenAmount; } //When a user buys our token they will recieve a bonus depedning on time:, function getBonus() internal constant returns (uint256 amount){ uint diffInSeconds = now - startDate; uint diffInHours = (diffInSeconds/60)/60; // 10/29/2017 - 11/1/2017 if(diffInHours < 72){ return bonus1Rate; } // 11/1/2017 - 11/4/2017 if(diffInHours >= 72 && diffInHours < 144){ return bonus2Rate; } // 11/4/2017 - 11/7/2017 if(diffInHours >= 144 && diffInHours < 216){ return bonus3Rate; } // 11/7/2017 - 11/10/2017 if(diffInHours >= 216 && diffInHours < 288){ return bonus4Rate; } // 11/10/2017 - 11/13/2017 if(diffInHours >= 288 && diffInHours < 360){ return bonus5Rate; } // 11/13/2017 - 11/16/2017 if(diffInHours >= 360 && diffInHours < 432){ return bonus6Rate; } // 11/16/2017 - 11/19/2017 if(diffInHours >= 432 && diffInHours < 504){ return bonus7Rate; } // 11/19/2017 - 11/22/2017 if(diffInHours >= 504 && diffInHours < 576){ return bonus8Rate; } // 11/22/2017 - 11/25/2017 if(diffInHours >= 576 && diffInHours < 648){ return bonus9Rate; } // 11/25/2017 - 11/28/2017 if(diffInHours >= 648 && diffInHours < 720){ return bonus10Rate; } return rate; } // @return true if the transaction can buy tokens // check for valid time period, min amount and within cap function validPurchase() internal constant returns (bool) { uint256 tokenAmount = getTokenAmount(msg.value); bool withinPeriod = startDate <= now && endDate >= now; bool nonZeroPurchase = msg.value != 0; bool minAmount = msg.value >= minimumParticipationAmount; bool maxAmount = msg.value <= maximalParticipationAmount; bool withTokensSupply = tokensInWeiSold.add(tokenAmount) <= totalTokenSupply; //bool withinCap = weiRaised.add(msg.value) <= cap; bool withMaxAmountForAddress = maxAmountAddresses[msg.sender] == 0 || balances[msg.sender].add(tokenAmount) <= maxAmountAddresses[msg.sender]; if(maxAmountAddresses[msg.sender] != 0) { maxAmount = balances[msg.sender].add(tokenAmount) <= maxAmountAddresses[msg.sender]; } return withinPeriod && nonZeroPurchase && minAmount && !isFinalized && withTokensSupply && withMaxAmountForAddress && maxAmount; } // @return true if the goal is reached function capReached() public constant returns (bool) { return tokensInWeiSold >= totalTokenSupply; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return isFinalized; } }
return true if the goal is reached
function capReached() public constant returns (bool) { return tokensInWeiSold >= totalTokenSupply; }
14,079,034
pragma solidity 0.6.6; /** * @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; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); 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 removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); 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); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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 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 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 override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override 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 override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public override 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 override returns (bool) { _approve(msg.sender, 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, msg.sender, _allowances[sender][msg.sender].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( msg.sender, spender, _allowances[msg.sender][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( msg.sender, spender, _allowances[msg.sender][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'); _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'); _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'); _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 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 ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(msg.sender, 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, msg.sender).sub( amount, 'ERC20: burn amount exceeds allowance' ); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } } /* * @dev Implementation of a token compliant with the ERC20 Token protocol; * The token has additional burn functionality. */ contract Token is ERC20Burnable { using SafeMath for uint256; /* * @dev Initialization of the token, * following arguments are provided via the constructor: name, symbol, recipient, totalSupply. * The total supply of tokens is minted to the specified recipient. */ constructor( string memory name, string memory symbol, address recipient, uint256 totalSupply ) public ERC20(name, symbol) { _mint(recipient, totalSupply); } } /* * @dev Implementation of the Initial Stake Offering (ISO). * The ISO is a decentralized token offering with trustless liquidity provisioning, * dividend accumulation and bonus rewards from staking. */ contract UnistakeTokenSale { using SafeMath for uint256; struct Contributor { uint256 phase; uint256 remainder; uint256 fromTotalDivs; } address payable public immutable wallet; uint256 public immutable totalSupplyR1; uint256 public immutable totalSupplyR2; uint256 public immutable totalSupplyR3; uint256 public immutable totalSupplyUniswap; uint256 public immutable rateR1; uint256 public immutable rateR2; uint256 public immutable rateR3; uint256 public immutable periodDurationR3; uint256 public immutable timeDelayR1; uint256 public immutable timeDelayR2; uint256 public immutable stakingPeriodR1; uint256 public immutable stakingPeriodR2; uint256 public immutable stakingPeriodR3; Token public immutable token; IUniswapV2Router02 public immutable uniswapRouter; uint256 public immutable decreasingPctToken; uint256 public immutable decreasingPctETH; uint256 public immutable decreasingPctRate; uint256 public immutable decreasingPctBonus; uint256 public immutable listingRate; address public immutable platformStakingContract; mapping(address => bool) private _contributor; mapping(address => Contributor) private _contributors; mapping(address => uint256)[3] private _contributions; bool[3] private _hasEnded; uint256[3] private _actualSupply; uint256 private _startTimeR2 = 2**256 - 1; uint256 private _startTimeR3 = 2**256 - 1; uint256 private _endTimeR3 = 2**256 - 1; mapping(address => bool)[3] private _hasWithdrawn; bool private _bonusOfferingActive; uint256 private _bonusOfferingActivated; uint256 private _bonusTotal; uint256 private _contributionsTotal; uint256 private _contributorsTotal; uint256 private _contributedFundsTotal; uint256 private _bonusReductionFactor; uint256 private _fundsWithdrawn; uint256 private _endedDayR3; uint256 private _latestStakingPlatformPayment; uint256 private _totalDividends; uint256 private _scaledRemainder; uint256 private _scaling = uint256(10) ** 12; uint256 private _phase = 1; uint256 private _totalRestakedDividends; mapping(address => uint256) private _restkedDividends; mapping(uint256 => uint256) private _payouts; event Staked( address indexed account, uint256 amount); event Claimed( address indexed account, uint256 amount); event Reclaimed( address indexed account, uint256 amount); event Withdrawn( address indexed account, uint256 amount); event Penalized( address indexed account, uint256 amount); event Ended( address indexed account, uint256 amount, uint256 time); event Splitted( address indexed account, uint256 amount1, uint256 amount2); event Bought( uint8 indexed round, address indexed account, uint256 amount); event Activated( bool status, uint256 time); /* * @dev Initialization of the ISO, * following arguments are provided via the constructor: * ---------------------------------------------------- * tokenArg - token offered in the ISO. * totalSupplyArg - total amount of tokens allocated for each round. * totalSupplyUniswapArg - amount of tokens that will be sent to uniswap. * ratesArg - contribution ratio ETH:Token for each round. * periodDurationR3 - duration of a day during round 3. * timeDelayR1Arg - time delay between round 1 and round 2. * timeDelayR2Arg - time delay between round 2 and round 3. * stakingPeriodArg - staking duration required to get bonus tokens for each round. * uniswapRouterArg - contract address of the uniswap router object. * decreasingPctArg - decreasing percentages associated with: token, ETH, rate, and bonus. * listingRateArg - initial listing rate of the offered token. * platformStakingContractArg - contract address of the timed distribution contract. * walletArg - account address of the team wallet. * */ constructor( address tokenArg, uint256[3] memory totalSupplyArg, uint256 totalSupplyUniswapArg, uint256[3] memory ratesArg, uint256 periodDurationR3Arg, uint256 timeDelayR1Arg, uint256 timeDelayR2Arg, uint256[3] memory stakingPeriodArg, address uniswapRouterArg, uint256[4] memory decreasingPctArg, uint256 listingRateArg, address platformStakingContractArg, address payable walletArg ) public { for (uint256 j = 0; j < 3; j++) { require(totalSupplyArg[j] > 0, "The 'totalSupplyArg' argument must be larger than zero"); require(ratesArg[j] > 0, "The 'ratesArg' argument must be larger than zero"); require(stakingPeriodArg[j] > 0, "The 'stakingPeriodArg' argument must be larger than zero"); } for (uint256 j = 0; j < 4; j++) { require(decreasingPctArg[j] < 10000, "The 'decreasingPctArg' arguments must be less than 100 percent"); } require(totalSupplyUniswapArg > 0, "The 'totalSupplyUniswapArg' argument must be larger than zero"); require(periodDurationR3Arg > 0, "The 'slotDurationR3Arg' argument must be larger than zero"); require(tokenArg != address(0), "The 'tokenArg' argument cannot be the zero address"); require(uniswapRouterArg != address(0), "The 'uniswapRouterArg' argument cannot be the zero addresss"); require(listingRateArg > 0, "The 'listingRateArg' argument must be larger than zero"); require(platformStakingContractArg != address(0), "The 'vestingContractArg' argument cannot be the zero address"); require(walletArg != address(0), "The 'walletArg' argument cannot be the zero address"); token = Token(tokenArg); totalSupplyR1 = totalSupplyArg[0]; totalSupplyR2 = totalSupplyArg[1]; totalSupplyR3 = totalSupplyArg[2]; totalSupplyUniswap = totalSupplyUniswapArg; periodDurationR3 = periodDurationR3Arg; timeDelayR1 = timeDelayR1Arg; timeDelayR2 = timeDelayR2Arg; rateR1 = ratesArg[0]; rateR2 = ratesArg[1]; rateR3 = ratesArg[2]; stakingPeriodR1 = stakingPeriodArg[0]; stakingPeriodR2 = stakingPeriodArg[1]; stakingPeriodR3 = stakingPeriodArg[2]; uniswapRouter = IUniswapV2Router02(uniswapRouterArg); decreasingPctToken = decreasingPctArg[0]; decreasingPctETH = decreasingPctArg[1]; decreasingPctRate = decreasingPctArg[2]; decreasingPctBonus = decreasingPctArg[3]; listingRate = listingRateArg; platformStakingContract = platformStakingContractArg; wallet = walletArg; } /** * @dev The fallback function is used for all contributions * during the ISO. The function monitors the current * round and manages token contributions accordingly. */ receive() external payable { if (token.balanceOf(address(this)) > 0) { uint8 currentRound = _calculateCurrentRound(); if (currentRound == 0) { _buyTokenR1(); } else if (currentRound == 1) { _buyTokenR2(); } else if (currentRound == 2) { _buyTokenR3(); } else { revert("The stake offering rounds are not active"); } } else { revert("The stake offering must be active"); } } /** * @dev Wrapper around the round 3 closing function. */ function closeR3() external { uint256 period = _calculatePeriod(block.timestamp); _closeR3(period); } /** * @dev This function prepares the staking and bonus reward settings * and it also provides liquidity to a freshly created uniswap pair. */ function activateStakesAndUniswapLiquidity() external { require(_hasEnded[0] && _hasEnded[1] && _hasEnded[2], "all rounds must have ended"); require(!_bonusOfferingActive, "the bonus offering and uniswap paring can only be done once per ISO"); uint256[3] memory bonusSupplies = [ (_actualSupply[0].mul(_bonusReductionFactor)).div(10000), (_actualSupply[1].mul(_bonusReductionFactor)).div(10000), (_actualSupply[2].mul(_bonusReductionFactor)).div(10000) ]; uint256 totalSupply = totalSupplyR1.add(totalSupplyR2).add(totalSupplyR3); uint256 soldSupply = _actualSupply[0].add(_actualSupply[1]).add(_actualSupply[2]); uint256 unsoldSupply = totalSupply.sub(soldSupply); uint256 exceededBonus = totalSupply .sub(bonusSupplies[0]) .sub(bonusSupplies[1]) .sub(bonusSupplies[2]); uint256 exceededUniswapAmount = _createUniswapPair(_endedDayR3); _bonusOfferingActive = true; _bonusOfferingActivated = block.timestamp; _bonusTotal = bonusSupplies[0].add(bonusSupplies[1]).add(bonusSupplies[2]); _contributionsTotal = soldSupply; _distribute(unsoldSupply.add(exceededBonus).add(exceededUniswapAmount)); emit Activated(true, block.timestamp); } /** * @dev This function allows the caller to stake claimable dividends. */ function restakeDividends() external { uint256 pending = _pendingDividends(msg.sender); pending = pending.add(_contributors[msg.sender].remainder); require(pending >= 0, "You do not have dividends to restake"); _restkedDividends[msg.sender] = _restkedDividends[msg.sender].add(pending); _totalRestakedDividends = _totalRestakedDividends.add(pending); _bonusTotal = _bonusTotal.sub(pending); _contributors[msg.sender].phase = _phase; _contributors[msg.sender].remainder = 0; _contributors[msg.sender].fromTotalDivs = _totalDividends; emit Staked(msg.sender, pending); } /** * @dev This function is called by contributors to * withdraw round 1 tokens. * ----------------------------------------------------- * Withdrawing tokens might result in bonus tokens, dividends, * or similar (based on the staking duration of the contributor). * */ function withdrawR1Tokens() external { require(_bonusOfferingActive, "The bonus offering is not active yet"); _withdrawTokens(0); } /** * @dev This function is called by contributors to * withdraw round 2 tokens. * ----------------------------------------------------- * Withdrawing tokens might result in bonus tokens, dividends, * or similar (based on the staking duration of the contributor). * */ function withdrawR2Tokens() external { require(_bonusOfferingActive, "The bonus offering is not active yet"); _withdrawTokens(1); } /** * @dev This function is called by contributors to * withdraw round 3 tokens. * ----------------------------------------------------- * Withdrawing tokens might result in bonus tokens, dividends, * or similar (based on the staking duration of the contributor). * */ function withdrawR3Tokens() external { require(_bonusOfferingActive, "The bonus offering is not active yet"); _withdrawTokens(2); } /** * @dev wrapper around the withdrawal of funds function. */ function withdrawFunds() external { uint256 amount = ((address(this).balance).sub(_fundsWithdrawn)).div(2); _withdrawFunds(amount); } /** * @dev Returns the total amount of restaked dividends in the ISO. */ function getRestakedDividendsTotal() external view returns (uint256) { return _totalRestakedDividends; } /** * @dev Returns the total staking bonuses in the ISO. */ function getStakingBonusesTotal() external view returns (uint256) { return _bonusTotal; } /** * @dev Returns the latest amount of tokens sent to the timed distribution contract. */ function getLatestStakingPlatformPayment() external view returns (uint256) { return _latestStakingPlatformPayment; } /** * @dev Returns the current day of round 3. */ function getCurrentDayR3() external view returns (uint256) { if (_endedDayR3 != 0) { return _endedDayR3; } return _calculatePeriod(block.timestamp); } /** * @dev Returns the ending day of round 3. */ function getEndedDayR3() external view returns (uint256) { return _endedDayR3; } /** * @dev Returns the start time of round 2. */ function getR2Start() external view returns (uint256) { return _startTimeR2; } /** * @dev Returns the start time of round 3. */ function getR3Start() external view returns (uint256) { return _startTimeR3; } /** * @dev Returns the end time of round 3. */ function getR3End() external view returns (uint256) { return _endTimeR3; } /** * @dev Returns the total amount of contributors in the ISO. */ function getContributorsTotal() external view returns (uint256) { return _contributorsTotal; } /** * @dev Returns the total amount of contributed funds (ETH) in the ISO */ function getContributedFundsTotal() external view returns (uint256) { return _contributedFundsTotal; } /** * @dev Returns the current round of the ISO. */ function getCurrentRound() external view returns (uint8) { uint8 round = _calculateCurrentRound(); if (round == 0 && !_hasEnded[0]) { return 1; } if (round == 1 && !_hasEnded[1] && _hasEnded[0]) { if (block.timestamp <= _startTimeR2) { return 0; } return 2; } if (round == 2 && !_hasEnded[2] && _hasEnded[1]) { if (block.timestamp <= _startTimeR3) { return 0; } return 3; } else { return 0; } } /** * @dev Returns whether round 1 has ended or not. */ function hasR1Ended() external view returns (bool) { return _hasEnded[0]; } /** * @dev Returns whether round 2 has ended or not. */ function hasR2Ended() external view returns (bool) { return _hasEnded[1]; } /** * @dev Returns whether round 3 has ended or not. */ function hasR3Ended() external view returns (bool) { return _hasEnded[2]; } /** * @dev Returns the remaining time delay between round 1 and round 2. */ function getRemainingTimeDelayR1R2() external view returns (uint256) { if (timeDelayR1 > 0) { if (_hasEnded[0] && !_hasEnded[1]) { if (_startTimeR2.sub(block.timestamp) > 0) { return _startTimeR2.sub(block.timestamp); } else { return 0; } } else { return 0; } } else { return 0; } } /** * @dev Returns the remaining time delay between round 2 and round 3. */ function getRemainingTimeDelayR2R3() external view returns (uint256) { if (timeDelayR2 > 0) { if (_hasEnded[0] && _hasEnded[1] && !_hasEnded[2]) { if (_startTimeR3.sub(block.timestamp) > 0) { return _startTimeR3.sub(block.timestamp); } else { return 0; } } else { return 0; } } else { return 0; } } /** * @dev Returns the total sales for round 1. */ function getR1Sales() external view returns (uint256) { return _actualSupply[0]; } /** * @dev Returns the total sales for round 2. */ function getR2Sales() external view returns (uint256) { return _actualSupply[1]; } /** * @dev Returns the total sales for round 3. */ function getR3Sales() external view returns (uint256) { return _actualSupply[2]; } /** * @dev Returns whether the staking- and bonus functionality has been activated or not. */ function getStakingActivationStatus() external view returns (bool) { return _bonusOfferingActive; } /** * @dev This function allows the caller to withdraw claimable dividends. */ function claimDividends() public { if (_totalDividends > _contributors[msg.sender].fromTotalDivs) { uint256 pending = _pendingDividends(msg.sender); pending = pending.add(_contributors[msg.sender].remainder); require(pending >= 0, "You do not have dividends to claim"); _contributors[msg.sender].phase = _phase; _contributors[msg.sender].remainder = 0; _contributors[msg.sender].fromTotalDivs = _totalDividends; _bonusTotal = _bonusTotal.sub(pending); require(token.transfer(msg.sender, pending), "Error in sending reward from contract"); emit Claimed(msg.sender, pending); } } /** * @dev This function allows the caller to withdraw restaked dividends. */ function withdrawRestakedDividends() public { uint256 amount = _restkedDividends[msg.sender]; require(amount >= 0, "You do not have restaked dividends to withdraw"); claimDividends(); _restkedDividends[msg.sender] = 0; _totalRestakedDividends = _totalRestakedDividends.sub(amount); token.transfer(msg.sender, amount); emit Reclaimed(msg.sender, amount); } /** * @dev Returns claimable dividends. */ function getDividends(address accountArg) public view returns (uint256) { uint256 amount = ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))).div(_scaling); amount += ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))) % _scaling ; return (amount.add(_contributors[msg.sender].remainder)); } /** * @dev Returns restaked dividends. */ function getRestakedDividends(address accountArg) public view returns (uint256) { return _restkedDividends[accountArg]; } /** * @dev Returns round 1 contributions of an account. */ function getR1Contribution(address accountArg) public view returns (uint256) { return _contributions[0][accountArg]; } /** * @dev Returns round 2 contributions of an account. */ function getR2Contribution(address accountArg) public view returns (uint256) { return _contributions[1][accountArg]; } /** * @dev Returns round 3 contributions of an account. */ function getR3Contribution(address accountArg) public view returns (uint256) { return _contributions[2][accountArg]; } /** * @dev Returns the total contributions of an account. */ function getContributionTotal(address accountArg) public view returns (uint256) { uint256 contributionR1 = getR1Contribution(accountArg); uint256 contributionR2 = getR2Contribution(accountArg); uint256 contributionR3 = getR3Contribution(accountArg); uint256 restaked = getRestakedDividends(accountArg); return contributionR1.add(contributionR2).add(contributionR3).add(restaked); } /** * @dev Returns the total contributions in the ISO (including restaked dividends). */ function getContributionsTotal() public view returns (uint256) { return _contributionsTotal.add(_totalRestakedDividends); } /** * @dev Returns expected round 1 staking bonus for an account. */ function getStakingBonusR1(address accountArg) public view returns (uint256) { uint256 contribution = _contributions[0][accountArg]; return (contribution.mul(_bonusReductionFactor)).div(10000); } /** * @dev Returns expected round 2 staking bonus for an account. */ function getStakingBonusR2(address accountArg) public view returns (uint256) { uint256 contribution = _contributions[1][accountArg]; return (contribution.mul(_bonusReductionFactor)).div(10000); } /** * @dev Returns expected round 3 staking bonus for an account. */ function getStakingBonusR3(address accountArg) public view returns (uint256) { uint256 contribution = _contributions[2][accountArg]; return (contribution.mul(_bonusReductionFactor)).div(10000); } /** * @dev Returns the total expected staking bonuses for an account. */ function getStakingBonusTotal(address accountArg) public view returns (uint256) { uint256 stakeR1 = getStakingBonusR1(accountArg); uint256 stakeR2 = getStakingBonusR2(accountArg); uint256 stakeR3 = getStakingBonusR3(accountArg); return stakeR1.add(stakeR2).add(stakeR3); } /** * @dev This function handles distribution of extra supply. */ function _distribute(uint256 amountArg) private { uint256 vested = amountArg.div(2); uint256 burned = amountArg.sub(vested); token.transfer(platformStakingContract, vested); token.burn(burned); } /** * @dev This function handles calculation of token withdrawals * (it also withdraws dividends and restaked dividends * during certain circumstances). */ function _withdrawTokens(uint8 indexArg) private { require(_hasEnded[0] && _hasEnded[1] && _hasEnded[2], "The rounds must be inactive before any tokens can be withdrawn"); require(!_hasWithdrawn[indexArg][msg.sender], "The caller must have withdrawable tokens available from this round"); claimDividends(); uint256 amount = _contributions[indexArg][msg.sender]; uint256 amountBonus = (amount.mul(_bonusReductionFactor)).div(10000); _contributions[indexArg][msg.sender] = _contributions[indexArg][msg.sender].sub(amount); _contributionsTotal = _contributionsTotal.sub(amount); uint256 contributions = getContributionTotal(msg.sender); uint256 restaked = getRestakedDividends(msg.sender); if (contributions.sub(restaked) == 0) withdrawRestakedDividends(); uint pending = _pendingDividends(msg.sender); _contributors[msg.sender].remainder = (_contributors[msg.sender].remainder).add(pending); _contributors[msg.sender].fromTotalDivs = _totalDividends; _contributors[msg.sender].phase = _phase; _hasWithdrawn[indexArg][msg.sender] = true; token.transfer(msg.sender, amount); _endStake(indexArg, msg.sender, amountBonus); } /** * @dev This function handles fund withdrawals. */ function _withdrawFunds(uint256 amountArg) private { require(msg.sender == wallet, "The caller must be the specified funds wallet of the team"); require(amountArg <= ((address(this).balance.sub(_fundsWithdrawn)).div(2)), "The 'amountArg' argument exceeds the limit"); require(!_hasEnded[2], "The third round is not active"); _fundsWithdrawn = _fundsWithdrawn.add(amountArg); wallet.transfer(amountArg); } /** * @dev This function handles token purchases for round 1. */ function _buyTokenR1() private { if (token.balanceOf(address(this)) > 0) { require(!_hasEnded[0], "The first round must be active"); bool isRoundEnded = _buyToken(0, rateR1, totalSupplyR1); if (isRoundEnded == true) { _startTimeR2 = block.timestamp.add(timeDelayR1); } } else { revert("The stake offering must be active"); } } /** * @dev This function handles token purchases for round 2. */ function _buyTokenR2() private { require(_hasEnded[0] && !_hasEnded[1], "The first round one must not be active while the second round must be active"); require(block.timestamp >= _startTimeR2, "The time delay between the first round and the second round must be surpassed"); bool isRoundEnded = _buyToken(1, rateR2, totalSupplyR2); if (isRoundEnded == true) { _startTimeR3 = block.timestamp.add(timeDelayR2); } } /** * @dev This function handles token purchases for round 3. */ function _buyTokenR3() private { require(_hasEnded[1] && !_hasEnded[2], "The second round one must not be active while the third round must be active"); require(block.timestamp >= _startTimeR3, "The time delay between the first round and the second round must be surpassed"); uint256 period = _calculatePeriod(block.timestamp); (bool isRoundClosed, uint256 actualPeriodTotalSupply) = _closeR3(period); if (!isRoundClosed) { bool isRoundEnded = _buyToken(2, rateR3, actualPeriodTotalSupply); if (isRoundEnded == true) { _endTimeR3 = block.timestamp; uint256 endingPeriod = _calculateEndingPeriod(); uint256 reductionFactor = _calculateBonusReductionFactor(endingPeriod); _bonusReductionFactor = reductionFactor; _endedDayR3 = endingPeriod; } } } /** * @dev This function handles bonus payouts and the split of forfeited bonuses. */ function _endStake(uint256 indexArg, address accountArg, uint256 amountArg) private { uint256 elapsedTime = (block.timestamp).sub(_bonusOfferingActivated); uint256 payout; uint256 duration = _getDuration(indexArg); if (elapsedTime >= duration) { payout = amountArg; } else if (elapsedTime >= duration.mul(3).div(4) && elapsedTime < duration) { payout = amountArg.mul(3).div(4); } else if (elapsedTime >= duration.div(2) && elapsedTime < duration.mul(3).div(4)) { payout = amountArg.div(2); } else if (elapsedTime >= duration.div(4) && elapsedTime < duration.div(2)) { payout = amountArg.div(4); } else { payout = 0; } _split(amountArg.sub(payout)); if (payout != 0) { token.transfer(accountArg, payout); } emit Ended(accountArg, amountArg, block.timestamp); } /** * @dev This function splits forfeited bonuses into dividends * and to timed distribution contract accordingly. */ function _split(uint256 amountArg) private { if (amountArg == 0) { return; } uint256 dividends = amountArg.div(2); uint256 platformStakingShare = amountArg.sub(dividends); _bonusTotal = _bonusTotal.sub(platformStakingShare); _latestStakingPlatformPayment = platformStakingShare; token.transfer(platformStakingContract, platformStakingShare); _addDividends(_latestStakingPlatformPayment); emit Splitted(msg.sender, dividends, platformStakingShare); } /** * @dev this function handles addition of new dividends. */ function _addDividends(uint256 bonusArg) private { uint256 latest = (bonusArg.mul(_scaling)).add(_scaledRemainder); uint256 dividendPerToken = latest.div(_contributionsTotal.add(_totalRestakedDividends)); _scaledRemainder = latest.mod(_contributionsTotal.add(_totalRestakedDividends)); _totalDividends = _totalDividends.add(dividendPerToken); _payouts[_phase] = _payouts[_phase-1].add(dividendPerToken); _phase++; } /** * @dev returns pending dividend rewards. */ function _pendingDividends(address accountArg) private returns (uint256) { uint256 amount = ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))).div(_scaling); _contributors[accountArg].remainder += ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))) % _scaling ; return amount; } /** * @dev This function creates a uniswap pair and handles liquidity provisioning. * Returns the uniswap token leftovers. */ function _createUniswapPair(uint256 endingPeriodArg) private returns (uint256) { uint256 listingPrice = endingPeriodArg.mul(decreasingPctRate); uint256 ethDecrease = uint256(5000).sub(endingPeriodArg.mul(decreasingPctETH)); uint256 ethOnUniswap = (_contributedFundsTotal.mul(ethDecrease)).div(10000); ethOnUniswap = ethOnUniswap <= (address(this).balance) ? ethOnUniswap : (address(this).balance); uint256 tokensOnUniswap = ethOnUniswap .mul(listingRate) .mul(10000) .div(uint256(10000).sub(listingPrice)) .div(100000); token.approve(address(uniswapRouter), tokensOnUniswap); uniswapRouter.addLiquidityETH.value(ethOnUniswap)( address(token), tokensOnUniswap, 0, 0, wallet, block.timestamp ); wallet.transfer(address(this).balance); return (totalSupplyUniswap.sub(tokensOnUniswap)); } /** * @dev this function will close round 3 if based on day and sold supply. * Returns whether a particular round has ended or not and * the max supply of a particular day during round 3. */ function _closeR3(uint256 periodArg) private returns (bool isRoundEnded, uint256 maxPeriodSupply) { require(_hasEnded[0] && _hasEnded[1] && !_hasEnded[2], 'Round 3 has ended or Round 1 or 2 have not ended yet'); require(block.timestamp >= _startTimeR3, 'Pause period between Round 2 and 3'); uint256 decreasingTokenNumber = totalSupplyR3.mul(decreasingPctToken).div(10000); maxPeriodSupply = totalSupplyR3.sub(periodArg.mul(decreasingTokenNumber)); if (maxPeriodSupply <= _actualSupply[2]) { msg.sender.transfer(msg.value); _hasEnded[2] = true; _endTimeR3 = block.timestamp; uint256 endingPeriod = _calculateEndingPeriod(); uint256 reductionFactor = _calculateBonusReductionFactor(endingPeriod); _endedDayR3 = endingPeriod; _bonusReductionFactor = reductionFactor; return (true, maxPeriodSupply); } else { return (false, maxPeriodSupply); } } /** * @dev this function handles low level token purchases. * Returns whether a particular round has ended or not. */ function _buyToken(uint8 indexArg, uint256 rateArg, uint256 totalSupplyArg) private returns (bool isRoundEnded) { uint256 tokensNumber = msg.value.mul(rateArg).div(100000); uint256 actualTotalBalance = _actualSupply[indexArg]; uint256 newTotalRoundBalance = actualTotalBalance.add(tokensNumber); if (!_contributor[msg.sender]) { _contributor[msg.sender] = true; _contributorsTotal++; } if (newTotalRoundBalance < totalSupplyArg) { _contributions[indexArg][msg.sender] = _contributions[indexArg][msg.sender].add(tokensNumber); _actualSupply[indexArg] = newTotalRoundBalance; _contributedFundsTotal = _contributedFundsTotal.add(msg.value); emit Bought(uint8(indexArg + 1), msg.sender, tokensNumber); return false; } else { uint256 availableTokens = totalSupplyArg.sub(actualTotalBalance); uint256 availableEth = availableTokens.mul(100000).div(rateArg); _contributions[indexArg][msg.sender] = _contributions[indexArg][msg.sender].add(availableTokens); _actualSupply[indexArg] = totalSupplyArg; _contributedFundsTotal = _contributedFundsTotal.add(availableEth); _hasEnded[indexArg] = true; msg.sender.transfer(msg.value.sub(availableEth)); emit Bought(uint8(indexArg + 1), msg.sender, availableTokens); return true; } } /** * @dev Returns the staking duration of a particular round. */ function _getDuration(uint256 indexArg) private view returns (uint256) { if (indexArg == 0) { return stakingPeriodR1; } if (indexArg == 1) { return stakingPeriodR2; } if (indexArg == 2) { return stakingPeriodR3; } } /** * @dev Returns the bonus reduction factor. */ function _calculateBonusReductionFactor(uint256 periodArg) private view returns (uint256) { uint256 reductionFactor = uint256(10000).sub(periodArg.mul(decreasingPctBonus)); return reductionFactor; } /** * @dev Returns the current round. */ function _calculateCurrentRound() private view returns (uint8) { if (!_hasEnded[0]) { return 0; } else if (_hasEnded[0] && !_hasEnded[1] && !_hasEnded[2]) { return 1; } else if (_hasEnded[0] && _hasEnded[1] && !_hasEnded[2]) { return 2; } else { return 2**8 - 1; } } /** * @dev Returns the current day. */ function _calculatePeriod(uint256 timeArg) private view returns (uint256) { uint256 period = ((timeArg.sub(_startTimeR3)).div(periodDurationR3)); uint256 maxPeriods = uint256(10000).div(decreasingPctToken); if (period > maxPeriods) { return maxPeriods; } return period; } /** * @dev Returns the ending day of round 3. */ function _calculateEndingPeriod() private view returns (uint256) { require(_endTimeR3 != (2**256) - 1, "The third round must be active"); uint256 endingPeriod = _calculatePeriod(_endTimeR3); return endingPeriod; } }
Returns round 2 contributions of an account./
function getR2Contribution(address accountArg) public view returns (uint256) { return _contributions[1][accountArg]; }
12,816,435
/** *Submitted for verification at Etherscan.io on 2022-05-05 */ //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 memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 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. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @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 FTM balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.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); } /** * @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"); } } } contract LasmVesting is ReentrancyGuard, Ownable { // Allocation distribution of the total supply. uint256 private constant E18 = 10 ** 18; uint256 private constant LOCKED_ALLOCATION = 160_000_000 * E18; uint256 private constant PUBLIC_SALE_ALLOCATION = 80_000_000 * E18; uint256 private constant TEAM_ALLOCATION_1 = 110_000_000 * E18; uint256 private constant TEAM_ALLOCATION_2 = 10_000_000 * E18; uint256 private constant PARTNERS_ALLOCATION = 40_000_000 * E18; uint256 private constant MARKETING_ALLOCATION = 40_000_000 * E18; uint256 private constant DEVELOPMENT_ALLOCATION = 80_000_000 * E18; uint256 private constant STAKING_ALLOCATION = 240_000_000 * E18; uint256 private constant AIRDROP_ALLOCATION = 40_000_000 * E18; // vesting wallets address private constant lockedWallet = address(0x35eb4C5e5b240C6Ec155516385Db59327B3415B1); address private constant managerWallet = address(0xA22Bf614Fa7Fe2486d2bdf9B1Ace730716caFa70); address private constant teamWallet = address(0xb37F5a0Da2630a9474791f606048538AEc5F1ca9); address private constant partnersWallet = address(0x6C53d1F3323Ca6F8a0d10Ed12B1248254DCd0453); address private constant marketingWallet = address(0x51f68ddA6470C0aE5B7383F2af3614C582D80A0F); address private constant developmentWallet = address(0xEf3fE1A4B8393ac016Ef57020c28E0487e0EdbDa); address private constant stakingRewardsWallet = address(0x4168CAc6FB9c95d19d8cAA39BfC0418ab41564C9); address private constant airdropWallet = address(0xe7bB7d8be65A11b4BA7141EE6E1CD85D13ad650C); uint256 private constant VESTING_END_AT = 4 * 365 days; // 48 months address public vestingToken; // ERC20 token that get vested. event TokenSet(address vestingToken); event Claimed(address indexed beneficiary, uint256 amount); struct Schedule { // Name of the template string templateName; // Tokens that were already claimed uint256 claimedTokens; // Start time of the schedule uint256 startTime; // Total amount of tokens uint256 allocation; // Schedule duration (How long the schedule will last) uint256 duration; // Cliff of the schedule. uint256 cliff; // Linear period of the schedule. uint256 linear; // Last time of Claimed uint256 lastClaimTime; } struct ClaimedEvent { // Index of the schedule list uint8 scheduleIndex; // Tokens that were only unlocked in this event uint256 claimedTokens; // Tokens that were already unlocked uint256 unlockedTokens; // Tokens that are locked yet uint256 lockedTokens; // Time of the current event uint256 eventTime; } Schedule[] public schedules; ClaimedEvent[] public scheduleEvents; mapping (address => uint8[]) public schedulesByOwner; mapping (string => uint8) public schedulesByName; mapping (string => address) public beneficiary; mapping (address => uint8[]) public eventsByScheduleBeneficiary; mapping (string => uint8[]) public eventsByScheduleName; constructor() { } /** * @dev Allow owner to set the token address that get vested. * @param tokenAddress Address of the BEP-20 token. */ function setToken(address tokenAddress) external onlyOwner { require(tokenAddress != address(0), "Vesting: ZERO_ADDRESS_NOT_ALLOWED"); require(vestingToken == address(0), "Vesting: ALREADY_SET"); vestingToken = tokenAddress; emit TokenSet(tokenAddress); } /** * @dev Allow owner to initiate the vesting schedule */ function initVestingSchedule() public onlyOwner { // For Locked allocation _createSchedule(lockedWallet, Schedule({ templateName : "Locked", claimedTokens : uint256(0), startTime : block.timestamp, allocation : LOCKED_ALLOCATION, duration : 93312000, // 36 Months (36 * 30 * 24 * 60 * 60) cliff : 62208000, // 24 Months (24 * 30 * 24 * 60 * 60) linear : 31104000, // 12 Months (12 * 30 * 24 * 60 * 60) lastClaimTime : 0 })); // For Public sale allocation _createSchedule(managerWallet, Schedule({ templateName : "PublicSale", claimedTokens : uint256(0), startTime : block.timestamp, allocation : PUBLIC_SALE_ALLOCATION, duration : 18144000, // 7 Months (7 * 30 * 24 * 60 * 60) cliff : 7776000, // 3 Months (4 * 30 * 24 * 60 * 60) linear : 10368000, // 4 Months (4 * 30 * 24 * 60 * 60) lastClaimTime : 0 })); // For Team allocation_1 _createSchedule(teamWallet, Schedule({ templateName : "Team_1", claimedTokens : uint256(0), startTime : block.timestamp, allocation : TEAM_ALLOCATION_1, duration : 93312000, // 36 Months (36 * 30 * 24 * 60 * 60) cliff : 7776000, // 3 Months ( 3 * 30 * 24 * 60 * 60) linear : 85536000, // 33 Months (33 * 30 * 24 * 60 * 60) lastClaimTime : 0 })); // For Team allocation_2 _createSchedule(teamWallet, Schedule({ templateName : "Team_2", claimedTokens : uint256(0), startTime : block.timestamp + 93312000, // After 36 Months of closing the Team Allocation_1 allocation : TEAM_ALLOCATION_2, duration : 31104000, // 12 Months (12 * 30 * 24 * 60 * 60) cliff : 0, linear : 31104000, // 12 Months (12 * 30 * 24 * 60 * 60) lastClaimTime : 0 })); // For Partners & Advisors allocation _createSchedule(partnersWallet, Schedule({ templateName : "Partners", claimedTokens : uint256(0), startTime : block.timestamp, allocation : PARTNERS_ALLOCATION, duration : 62208000, // 24 Months (24 * 30 * 24 * 60 * 60) cliff : 31104000, // 12 Months (12 * 30 * 24 * 60 * 60) linear : 31104000, // 12 Months (12 * 30 * 24 * 60 * 60) lastClaimTime : 0 })); // For Marketing allocation _createSchedule(marketingWallet, Schedule({ templateName : "Marketing", claimedTokens : uint256(0), startTime : block.timestamp, allocation : MARKETING_ALLOCATION, duration : 0, // 0 Months cliff : 0, // 0 Months linear : 0, // 0 Months lastClaimTime : 0 })); // For Development allocation _createSchedule(developmentWallet, Schedule({ templateName : "Development", claimedTokens : uint256(0), startTime : block.timestamp, allocation : DEVELOPMENT_ALLOCATION, duration : 0, // 0 Month cliff : 0, // 0 Month linear : 0, // 0 Month lastClaimTime : 0 })); // For P2E & Staking rewards allocation _createSchedule(stakingRewardsWallet, Schedule({ templateName : "Staking", claimedTokens : uint256(0), startTime : block.timestamp, allocation : STAKING_ALLOCATION, duration : 85536000, // 33 Months (33 * 30 * 24 * 60 * 60) cliff : 7776000, // 3 Months ( 3 * 30 * 24 * 60 * 60) linear : 77760000, // 30 Months (30 * 30 * 24 * 60 * 60) lastClaimTime : 0 })); // For Airdrop allocation _createSchedule(airdropWallet, Schedule({ templateName : "Airdrop", claimedTokens : uint256(0), startTime : block.timestamp, allocation : AIRDROP_ALLOCATION, duration : 0, // 0 Month cliff : 0, // 0 Month linear : 0, // 0 Month lastClaimTime : 0 })); } function _createSchedule(address _beneficiary, Schedule memory _schedule) internal { schedules.push(_schedule); uint8 index = uint8(schedules.length) - 1; schedulesByOwner[_beneficiary].push(index); schedulesByName[_schedule.templateName] = index; beneficiary[_schedule.templateName] = _beneficiary; } /** * @dev Check the amount of claimable token of the beneficiary. */ function pendingTokensByScheduleBeneficiary(address _account) public view returns (uint256) { uint8[] memory _indexs = schedulesByOwner[_account]; require(_indexs.length != uint256(0), "Vesting: NOT_AUTORIZE"); uint256 amount = 0; for (uint8 i = 0; i < _indexs.length; i++) { string memory _templateName = schedules[_indexs[i]].templateName; amount += pendingTokensByScheduleName(_templateName); } return amount; } /** * @dev Check the amount of claimable token of the schedule. */ function pendingTokensByScheduleName(string memory _templateName) public view returns (uint256) { uint8 index = schedulesByName[_templateName]; require(index >= 0 && index < schedules.length, "Vesting: NOT_SCHEDULE"); Schedule memory schedule = schedules[index]; uint256 vestedAmount = 0; if ( schedule.startTime + schedule.cliff >= block.timestamp || schedule.claimedTokens == schedule.allocation) { return 0; } if (schedule.duration == 0 && schedule.startTime <= block.timestamp) { vestedAmount = schedule.allocation; } else if (schedule.startTime + schedule.duration <= block.timestamp) { vestedAmount = schedule.allocation; } else { if (block.timestamp > schedule.startTime + schedule.cliff && schedule.linear > 0) { uint256 timePeriod = block.timestamp - schedule.startTime - schedule.cliff; uint256 unitPeriodAllocation = schedule.allocation / schedule.linear; vestedAmount = timePeriod * unitPeriodAllocation; } else return 0; } return vestedAmount - schedule.claimedTokens; } /** * @dev Allow the respective addresses claim the vested tokens. */ function claimByScheduleBeneficiary() external nonReentrant { require(vestingToken != address(0), "Vesting: VESTINGTOKEN_NO__SET"); uint8[] memory _indexs = schedulesByOwner[msg.sender]; require(_indexs.length != uint256(0), "Vesting: NOT_AUTORIZE"); uint256 amount = 0; uint8 index; for (uint8 i = 0; i < _indexs.length; i++) { index = _indexs[i]; string memory _templateName = schedules[index].templateName; uint256 claimAmount = pendingTokensByScheduleName(_templateName); if (claimAmount == 0) continue; schedules[index].claimedTokens += claimAmount; schedules[index].lastClaimTime = block.timestamp; amount += claimAmount; registerEvent(msg.sender, index, claimAmount); } require(amount > uint256(0), "Vesting: NO_VESTED_TOKENS"); SafeERC20.safeTransfer(IERC20(vestingToken), msg.sender, amount); emit Claimed(msg.sender, amount); } /** * @dev Allow the respective addresses claim the vested tokens of the schedule. */ function claimByScheduleName(string memory _templateName) external nonReentrant { require(vestingToken != address(0), "Vesting: VESTINGTOKEN_NO__SET"); uint8 index = schedulesByName[_templateName]; require(index >= 0 && index < schedules.length, "Vesting: NOT_SCHEDULE"); require(beneficiary[_templateName] == msg.sender, "Vesting: NOT_AUTORIZE"); uint256 claimAmount = pendingTokensByScheduleName(_templateName); require(claimAmount > uint256(0), "Vesting: NO_VESTED_TOKENS"); schedules[index].claimedTokens += claimAmount; schedules[index].lastClaimTime = block.timestamp; SafeERC20.safeTransfer(IERC20(vestingToken), msg.sender, claimAmount); registerEvent(msg.sender, index, claimAmount); emit Claimed(beneficiary[_templateName], claimAmount); } function registerEvent(address _account, uint8 _scheduleIndex, uint256 _claimedTokens) internal { Schedule memory schedule = schedules[_scheduleIndex]; scheduleEvents.push(ClaimedEvent({ scheduleIndex: _scheduleIndex, claimedTokens: _claimedTokens, unlockedTokens: schedule.claimedTokens, lockedTokens: schedule.allocation - schedule.claimedTokens, eventTime: schedule.lastClaimTime })); eventsByScheduleBeneficiary[_account].push(uint8(scheduleEvents.length) - 1); eventsByScheduleName[schedule.templateName].push(uint8(scheduleEvents.length) - 1); } /** * @dev Allow owner to withdraw the token from the contract. * @param tokenAddress Address of the BEP-20 token. * @param amount Amount of token that get skimmed out of the contract. * @param destination Whom token amount get transferred to. */ function withdraw(address tokenAddress, uint256 amount, address destination) external onlyOwner { require(vestingToken != address(0), "Vesting: VESTINGTOKEN_NO__SET"); require(block.timestamp > VESTING_END_AT, "Vesting: NOT_ALLOWED"); require(destination != address(0), "Vesting: ZERO_ADDRESS_NOT_ALLOWED"); require(amount <= IERC20(tokenAddress).balanceOf(address(this)), "Insufficient balance"); SafeERC20.safeTransfer(IERC20(tokenAddress), destination, amount); } }
Allow owner to initiate the vesting schedule/ For Locked allocation For Public sale allocation For Team allocation_1 For Team allocation_2 For Partners & Advisors allocation For Marketing allocation For Development allocation For P2E & Staking rewards allocation For Airdrop allocation
function initVestingSchedule() public onlyOwner { _createSchedule(lockedWallet, Schedule({ templateName : "Locked", claimedTokens : uint256(0), startTime : block.timestamp, allocation : LOCKED_ALLOCATION, lastClaimTime : 0 })); _createSchedule(managerWallet, Schedule({ templateName : "PublicSale", claimedTokens : uint256(0), startTime : block.timestamp, allocation : PUBLIC_SALE_ALLOCATION, lastClaimTime : 0 })); _createSchedule(teamWallet, Schedule({ templateName : "Team_1", claimedTokens : uint256(0), startTime : block.timestamp, allocation : TEAM_ALLOCATION_1, lastClaimTime : 0 })); _createSchedule(teamWallet, Schedule({ templateName : "Team_2", claimedTokens : uint256(0), allocation : TEAM_ALLOCATION_2, cliff : 0, lastClaimTime : 0 })); _createSchedule(partnersWallet, Schedule({ templateName : "Partners", claimedTokens : uint256(0), startTime : block.timestamp, allocation : PARTNERS_ALLOCATION, lastClaimTime : 0 })); _createSchedule(marketingWallet, Schedule({ templateName : "Marketing", claimedTokens : uint256(0), startTime : block.timestamp, allocation : MARKETING_ALLOCATION, lastClaimTime : 0 })); _createSchedule(developmentWallet, Schedule({ templateName : "Development", claimedTokens : uint256(0), startTime : block.timestamp, allocation : DEVELOPMENT_ALLOCATION, lastClaimTime : 0 })); _createSchedule(stakingRewardsWallet, Schedule({ templateName : "Staking", claimedTokens : uint256(0), startTime : block.timestamp, allocation : STAKING_ALLOCATION, lastClaimTime : 0 })); _createSchedule(airdropWallet, Schedule({ templateName : "Airdrop", claimedTokens : uint256(0), startTime : block.timestamp, allocation : AIRDROP_ALLOCATION, lastClaimTime : 0 })); }
1,988,733
./partial_match/9000/0xBd7BAE48164F376c12D8e47152c35d5912A06672/sources/contracts/FluxPriceFeed.sol
details about the most recent report return _latestAnswer value from latest report return _latestTimestamp when the latest report was transmitted/
function latestTransmissionDetails() external view returns (int192 _latestAnswer, uint64 _latestTimestamp) { return (transmissions[latestAggregatorRoundId].answer, transmissions[latestAggregatorRoundId].timestamp); }
11,342,603
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {IBToken} from "../interfaces/IBToken.sol"; import {IDebtToken} from "../interfaces/IDebtToken.sol"; import {ILendPoolLoan} from "../interfaces/ILendPoolLoan.sol"; import {ILendPool} from "../interfaces/ILendPool.sol"; import {IReserveOracleGetter} from "../interfaces/IReserveOracleGetter.sol"; import {INFTOracleGetter} from "../interfaces/INFTOracleGetter.sol"; import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol"; import {Errors} from "../libraries/helpers/Errors.sol"; import {WadRayMath} from "../libraries/math/WadRayMath.sol"; import {GenericLogic} from "../libraries/logic/GenericLogic.sol"; import {PercentageMath} from "../libraries/math/PercentageMath.sol"; import {ReserveLogic} from "../libraries/logic/ReserveLogic.sol"; import {NftLogic} from "../libraries/logic/NftLogic.sol"; import {ValidationLogic} from "../libraries/logic/ValidationLogic.sol"; import {ReserveConfiguration} from "../libraries/configuration/ReserveConfiguration.sol"; import {NftConfiguration} from "../libraries/configuration/NftConfiguration.sol"; import {DataTypes} from "../libraries/types/DataTypes.sol"; import {LendPoolStorage} from "./LendPoolStorage.sol"; import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import {IERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import {IERC721ReceiverUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {ContextUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; /** * @title LendPool contract * @dev Main point of interaction with an Bend protocol's market * - Users can: * # Deposit * # Withdraw * # Borrow * # Repay * # Auction * # Liquidate * - To be covered by a proxy contract, owned by the LendPoolAddressesProvider of the specific market * - All admin functions are callable by the LendPoolConfigurator contract defined also in the * LendPoolAddressesProvider * @author Bend **/ contract LendPool is Initializable, ILendPool, LendPoolStorage, ContextUpgradeable, IERC721ReceiverUpgradeable { using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; using ReserveLogic for DataTypes.ReserveData; using NftLogic for DataTypes.NftData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using NftConfiguration for DataTypes.NftConfigurationMap; modifier whenNotPaused() { _whenNotPaused(); _; } modifier onlyLendPoolConfigurator() { _onlyLendPoolConfigurator(); _; } function _whenNotPaused() internal view { require(!_paused, Errors.LP_IS_PAUSED); } function _onlyLendPoolConfigurator() internal view { require(_addressesProvider.getLendPoolConfigurator() == _msgSender(), Errors.LP_CALLER_NOT_LEND_POOL_CONFIGURATOR); } /** * @dev Function is invoked by the proxy contract when the LendPool contract is added to the * LendPoolAddressesProvider of the market. * - Caching the address of the LendPoolAddressesProvider in order to reduce gas consumption * on subsequent operations * @param provider The address of the LendPoolAddressesProvider **/ function initialize(ILendPoolAddressesProvider provider) public initializer { _maxNumberOfReserves = 32; _maxNumberOfNfts = 256; _addressesProvider = provider; } /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying bTokens. * - E.g. User deposits 100 USDC and gets in return 100 bUSDC * @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 bTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of bTokens * 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 override whenNotPaused { require(onBehalfOf != address(0), Errors.VL_INVALID_ONBEHALFOF_ADDRESS); DataTypes.ReserveData storage reserve = _reserves[asset]; address bToken = reserve.bTokenAddress; require(bToken != address(0), Errors.VL_INVALID_RESERVE_ADDRESS); ValidationLogic.validateDeposit(reserve, amount); reserve.updateState(); reserve.updateInterestRates(asset, bToken, amount, 0); IERC20Upgradeable(asset).safeTransferFrom(_msgSender(), bToken, amount); IBToken(bToken).mint(onBehalfOf, amount, reserve.liquidityIndex); emit Deposit(_msgSender(), asset, amount, onBehalfOf, referralCode); } /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent bTokens owned * E.g. User has 100 bUSDC, calls withdraw() and receives 100 USDC, burning the 100 bUSDC * @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 bToken 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 override whenNotPaused returns (uint256) { require(to != address(0), Errors.VL_INVALID_TARGET_ADDRESS); DataTypes.ReserveData storage reserve = _reserves[asset]; address bToken = reserve.bTokenAddress; require(bToken != address(0), Errors.VL_INVALID_RESERVE_ADDRESS); uint256 userBalance = IBToken(bToken).balanceOf(_msgSender()); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw(reserve, amountToWithdraw, userBalance); reserve.updateState(); reserve.updateInterestRates(asset, bToken, 0, amountToWithdraw); IBToken(bToken).burn(_msgSender(), to, amountToWithdraw, reserve.liquidityIndex); emit Withdraw(_msgSender(), asset, amountToWithdraw, to); return amountToWithdraw; } struct ExecuteBorrowLocalVars { address initiator; uint256 ltv; uint256 liquidationThreshold; uint256 liquidationBonus; uint256 loanId; address reserveOracle; address nftOracle; address loanAddress; } /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset * - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet * and lock collateral asset in contract * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param nftAsset The address of the underlying nft used as collateral * @param nftTokenId The token ID of the underlying nft used as collateral * @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral * @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 borrow( address asset, uint256 amount, address nftAsset, uint256 nftTokenId, address onBehalfOf, uint16 referralCode ) external override whenNotPaused { require(onBehalfOf != address(0), Errors.VL_INVALID_ONBEHALFOF_ADDRESS); ExecuteBorrowLocalVars memory vars; vars.initiator = _msgSender(); DataTypes.ReserveData storage reserveData = _reserves[asset]; DataTypes.NftData storage nftData = _nfts[nftAsset]; // update state MUST BEFORE get borrow amount which is depent on latest borrow index reserveData.updateState(); // Convert asset amount to ETH vars.reserveOracle = _addressesProvider.getReserveOracle(); vars.nftOracle = _addressesProvider.getNFTOracle(); vars.loanAddress = _addressesProvider.getLendPoolLoan(); vars.loanId = ILendPoolLoan(vars.loanAddress).getCollateralLoanId(nftAsset, nftTokenId); ValidationLogic.validateBorrow( onBehalfOf, asset, amount, reserveData, nftAsset, nftData, vars.loanAddress, vars.loanId, vars.reserveOracle, vars.nftOracle ); if (vars.loanId == 0) { IERC721Upgradeable(nftAsset).safeTransferFrom(_msgSender(), address(this), nftTokenId); vars.loanId = ILendPoolLoan(vars.loanAddress).createLoan( vars.initiator, onBehalfOf, nftAsset, nftTokenId, nftData.bNftAddress, asset, amount, reserveData.variableBorrowIndex ); } else { ILendPoolLoan(vars.loanAddress).updateLoan( vars.initiator, vars.loanId, amount, 0, reserveData.variableBorrowIndex ); } IDebtToken(reserveData.debtTokenAddress).mint(vars.initiator, onBehalfOf, amount, reserveData.variableBorrowIndex); // update interest rate according latest borrow amount (utilizaton) reserveData.updateInterestRates(asset, reserveData.bTokenAddress, 0, amount); IBToken(reserveData.bTokenAddress).transferUnderlyingTo(vars.initiator, amount); emit Borrow( vars.initiator, asset, amount, nftAsset, nftTokenId, onBehalfOf, reserveData.currentVariableBorrowRate, vars.loanId, referralCode ); } struct RepayLocalVars { address initiator; address poolLoan; address onBehalfOf; uint256 loanId; bool isUpdate; uint256 borrowAmount; uint256 repayAmount; } /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent loan owned * - E.g. User repays 100 USDC, burning loan and receives collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param amount The amount to repay **/ function repay( address nftAsset, uint256 nftTokenId, uint256 amount ) external override whenNotPaused returns (uint256, bool) { RepayLocalVars memory vars; vars.initiator = _msgSender(); vars.poolLoan = _addressesProvider.getLendPoolLoan(); vars.loanId = ILendPoolLoan(vars.poolLoan).getCollateralLoanId(nftAsset, nftTokenId); require(vars.loanId != 0, Errors.LP_NFT_IS_NOT_USED_AS_COLLATERAL); DataTypes.LoanData memory loanData = ILendPoolLoan(vars.poolLoan).getLoan(vars.loanId); DataTypes.ReserveData storage reserveData = _reserves[loanData.reserveAsset]; DataTypes.NftData storage nftData = _nfts[loanData.nftAsset]; // update state MUST BEFORE get borrow amount which is depent on latest borrow index reserveData.updateState(); (, vars.borrowAmount) = ILendPoolLoan(vars.poolLoan).getLoanReserveBorrowAmount(vars.loanId); ValidationLogic.validateRepay(reserveData, nftData, loanData, amount, vars.borrowAmount); vars.repayAmount = vars.borrowAmount; vars.isUpdate = false; if (amount < vars.repayAmount) { vars.isUpdate = true; vars.repayAmount = amount; } if (vars.isUpdate) { ILendPoolLoan(vars.poolLoan).updateLoan( vars.initiator, vars.loanId, 0, vars.repayAmount, reserveData.variableBorrowIndex ); } else { ILendPoolLoan(vars.poolLoan).repayLoan( vars.initiator, vars.loanId, nftData.bNftAddress, vars.repayAmount, reserveData.variableBorrowIndex ); } IDebtToken(reserveData.debtTokenAddress).burn(loanData.borrower, vars.repayAmount, reserveData.variableBorrowIndex); // update interest rate according latest borrow amount (utilizaton) reserveData.updateInterestRates(loanData.reserveAsset, reserveData.bTokenAddress, vars.repayAmount, 0); // transfer repay amount to bToken IERC20Upgradeable(loanData.reserveAsset).safeTransferFrom( vars.initiator, reserveData.bTokenAddress, vars.repayAmount ); // transfer erc721 to borrower if (!vars.isUpdate) { IERC721Upgradeable(loanData.nftAsset).safeTransferFrom(address(this), loanData.borrower, nftTokenId); } emit Repay( vars.initiator, loanData.reserveAsset, vars.repayAmount, loanData.nftAsset, loanData.nftTokenId, loanData.borrower, vars.loanId ); return (vars.repayAmount, !vars.isUpdate); } /** * @dev Function to auction a non-healthy position collateral-wise * - The bidder want to buy collateral asset of the user getting liquidated * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param bidPrice The bid price of the bidder want to buy underlying NFT * @param onBehalfOf Address of the user who will get the underlying NFT, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of NFT * is a different wallet **/ function auction( address nftAsset, uint256 nftTokenId, uint256 bidPrice, address onBehalfOf ) external override whenNotPaused { address poolLiquidator = _addressesProvider.getLendPoolLiquidator(); //solium-disable-next-line (bool success, bytes memory result) = poolLiquidator.delegatecall( abi.encodeWithSignature("auction(address,uint256,uint256,address)", nftAsset, nftTokenId, bidPrice, onBehalfOf) ); _verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED); } /** * @notice Redeem a NFT loan which state is in Auction * - E.g. User repays 100 USDC, burning loan and receives collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param amount The amount to repay the debt and bid fine **/ function redeem( address nftAsset, uint256 nftTokenId, uint256 amount ) external override whenNotPaused returns (uint256) { address poolLiquidator = _addressesProvider.getLendPoolLiquidator(); //solium-disable-next-line (bool success, bytes memory result) = poolLiquidator.delegatecall( abi.encodeWithSignature("redeem(address,uint256,uint256)", nftAsset, nftTokenId, amount) ); bytes memory resultData = _verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED); uint256 repayAmount = abi.decode(resultData, (uint256)); return (repayAmount); } /** * @dev Function to liquidate a non-healthy position collateral-wise * - The caller (liquidator) buy collateral asset of the user getting liquidated, and receives * the collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral **/ function liquidate( address nftAsset, uint256 nftTokenId, uint256 amount ) external override whenNotPaused returns (uint256) { address poolLiquidator = _addressesProvider.getLendPoolLiquidator(); //solium-disable-next-line (bool success, bytes memory result) = poolLiquidator.delegatecall( abi.encodeWithSignature("liquidate(address,uint256,uint256)", nftAsset, nftTokenId, amount) ); bytes memory resultData = _verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED); uint256 extraAmount = abi.decode(resultData, (uint256)); return (extraAmount); } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure override returns (bytes4) { operator; from; tokenId; data; return IERC721ReceiverUpgradeable.onERC721Received.selector; } /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getReserveConfiguration(address asset) external view override returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } /** * @dev Returns the configuration of the NFT * @param asset The address of the asset of the NFT * @return The configuration of the NFT **/ function getNftConfiguration(address asset) external view override returns (DataTypes.NftConfigurationMap memory) { return _nfts[asset].configuration; } /** * @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 override returns (uint256) { return _reserves[asset].getNormalizedIncome(); } /** * @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 override returns (uint256) { return _reserves[asset].getNormalizedDebt(); } /** * @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 override returns (DataTypes.ReserveData memory) { return _reserves[asset]; } /** * @dev Returns the state and configuration of the nft * @param asset The address of the underlying asset of the nft * @return The state of the nft **/ function getNftData(address asset) external view override returns (DataTypes.NftData memory) { return _nfts[asset]; } /** * @dev Returns the loan data of the NFT * @param nftAsset The address of the NFT * @param reserveAsset The address of the Reserve * @return totalCollateralInETH the total collateral in ETH of the NFT * @return totalCollateralInReserve the total collateral in Reserve of the NFT * @return availableBorrowsInETH the borrowing power in ETH of the NFT * @return availableBorrowsInReserve the borrowing power in Reserve of the NFT * @return ltv the loan to value of the user * @return liquidationThreshold the liquidation threshold of the NFT * @return liquidationBonus the liquidation bonus of the NFT **/ function getNftCollateralData(address nftAsset, address reserveAsset) external view override returns ( uint256 totalCollateralInETH, uint256 totalCollateralInReserve, uint256 availableBorrowsInETH, uint256 availableBorrowsInReserve, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ) { DataTypes.NftData storage nftData = _nfts[nftAsset]; DataTypes.ReserveData storage reserveData = _reserves[reserveAsset]; (ltv, liquidationThreshold, liquidationBonus) = nftData.configuration.getCollateralParams(); (totalCollateralInETH, totalCollateralInReserve) = GenericLogic.calculateNftCollateralData( reserveAsset, reserveData, nftAsset, nftData, _addressesProvider.getReserveOracle(), _addressesProvider.getNFTOracle() ); availableBorrowsInETH = GenericLogic.calculateAvailableBorrows(totalCollateralInETH, 0, ltv); availableBorrowsInReserve = GenericLogic.calculateAvailableBorrows(totalCollateralInReserve, 0, ltv); } /** * @dev Returns the debt data of the NFT * @param nftAsset The address of the NFT * @param nftTokenId The token id of the NFT * @return loanId the loan id of the NFT * @return reserveAsset the address of the Reserve * @return totalCollateral the total power of the NFT * @return totalDebt the total debt of the NFT * @return availableBorrows the borrowing power left of the NFT * @return healthFactor the current health factor of the NFT **/ function getNftDebtData(address nftAsset, uint256 nftTokenId) external view override returns ( uint256 loanId, address reserveAsset, uint256 totalCollateral, uint256 totalDebt, uint256 availableBorrows, uint256 healthFactor ) { DataTypes.NftData storage nftData = _nfts[nftAsset]; (uint256 ltv, uint256 liquidationThreshold, ) = nftData.configuration.getCollateralParams(); loanId = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getCollateralLoanId(nftAsset, nftTokenId); if (loanId == 0) { return (0, address(0), 0, 0, 0, 0); } DataTypes.LoanData memory loan = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getLoan(loanId); reserveAsset = loan.reserveAsset; DataTypes.ReserveData storage reserveData = _reserves[reserveAsset]; (, totalCollateral) = GenericLogic.calculateNftCollateralData( reserveAsset, reserveData, nftAsset, nftData, _addressesProvider.getReserveOracle(), _addressesProvider.getNFTOracle() ); (, totalDebt) = GenericLogic.calculateNftDebtData( reserveAsset, reserveData, _addressesProvider.getLendPoolLoan(), loanId, _addressesProvider.getReserveOracle() ); availableBorrows = GenericLogic.calculateAvailableBorrows(totalCollateral, totalDebt, ltv); if (loan.state == DataTypes.LoanState.Active) { healthFactor = GenericLogic.calculateHealthFactorFromBalances(totalCollateral, totalDebt, liquidationThreshold); } } /** * @dev Returns the auction data of the NFT * @param nftAsset The address of the NFT * @param nftTokenId The token id of the NFT * @return loanId the loan id of the NFT * @return bidderAddress the highest bidder address of the loan * @return bidPrice the highest bid price in Reserve of the loan * @return bidBorrowAmount the borrow amount in Reserve of the loan * @return bidFine the penalty fine of the loan **/ function getNftAuctionData(address nftAsset, uint256 nftTokenId) external view override returns ( uint256 loanId, address bidderAddress, uint256 bidPrice, uint256 bidBorrowAmount, uint256 bidFine ) { DataTypes.NftData storage nftData = _nfts[nftAsset]; loanId = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getCollateralLoanId(nftAsset, nftTokenId); if (loanId != 0) { DataTypes.LoanData memory loan = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getLoan(loanId); bidderAddress = loan.bidderAddress; bidPrice = loan.bidPrice; bidBorrowAmount = loan.bidBorrowAmount; bidFine = loan.bidPrice.percentMul(nftData.configuration.getRedeemFine()); } } struct GetLiquidationPriceLocalVars { address poolLoan; uint256 loanId; uint256 thresholdPrice; uint256 liquidatePrice; uint256 paybackAmount; uint256 remainAmount; } function getNftLiquidatePrice(address nftAsset, uint256 nftTokenId) external view override returns (uint256 liquidatePrice, uint256 paybackAmount) { GetLiquidationPriceLocalVars memory vars; vars.poolLoan = _addressesProvider.getLendPoolLoan(); vars.loanId = ILendPoolLoan(vars.poolLoan).getCollateralLoanId(nftAsset, nftTokenId); if (vars.loanId == 0) { return (0, 0); } DataTypes.LoanData memory loanData = ILendPoolLoan(vars.poolLoan).getLoan(vars.loanId); DataTypes.ReserveData storage reserveData = _reserves[loanData.reserveAsset]; DataTypes.NftData storage nftData = _nfts[nftAsset]; (vars.paybackAmount, vars.thresholdPrice, vars.liquidatePrice) = GenericLogic.calculateLoanLiquidatePrice( vars.loanId, loanData.reserveAsset, reserveData, loanData.nftAsset, nftData, vars.poolLoan, _addressesProvider.getReserveOracle(), _addressesProvider.getNFTOracle() ); if (vars.liquidatePrice < vars.paybackAmount) { vars.liquidatePrice = vars.paybackAmount; } return (vars.liquidatePrice, vars.paybackAmount); } /** * @dev Validates and finalizes an bToken transfer * - Only callable by the overlying bToken of the `asset` * @param asset The address of the underlying asset of the bToken * @param from The user from which the bToken are transferred * @param to The user receiving the bTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The bToken balance of the `from` user before the transfer * @param balanceToBefore The bToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external view override whenNotPaused { asset; from; to; amount; balanceFromBefore; balanceToBefore; DataTypes.ReserveData storage reserve = _reserves[asset]; require(_msgSender() == reserve.bTokenAddress, Errors.LP_CALLER_MUST_BE_AN_BTOKEN); ValidationLogic.validateTransfer(from, reserve); } /** * @dev Returns the list of the initialized reserves **/ function getReservesList() external view override returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } /** * @dev Returns the list of the initialized nfts **/ function getNftsList() external view override returns (address[] memory) { address[] memory _activeNfts = new address[](_nftsCount); for (uint256 i = 0; i < _nftsCount; i++) { _activeNfts[i] = _nftsList[i]; } return _activeNfts; } /** * @dev Set the _pause state of the pool * - Only callable by the LendPoolConfigurator contract * @param val `true` to pause the pool, `false` to un-pause it */ function setPause(bool val) external override onlyLendPoolConfigurator { _paused = val; if (_paused) { emit Paused(); } else { emit Unpaused(); } } /** * @dev Returns if the LendPool is paused */ function paused() external view override returns (bool) { return _paused; } /** * @dev Returns the cached LendPoolAddressesProvider connected to this contract **/ function getAddressesProvider() external view override returns (ILendPoolAddressesProvider) { return _addressesProvider; } function setMaxNumberOfReserves(uint256 val) external override onlyLendPoolConfigurator { _maxNumberOfReserves = val; } /** * @dev Returns the maximum number of reserves supported to be listed in this LendPool */ function getMaxNumberOfReserves() public view override returns (uint256) { return _maxNumberOfReserves; } function setMaxNumberOfNfts(uint256 val) external override onlyLendPoolConfigurator { _maxNumberOfNfts = val; } /** * @dev Returns the maximum number of nfts supported to be listed in this LendPool */ function getMaxNumberOfNfts() public view override returns (uint256) { return _maxNumberOfNfts; } /** * @dev Initializes a reserve, activating it, assigning an bToken and nft loan and an * interest rate strategy * - Only callable by the LendPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param bTokenAddress The address of the bToken that will be assigned to the reserve * @param debtTokenAddress The address of the debtToken that will be assigned to the reserve * @param interestRateAddress The address of the interest rate strategy contract **/ function initReserve( address asset, address bTokenAddress, address debtTokenAddress, address interestRateAddress ) external override onlyLendPoolConfigurator { require(AddressUpgradeable.isContract(asset), Errors.LP_NOT_CONTRACT); _reserves[asset].init(bTokenAddress, debtTokenAddress, interestRateAddress); _addReserveToList(asset); } /** * @dev Initializes a nft, activating it, assigning nft loan and an * interest rate strategy * - Only callable by the LendPoolConfigurator contract * @param asset The address of the underlying asset of the nft **/ function initNft(address asset, address bNftAddress) external override onlyLendPoolConfigurator { require(AddressUpgradeable.isContract(asset), Errors.LP_NOT_CONTRACT); _nfts[asset].init(bNftAddress); _addNftToList(asset); require(_addressesProvider.getLendPoolLoan() != address(0), Errors.LPC_INVALIED_LOAN_ADDRESS); IERC721Upgradeable(asset).setApprovalForAll(_addressesProvider.getLendPoolLoan(), true); ILendPoolLoan(_addressesProvider.getLendPoolLoan()).initNft(asset, bNftAddress); } /** * @dev Updates the address of the interest rate strategy contract * - Only callable by the LendPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param rateAddress The address of the interest rate strategy contract **/ function setReserveInterestRateAddress(address asset, address rateAddress) external override onlyLendPoolConfigurator { _reserves[asset].interestRateAddress = rateAddress; } /** * @dev Sets the configuration bitmap of the reserve as a whole * - Only callable by the LendPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param configuration The new configuration bitmap **/ function setReserveConfiguration(address asset, uint256 configuration) external override onlyLendPoolConfigurator { _reserves[asset].configuration.data = configuration; } /** * @dev Sets the configuration bitmap of the NFT as a whole * - Only callable by the LendPoolConfigurator contract * @param asset The address of the asset of the NFT * @param configuration The new configuration bitmap **/ function setNftConfiguration(address asset, uint256 configuration) external override onlyLendPoolConfigurator { _nfts[asset].configuration.data = configuration; } function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED); bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; if (!reserveAlreadyAdded) { _reserves[asset].id = uint8(reservesCount); _reservesList[reservesCount] = asset; _reservesCount = reservesCount + 1; } } function _addNftToList(address asset) internal { uint256 nftsCount = _nftsCount; require(nftsCount < _maxNumberOfNfts, Errors.LP_NO_MORE_NFTS_ALLOWED); bool nftAlreadyAdded = _nfts[asset].id != 0 || _nftsList[0] == asset; if (!nftAlreadyAdded) { _nfts[asset].id = uint8(nftsCount); _nftsList[nftsCount] = asset; _nftsCount = nftsCount + 1; } } 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: agpl-3.0 pragma solidity 0.8.4; import {ILendPoolAddressesProvider} from "./ILendPoolAddressesProvider.sol"; import {IIncentivesController} from "./IIncentivesController.sol"; import {IScaledBalanceToken} from "./IScaledBalanceToken.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; interface IBToken is IScaledBalanceToken, IERC20Upgradeable, IERC20MetadataUpgradeable { /** * @dev Emitted when an bToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this bToken **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController ); /** * @dev Initializes the bToken * @param addressProvider The address of the address provider where this bToken will be used * @param treasury The address of the Bend treasury, receiving the fees on this bToken * @param underlyingAsset The address of the underlying asset of this bToken */ function initialize( ILendPoolAddressesProvider addressProvider, address treasury, address underlyingAsset, uint8 bTokenDecimals, string calldata bTokenName, string calldata bTokenSymbol ) external; /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` bTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after bTokens are burned * @param from The owner of the bTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns bTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the bTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints bTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IIncentivesController); /** * @dev Returns the address of the underlying asset of this bToken **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol"; import {IIncentivesController} from "./IIncentivesController.sol"; import {IScaledBalanceToken} from "./IScaledBalanceToken.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; /** * @title IDebtToken * @author Bend * @notice Defines the basic interface for a debt token. **/ interface IDebtToken is IScaledBalanceToken, IERC20Upgradeable, IERC20MetadataUpgradeable { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lend pool * @param incentivesController The address of the incentives controller * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol ); /** * @dev Initializes the debt token. * @param addressProvider The address of the lend pool * @param underlyingAsset The address of the underlying asset * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendPoolAddressesProvider addressProvider, address underlyingAsset, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol ) external; /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints debt token to the `user` address * @param user The address receiving the borrowed underlying * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IIncentivesController); /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external; /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {DataTypes} from "../libraries/types/DataTypes.sol"; interface ILendPoolLoan { /** * @dev Emitted on initialization to share location of dependent notes * @param pool The address of the associated lend pool */ event Initialized(address indexed pool); /** * @dev Emitted when a loan is created * @param user The address initiating the action */ event LoanCreated( address indexed user, address indexed onBehalfOf, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 amount, uint256 borrowIndex ); /** * @dev Emitted when a loan is updated * @param user The address initiating the action */ event LoanUpdated( address indexed user, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 amountAdded, uint256 amountTaken, uint256 borrowIndex ); /** * @dev Emitted when a loan is repaid by the borrower * @param user The address initiating the action */ event LoanRepaid( address indexed user, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 amount, uint256 borrowIndex ); /** * @dev Emitted when a loan is auction by the liquidator * @param user The address initiating the action */ event LoanAuctioned( address indexed user, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, uint256 amount, uint256 borrowIndex, address bidder, uint256 price, address previousBidder, uint256 previousPrice ); /** * @dev Emitted when a loan is redeemed * @param user The address initiating the action */ event LoanRedeemed( address indexed user, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 amountTaken, uint256 borrowIndex ); /** * @dev Emitted when a loan is liquidate by the liquidator * @param user The address initiating the action */ event LoanLiquidated( address indexed user, uint256 indexed loanId, address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 amount, uint256 borrowIndex ); function initNft(address nftAsset, address bNftAddress) external; /** * @dev Create store a loan object with some params * @param initiator The address of the user initiating the borrow * @param onBehalfOf The address receiving the loan */ function createLoan( address initiator, address onBehalfOf, address nftAsset, uint256 nftTokenId, address bNftAddress, address reserveAsset, uint256 amount, uint256 borrowIndex ) external returns (uint256); /** * @dev Update the given loan with some params * * Requirements: * - The caller must be a holder of the loan * - The loan must be in state Active * @param initiator The address of the user initiating the borrow */ function updateLoan( address initiator, uint256 loanId, uint256 amountAdded, uint256 amountTaken, uint256 borrowIndex ) external; /** * @dev Repay the given loan * * Requirements: * - The caller must be a holder of the loan * - The caller must send in principal + interest * - The loan must be in state Active * * @param initiator The address of the user initiating the repay * @param loanId The loan getting burned * @param bNftAddress The address of bNFT */ function repayLoan( address initiator, uint256 loanId, address bNftAddress, uint256 amount, uint256 borrowIndex ) external; /** * @dev Auction the given loan * * Requirements: * - The price must be greater than current highest price * - The loan must be in state Active or Auction * * @param initiator The address of the user initiating the auction * @param loanId The loan getting auctioned * @param bidPrice The bid price of this auction */ function auctionLoan( address initiator, uint256 loanId, address onBehalfOf, uint256 bidPrice, uint256 borrowAmount, uint256 borrowIndex ) external; /** * @dev Redeem the given loan with some params * * Requirements: * - The caller must be a holder of the loan * - The loan must be in state Auction * @param initiator The address of the user initiating the borrow */ function redeemLoan( address initiator, uint256 loanId, uint256 amountTaken, uint256 borrowIndex ) external; /** * @dev Liquidate the given loan * * Requirements: * - The caller must send in principal + interest * - The loan must be in state Active * * @param initiator The address of the user initiating the auction * @param loanId The loan getting burned * @param bNftAddress The address of bNFT */ function liquidateLoan( address initiator, uint256 loanId, address bNftAddress, uint256 borrowAmount, uint256 borrowIndex ) external; function borrowerOf(uint256 loanId) external view returns (address); function getCollateralLoanId(address nftAsset, uint256 nftTokenId) external view returns (uint256); function getLoan(uint256 loanId) external view returns (DataTypes.LoanData memory loanData); function getLoanCollateralAndReserve(uint256 loanId) external view returns ( address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 scaledAmount ); function getLoanReserveBorrowScaledAmount(uint256 loanId) external view returns (address, uint256); function getLoanReserveBorrowAmount(uint256 loanId) external view returns (address, uint256); function getLoanHighestBid(uint256 loanId) external view returns (address, uint256); function getNftCollateralAmount(address nftAsset) external view returns (uint256); function getUserNftCollateralAmount(address user, address nftAsset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {ILendPoolAddressesProvider} from "./ILendPoolAddressesProvider.sol"; import {DataTypes} from "../libraries/types/DataTypes.sol"; interface ILendPool { /** * @dev Emitted on deposit() * @param user The address initiating the deposit * @param amount The amount deposited * @param reserve The address of the underlying asset of the reserve * @param onBehalfOf The beneficiary of the deposit, receiving the bTokens * @param referral The referral code used **/ event Deposit( address user, address indexed reserve, uint256 amount, address indexed onBehalfOf, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param user The address initiating the withdrawal, owner of bTokens * @param reserve The address of the underlyng asset being withdrawn * @param amount The amount to be withdrawn * @param to Address that will receive the underlying **/ event Withdraw(address indexed user, address indexed reserve, uint256 amount, address indexed to); /** * @dev Emitted on borrow() when loan needs to be opened * @param user The address of the user initiating the borrow(), receiving the funds * @param reserve The address of the underlying asset being borrowed * @param amount The amount borrowed out * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param onBehalfOf The address that will be getting the loan * @param referral The referral code used **/ event Borrow( address user, address indexed reserve, uint256 amount, address nftAsset, uint256 nftTokenId, address indexed onBehalfOf, uint256 borrowRate, uint256 loanId, uint16 indexed referral ); /** * @dev Emitted on repay() * @param user The address of the user initiating the repay(), providing the funds * @param reserve The address of the underlying asset of the reserve * @param amount The amount repaid * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param borrower The beneficiary of the repayment, getting his debt reduced * @param loanId The loan ID of the NFT loans **/ event Repay( address user, address indexed reserve, uint256 amount, address indexed nftAsset, uint256 nftTokenId, address indexed borrower, uint256 loanId ); /** * @dev Emitted when a borrower's loan is auctioned. * @param user The address of the user initiating the auction * @param reserve The address of the underlying asset of the reserve * @param bidPrice The price of the underlying reserve given by the bidder * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param onBehalfOf The address that will be getting the NFT * @param loanId The loan ID of the NFT loans **/ event Auction( address user, address indexed reserve, uint256 bidPrice, address indexed nftAsset, uint256 nftTokenId, address onBehalfOf, address indexed borrower, uint256 loanId ); /** * @dev Emitted on redeem() * @param user The address of the user initiating the redeem(), providing the funds * @param reserve The address of the underlying asset of the reserve * @param borrowAmount The borrow amount repaid * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token id of the underlying NFT used as collateral * @param loanId The loan ID of the NFT loans **/ event Redeem( address user, address indexed reserve, uint256 borrowAmount, uint256 fineAmount, address indexed nftAsset, uint256 nftTokenId, address indexed borrower, uint256 loanId ); /** * @dev Emitted when a borrower's loan is liquidated. * @param user The address of the user initiating the auction * @param reserve The address of the underlying asset of the reserve * @param repayAmount The amount of reserve repaid by the liquidator * @param remainAmount The amount of reserve received by the borrower * @param loanId The loan ID of the NFT loans **/ event Liquidate( address user, address indexed reserve, uint256 repayAmount, uint256 remainAmount, address indexed nftAsset, uint256 nftTokenId, address indexed borrower, uint256 loanId ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @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 LendPool contract. The event is therefore replicated here so it * gets added to the LendPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity 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 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying bTokens. * - E.g. User deposits 100 USDC and gets in return 100 bUSDC * @param reserve The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the bTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of bTokens * 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 reserve, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent bTokens owned * E.g. User has 100 bUSDC, calls withdraw() and receives 100 USDC, burning the 100 bUSDC * @param reserve 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 bToken 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 reserve, 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 * - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet * and lock collateral asset in contract * @param reserveAsset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param onBehalfOf Address of the user who will receive the loan. 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 * @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 borrow( address reserveAsset, uint256 amount, address nftAsset, uint256 nftTokenId, address onBehalfOf, uint16 referralCode ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent loan owned * - E.g. User repays 100 USDC, burning loan and receives collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param amount The amount to repay * @return The final amount repaid, loan is burned or not **/ function repay( address nftAsset, uint256 nftTokenId, uint256 amount ) external returns (uint256, bool); /** * @dev Function to auction a non-healthy position collateral-wise * - The caller (liquidator) want to buy collateral asset of the user getting liquidated * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param bidPrice The bid price of the liquidator want to buy the underlying NFT * @param onBehalfOf Address of the user who will get the underlying NFT, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of NFT * is a different wallet **/ function auction( address nftAsset, uint256 nftTokenId, uint256 bidPrice, address onBehalfOf ) external; /** * @notice Redeem a NFT loan which state is in Auction * - E.g. User repays 100 USDC, burning loan and receives collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral * @param amount The amount to repay the debt and bid fine **/ function redeem( address nftAsset, uint256 nftTokenId, uint256 amount ) external returns (uint256); /** * @dev Function to liquidate a non-healthy position collateral-wise * - The caller (liquidator) buy collateral asset of the user getting liquidated, and receives * the collateral asset * @param nftAsset The address of the underlying NFT used as collateral * @param nftTokenId The token ID of the underlying NFT used as collateral **/ function liquidate( address nftAsset, uint256 nftTokenId, uint256 amount ) external returns (uint256); /** * @dev Validates and finalizes an bToken transfer * - Only callable by the overlying bToken of the `asset` * @param asset The address of the underlying asset of the bToken * @param from The user from which the bTokens are transferred * @param to The user receiving the bTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The bToken balance of the `from` user before the transfer * @param balanceToBefore The bToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external view; function getReserveConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); function getNftConfiguration(address asset) external view returns (DataTypes.NftConfigurationMap 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 getReservesList() external view returns (address[] memory); function getNftData(address asset) external view returns (DataTypes.NftData memory); /** * @dev Returns the loan data of the NFT * @param nftAsset The address of the NFT * @param reserveAsset The address of the Reserve * @return totalCollateralInETH the total collateral in ETH of the NFT * @return totalCollateralInReserve the total collateral in Reserve of the NFT * @return availableBorrowsInETH the borrowing power in ETH of the NFT * @return availableBorrowsInReserve the borrowing power in Reserve of the NFT * @return ltv the loan to value of the user * @return liquidationThreshold the liquidation threshold of the NFT * @return liquidationBonus the liquidation bonus of the NFT **/ function getNftCollateralData(address nftAsset, address reserveAsset) external view returns ( uint256 totalCollateralInETH, uint256 totalCollateralInReserve, uint256 availableBorrowsInETH, uint256 availableBorrowsInReserve, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Returns the debt data of the NFT * @param nftAsset The address of the NFT * @param nftTokenId The token id of the NFT * @return loanId the loan id of the NFT * @return reserveAsset the address of the Reserve * @return totalCollateral the total power of the NFT * @return totalDebt the total debt of the NFT * @return availableBorrows the borrowing power left of the NFT * @return healthFactor the current health factor of the NFT **/ function getNftDebtData(address nftAsset, uint256 nftTokenId) external view returns ( uint256 loanId, address reserveAsset, uint256 totalCollateral, uint256 totalDebt, uint256 availableBorrows, uint256 healthFactor ); /** * @dev Returns the auction data of the NFT * @param nftAsset The address of the NFT * @param nftTokenId The token id of the NFT * @return loanId the loan id of the NFT * @return bidderAddress the highest bidder address of the loan * @return bidPrice the highest bid price in Reserve of the loan * @return bidBorrowAmount the borrow amount in Reserve of the loan * @return bidFine the penalty fine of the loan **/ function getNftAuctionData(address nftAsset, uint256 nftTokenId) external view returns ( uint256 loanId, address bidderAddress, uint256 bidPrice, uint256 bidBorrowAmount, uint256 bidFine ); function getNftLiquidatePrice(address nftAsset, uint256 nftTokenId) external view returns (uint256 liquidatePrice, uint256 paybackAmount); function getNftsList() external view returns (address[] memory); /** * @dev Set the _pause state of a reserve * - Only callable by the LendPool contract * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external; /** * @dev Returns if the LendPool is paused */ function paused() external view returns (bool); function getAddressesProvider() external view returns (ILendPoolAddressesProvider); function initReserve( address asset, address bTokenAddress, address debtTokenAddress, address interestRateAddress ) external; function initNft(address asset, address bNftAddress) external; function setReserveInterestRateAddress(address asset, address rateAddress) external; function setReserveConfiguration(address asset, uint256 configuration) external; function setNftConfiguration(address asset, uint256 configuration) external; function setMaxNumberOfReserves(uint256 val) external; function setMaxNumberOfNfts(uint256 val) external; function getMaxNumberOfReserves() external view returns (uint256); function getMaxNumberOfNfts() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /************ @title IReserveOracleGetter interface @notice Interface for getting Reserve price oracle.*/ interface IReserveOracleGetter { /* CAUTION: Price uint is ETH based (WEI, 18 decimals) */ /*********** @dev returns the asset price in ETH */ function getAssetPrice(address asset) external view returns (uint256); // get twap price depending on _period function getTwapPrice(address _priceFeedKey, uint256 _interval) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /************ @title INFTOracleGetter interface @notice Interface for getting NFT price oracle.*/ interface INFTOracleGetter { /* CAUTION: Price uint is ETH based (WEI, 18 decimals) */ /*********** @dev returns the asset price in ETH */ function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title LendPoolAddressesProvider 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 Bend Governance * @author Bend **/ interface ILendPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendPoolUpdated(address indexed newAddress, bytes encodedCallData); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendPoolConfiguratorUpdated(address indexed newAddress, bytes encodedCallData); event ReserveOracleUpdated(address indexed newAddress); event NftOracleUpdated(address indexed newAddress); event LendPoolLoanUpdated(address indexed newAddress, bytes encodedCallData); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy, bytes encodedCallData); event BNFTRegistryUpdated(address indexed newAddress); event LendPoolLiquidatorUpdated(address indexed newAddress); event IncentivesControllerUpdated(address indexed newAddress); event UIDataProviderUpdated(address indexed newAddress); event BendDataProviderUpdated(address indexed newAddress); event WalletBalanceProviderUpdated(address indexed newAddress); 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, bytes memory encodedCallData ) external; function getAddress(bytes32 id) external view returns (address); function getLendPool() external view returns (address); function setLendPoolImpl(address pool, bytes memory encodedCallData) external; function getLendPoolConfigurator() external view returns (address); function setLendPoolConfiguratorImpl(address configurator, bytes memory encodedCallData) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getReserveOracle() external view returns (address); function setReserveOracle(address reserveOracle) external; function getNFTOracle() external view returns (address); function setNFTOracle(address nftOracle) external; function getLendPoolLoan() external view returns (address); function setLendPoolLoanImpl(address loan, bytes memory encodedCallData) external; function getBNFTRegistry() external view returns (address); function setBNFTRegistry(address factory) external; function getLendPoolLiquidator() external view returns (address); function setLendPoolLiquidator(address liquidator) external; function getIncentivesController() external view returns (address); function setIncentivesController(address controller) external; function getUIDataProvider() external view returns (address); function setUIDataProvider(address provider) external; function getBendDataProvider() external view returns (address); function setBendDataProvider(address provider) external; function getWalletBalanceProvider() external view returns (address); function setWalletBalanceProvider(address provider) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title Errors library * @author Bend * @notice Defines the error messages emitted by the different contracts of the Bend protocol */ library Errors { enum ReturnCode { SUCCESS, FAILED } string public constant SUCCESS = "0"; //common errors string public constant CALLER_NOT_POOL_ADMIN = "100"; // 'The caller must be the pool admin' string public constant CALLER_NOT_ADDRESS_PROVIDER = "101"; string public constant INVALID_FROM_BALANCE_AFTER_TRANSFER = "102"; string public constant INVALID_TO_BALANCE_AFTER_TRANSFER = "103"; //math library erros string public constant MATH_MULTIPLICATION_OVERFLOW = "200"; string public constant MATH_ADDITION_OVERFLOW = "201"; string public constant MATH_DIVISION_BY_ZERO = "202"; //validation & check errors string public constant VL_INVALID_AMOUNT = "301"; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = "302"; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = "303"; // 'Action cannot be performed because the reserve is frozen' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = "304"; // 'User cannot withdraw more than the available balance' string public constant VL_BORROWING_NOT_ENABLED = "305"; // 'Borrowing is not enabled' string public constant VL_COLLATERAL_BALANCE_IS_0 = "306"; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = "307"; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = "308"; // 'There is not enough collateral to cover a new borrow' string public constant VL_NO_DEBT_OF_SELECTED_TYPE = "309"; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_ACTIVE_NFT = "310"; string public constant VL_NFT_FROZEN = "311"; string public constant VL_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = "312"; // 'User did not borrow the specified currency' string public constant VL_INVALID_HEALTH_FACTOR = "313"; string public constant VL_INVALID_ONBEHALFOF_ADDRESS = "314"; string public constant VL_INVALID_TARGET_ADDRESS = "315"; string public constant VL_INVALID_RESERVE_ADDRESS = "316"; string public constant VL_SPECIFIED_LOAN_NOT_BORROWED_BY_USER = "317"; string public constant VL_SPECIFIED_RESERVE_NOT_BORROWED_BY_USER = "318"; string public constant VL_HEALTH_FACTOR_HIGHER_THAN_LIQUIDATION_THRESHOLD = "319"; //lend pool errors string public constant LP_CALLER_NOT_LEND_POOL_CONFIGURATOR = "400"; // 'The caller of the function is not the lending pool configurator' string public constant LP_IS_PAUSED = "401"; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = "402"; string public constant LP_NOT_CONTRACT = "403"; string public constant LP_BORROW_NOT_EXCEED_LIQUIDATION_THRESHOLD = "404"; string public constant LP_BORROW_IS_EXCEED_LIQUIDATION_PRICE = "405"; string public constant LP_NO_MORE_NFTS_ALLOWED = "406"; string public constant LP_INVALIED_USER_NFT_AMOUNT = "407"; string public constant LP_INCONSISTENT_PARAMS = "408"; string public constant LP_NFT_IS_NOT_USED_AS_COLLATERAL = "409"; string public constant LP_CALLER_MUST_BE_AN_BTOKEN = "410"; string public constant LP_INVALIED_NFT_AMOUNT = "411"; string public constant LP_NFT_HAS_USED_AS_COLLATERAL = "412"; string public constant LP_DELEGATE_CALL_FAILED = "413"; string public constant LP_AMOUNT_LESS_THAN_EXTRA_DEBT = "414"; string public constant LP_AMOUNT_LESS_THAN_REDEEM_THRESHOLD = "415"; //lend pool loan errors string public constant LPL_INVALID_LOAN_STATE = "480"; string public constant LPL_INVALID_LOAN_AMOUNT = "481"; string public constant LPL_INVALID_TAKEN_AMOUNT = "482"; string public constant LPL_AMOUNT_OVERFLOW = "483"; string public constant LPL_BID_PRICE_LESS_THAN_LIQUIDATION_PRICE = "484"; string public constant LPL_BID_PRICE_LESS_THAN_HIGHEST_PRICE = "485"; string public constant LPL_BID_REDEEM_DURATION_HAS_END = "486"; string public constant LPL_BID_USER_NOT_SAME = "487"; string public constant LPL_BID_REPAY_AMOUNT_NOT_ENOUGH = "488"; string public constant LPL_BID_AUCTION_DURATION_HAS_END = "489"; string public constant LPL_BID_AUCTION_DURATION_NOT_END = "490"; string public constant LPL_BID_PRICE_LESS_THAN_BORROW = "491"; string public constant LPL_INVALID_BIDDER_ADDRESS = "492"; string public constant LPL_AMOUNT_LESS_THAN_BID_FINE = "493"; //common token errors string public constant CT_CALLER_MUST_BE_LEND_POOL = "500"; // 'The caller of this function must be a lending pool' string public constant CT_INVALID_MINT_AMOUNT = "501"; //invalid amount to mint string public constant CT_INVALID_BURN_AMOUNT = "502"; //invalid amount to burn string public constant CT_BORROW_ALLOWANCE_NOT_ENOUGH = "503"; //reserve logic errors string public constant RL_RESERVE_ALREADY_INITIALIZED = "601"; // 'Reserve has already been initialized' string public constant RL_LIQUIDITY_INDEX_OVERFLOW = "602"; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = "603"; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = "604"; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = "605"; // Variable borrow rate overflows uint128 //configure errors string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = "700"; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = "701"; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = "702"; // 'The caller must be the emergency admin' string public constant LPC_INVALIED_BNFT_ADDRESS = "703"; string public constant LPC_INVALIED_LOAN_ADDRESS = "704"; string public constant LPC_NFT_LIQUIDITY_NOT_0 = "705"; //reserve config errors string public constant RC_INVALID_LTV = "730"; string public constant RC_INVALID_LIQ_THRESHOLD = "731"; string public constant RC_INVALID_LIQ_BONUS = "732"; string public constant RC_INVALID_DECIMALS = "733"; string public constant RC_INVALID_RESERVE_FACTOR = "734"; string public constant RC_INVALID_REDEEM_DURATION = "735"; string public constant RC_INVALID_AUCTION_DURATION = "736"; string public constant RC_INVALID_REDEEM_FINE = "737"; string public constant RC_INVALID_REDEEM_THRESHOLD = "738"; //address provider erros string public constant LPAPR_PROVIDER_NOT_REGISTERED = "760"; // 'Provider is not registered' string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = "761"; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {Errors} from "../helpers/Errors.sol"; /** * @title WadRayMath library * @author Bend * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant HALF_WAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant HALF_RAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return HALF_RAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return HALF_WAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + HALF_WAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + HALF_RAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {ILendPoolLoan} from "../../interfaces/ILendPoolLoan.sol"; import {IReserveOracleGetter} from "../../interfaces/IReserveOracleGetter.sol"; import {INFTOracleGetter} from "../../interfaces/INFTOracleGetter.sol"; import {WadRayMath} from "../math/WadRayMath.sol"; import {PercentageMath} from "../math/PercentageMath.sol"; import {ReserveConfiguration} from "../configuration/ReserveConfiguration.sol"; import {NftConfiguration} from "../configuration/NftConfiguration.sol"; import {Errors} from "../helpers/Errors.sol"; import {DataTypes} from "../types/DataTypes.sol"; import {ReserveLogic} from "./ReserveLogic.sol"; /** * @title GenericLogic library * @author Bend * @notice Implements protocol-level logic to calculate and validate the state of a user */ library GenericLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using NftConfiguration for DataTypes.NftConfigurationMap; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether; struct CalculateLoanDataVars { uint256 reserveUnitPrice; uint256 reserveUnit; uint256 reserveDecimals; uint256 healthFactor; uint256 totalCollateralInETH; uint256 totalCollateralInReserve; uint256 totalDebtInETH; uint256 totalDebtInReserve; uint256 nftLtv; uint256 nftLiquidationThreshold; address nftAsset; uint256 nftTokenId; uint256 nftUnitPrice; } /** * @dev Calculates the nft loan data. * this includes the total collateral/borrow balances in Reserve, * the Loan To Value, the Liquidation Ratio, and the Health factor. * @param reserveData Data of the reserve * @param nftData Data of the nft * @param reserveOracle The price oracle address of reserve * @param nftOracle The price oracle address of nft * @return The total collateral and total debt of the loan in Reserve, the ltv, liquidation threshold and the HF **/ function calculateLoanData( address reserveAddress, DataTypes.ReserveData storage reserveData, address nftAddress, DataTypes.NftData storage nftData, address loanAddress, uint256 loanId, address reserveOracle, address nftOracle ) internal view returns ( uint256, uint256, uint256 ) { CalculateLoanDataVars memory vars; (vars.nftLtv, vars.nftLiquidationThreshold, ) = nftData.configuration.getCollateralParams(); // calculate total borrow balance for the loan if (loanId != 0) { (vars.totalDebtInETH, vars.totalDebtInReserve) = calculateNftDebtData( reserveAddress, reserveData, loanAddress, loanId, reserveOracle ); } // calculate total collateral balance for the nft (vars.totalCollateralInETH, vars.totalCollateralInReserve) = calculateNftCollateralData( reserveAddress, reserveData, nftAddress, nftData, reserveOracle, nftOracle ); // calculate health by borrow and collateral vars.healthFactor = calculateHealthFactorFromBalances( vars.totalCollateralInReserve, vars.totalDebtInReserve, vars.nftLiquidationThreshold ); return (vars.totalCollateralInReserve, vars.totalDebtInReserve, vars.healthFactor); } function calculateNftDebtData( address reserveAddress, DataTypes.ReserveData storage reserveData, address loanAddress, uint256 loanId, address reserveOracle ) internal view returns (uint256, uint256) { CalculateLoanDataVars memory vars; // all asset price has converted to ETH based, unit is in WEI (18 decimals) vars.reserveDecimals = reserveData.configuration.getDecimals(); vars.reserveUnit = 10**vars.reserveDecimals; vars.reserveUnitPrice = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAddress); (, vars.totalDebtInReserve) = ILendPoolLoan(loanAddress).getLoanReserveBorrowAmount(loanId); vars.totalDebtInETH = (vars.totalDebtInReserve * vars.reserveUnitPrice) / vars.reserveUnit; return (vars.totalDebtInETH, vars.totalDebtInReserve); } function calculateNftCollateralData( address reserveAddress, DataTypes.ReserveData storage reserveData, address nftAddress, DataTypes.NftData storage nftData, address reserveOracle, address nftOracle ) internal view returns (uint256, uint256) { reserveData; nftData; CalculateLoanDataVars memory vars; // calculate total collateral balance for the nft // all asset price has converted to ETH based, unit is in WEI (18 decimals) vars.nftUnitPrice = INFTOracleGetter(nftOracle).getAssetPrice(nftAddress); vars.totalCollateralInETH = vars.nftUnitPrice; if (reserveAddress != address(0)) { vars.reserveDecimals = reserveData.configuration.getDecimals(); vars.reserveUnit = 10**vars.reserveDecimals; vars.reserveUnitPrice = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAddress); vars.totalCollateralInReserve = (vars.totalCollateralInETH * vars.reserveUnit) / vars.reserveUnitPrice; } return (vars.totalCollateralInETH, vars.totalCollateralInReserve); } /** * @dev Calculates the health factor from the corresponding balances * @param totalCollateral The total collateral * @param totalDebt The total debt * @param liquidationThreshold The avg liquidation threshold * @return The health factor calculated from the balances provided **/ function calculateHealthFactorFromBalances( uint256 totalCollateral, uint256 totalDebt, uint256 liquidationThreshold ) internal pure returns (uint256) { if (totalDebt == 0) return type(uint256).max; return (totalCollateral.percentMul(liquidationThreshold)).wadDiv(totalDebt); } /** * @dev Calculates the equivalent amount that an user can borrow, depending on the available collateral and the * average Loan To Value * @param totalCollateral The total collateral * @param totalDebt The total borrow balance * @param ltv The average loan to value * @return the amount available to borrow for the user **/ function calculateAvailableBorrows( uint256 totalCollateral, uint256 totalDebt, uint256 ltv ) internal pure returns (uint256) { uint256 availableBorrows = totalCollateral.percentMul(ltv); if (availableBorrows < totalDebt) { return 0; } availableBorrows = availableBorrows - totalDebt; return availableBorrows; } struct CalcLiquidatePriceLocalVars { uint256 ltv; uint256 liquidationThreshold; uint256 liquidationBonus; uint256 nftPriceInETH; uint256 nftPriceInReserve; uint256 reserveDecimals; uint256 reservePriceInETH; uint256 thresholdPrice; uint256 liquidatePrice; uint256 borrowAmount; } function calculateLoanLiquidatePrice( uint256 loanId, address reserveAsset, DataTypes.ReserveData storage reserveData, address nftAsset, DataTypes.NftData storage nftData, address poolLoan, address reserveOracle, address nftOracle ) internal view returns ( uint256, uint256, uint256 ) { CalcLiquidatePriceLocalVars memory vars; /* * 0 CR LH 100 * |___________________|___________________|___________________| * < Borrowing with Interest < * CR: Callteral Ratio; * LH: Liquidate Threshold; * Liquidate Trigger: Borrowing with Interest > thresholdPrice; * Liquidate Price: (100% - BonusRatio) * NFT Price; */ vars.reserveDecimals = reserveData.configuration.getDecimals(); (, vars.borrowAmount) = ILendPoolLoan(poolLoan).getLoanReserveBorrowAmount(loanId); (vars.ltv, vars.liquidationThreshold, vars.liquidationBonus) = nftData.configuration.getCollateralParams(); vars.nftPriceInETH = INFTOracleGetter(nftOracle).getAssetPrice(nftAsset); vars.reservePriceInETH = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAsset); vars.nftPriceInReserve = ((10**vars.reserveDecimals) * vars.nftPriceInETH) / vars.reservePriceInETH; vars.thresholdPrice = vars.nftPriceInReserve.percentMul(vars.liquidationThreshold); vars.liquidatePrice = vars.nftPriceInReserve.percentMul(PercentageMath.PERCENTAGE_FACTOR - vars.liquidationBonus); return (vars.borrowAmount, vars.thresholdPrice, vars.liquidatePrice); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {Errors} from "../helpers/Errors.sol"; /** * @title PercentageMath library * @author Bend * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; uint256 constant ONE_PERCENT = 1e2; //100, 1% uint256 constant TEN_PERCENT = 1e3; //1000, 10% uint256 constant ONE_THOUSANDTH_PERCENT = 1e1; //10, 0.1% uint256 constant ONE_TEN_THOUSANDTH_PERCENT = 1; //1, 0.01% /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require(value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require(value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {IBToken} from "../../interfaces/IBToken.sol"; import {IDebtToken} from "../../interfaces/IDebtToken.sol"; import {IInterestRate} from "../../interfaces/IInterestRate.sol"; import {ReserveConfiguration} from "../configuration/ReserveConfiguration.sol"; import {MathUtils} from "../math/MathUtils.sol"; import {WadRayMath} from "../math/WadRayMath.sol"; import {PercentageMath} from "../math/PercentageMath.sol"; import {Errors} from "../helpers/Errors.sol"; import {DataTypes} from "../types/DataTypes.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; /** * @title ReserveLogic library * @author Bend * @notice Implements the logic to update the reserves state */ library ReserveLogic { using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /** * @dev Emitted when the state of a reserve is updated * @param asset The address of the underlying asset of the reserve * @param liquidityRate The new liquidity 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 asset, uint256 liquidityRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; /** * @dev Returns the ongoing normalized income for the reserve * A value of 1e27 means there is no income. As time passes, the income is accrued * A value of 2*1e27 means for each unit of asset one unit of income has been accrued * @param reserve The reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.liquidityIndex; } uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul( reserve.liquidityIndex ); return cumulated; } /** * @dev Returns the ongoing normalized variable debt for the reserve * A value of 1e27 means there is no debt. As time passes, the income is accrued * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated * @param reserve The reserve object * @return The normalized variable debt. expressed in ray **/ function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.variableBorrowIndex; } uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul( reserve.variableBorrowIndex ); return cumulated; } /** * @dev Updates the liquidity cumulative index and the variable borrow index. * @param reserve the reserve object **/ function updateState(DataTypes.ReserveData storage reserve) internal { uint256 scaledVariableDebt = IDebtToken(reserve.debtTokenAddress).scaledTotalSupply(); uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; uint256 previousLiquidityIndex = reserve.liquidityIndex; uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp; (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( reserve, scaledVariableDebt, previousLiquidityIndex, previousVariableBorrowIndex, lastUpdatedTimestamp ); _mintToTreasury( reserve, scaledVariableDebt, previousVariableBorrowIndex, newLiquidityIndex, newVariableBorrowIndex, lastUpdatedTimestamp ); } /** * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate * the flashloan fee to the reserve, and spread it between all the depositors * @param reserve The reserve object * @param totalLiquidity The total liquidity available in the reserve * @param amount The amount to accomulate **/ function cumulateToLiquidityIndex( DataTypes.ReserveData storage reserve, uint256 totalLiquidity, uint256 amount ) internal { uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay()); uint256 result = amountToLiquidityRatio + (WadRayMath.ray()); result = result.rayMul(reserve.liquidityIndex); require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(result); } /** * @dev Initializes a reserve * @param reserve The reserve object * @param bTokenAddress The address of the overlying bToken contract * @param debtTokenAddress The address of the overlying debtToken contract * @param interestRateAddress The address of the interest rate strategy contract **/ function init( DataTypes.ReserveData storage reserve, address bTokenAddress, address debtTokenAddress, address interestRateAddress ) external { require(reserve.bTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED); reserve.liquidityIndex = uint128(WadRayMath.ray()); reserve.variableBorrowIndex = uint128(WadRayMath.ray()); reserve.bTokenAddress = bTokenAddress; reserve.debtTokenAddress = debtTokenAddress; reserve.interestRateAddress = interestRateAddress; } struct UpdateInterestRatesLocalVars { uint256 availableLiquidity; uint256 newLiquidityRate; uint256 newVariableRate; uint256 totalVariableDebt; } /** * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate * @param reserve The address of the reserve to be updated * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action * @param liquidityTaken The amount of liquidity taken from the protocol (withdraw or borrow) **/ function updateInterestRates( DataTypes.ReserveData storage reserve, address reserveAddress, address bTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { UpdateInterestRatesLocalVars memory vars; //calculates the total variable debt locally using the scaled borrow amount instead //of borrow amount(), as it's noticeably cheaper. Also, the index has been //updated by the previous updateState() call vars.totalVariableDebt = IDebtToken(reserve.debtTokenAddress).scaledTotalSupply().rayMul( reserve.variableBorrowIndex ); (vars.newLiquidityRate, vars.newVariableRate) = IInterestRate(reserve.interestRateAddress).calculateInterestRates( reserveAddress, bTokenAddress, liquidityAdded, liquidityTaken, vars.totalVariableDebt, reserve.configuration.getReserveFactor() ); require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW); require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW); reserve.currentLiquidityRate = uint128(vars.newLiquidityRate); reserve.currentVariableBorrowRate = uint128(vars.newVariableRate); emit ReserveDataUpdated( reserveAddress, vars.newLiquidityRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex ); } struct MintToTreasuryLocalVars { uint256 currentVariableDebt; uint256 previousVariableDebt; uint256 totalDebtAccrued; uint256 amountToMint; uint256 reserveFactor; } /** * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the * specific asset. * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The current scaled total variable debt * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest * @param newLiquidityIndex The new liquidity index * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest **/ function _mintToTreasury( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, uint256 newVariableBorrowIndex, uint40 timestamp ) internal { timestamp; MintToTreasuryLocalVars memory vars; vars.reserveFactor = reserve.configuration.getReserveFactor(); if (vars.reserveFactor == 0) { return; } //calculate the last principal variable debt vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex); //calculate the new total supply after accumulation of the index vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex); //debt accrued is the sum of the current debt minus the sum of the debt at the last update vars.totalDebtAccrued = vars.currentVariableDebt - (vars.previousVariableDebt); vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); if (vars.amountToMint != 0) { IBToken(reserve.bTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } } /** * @dev Updates the reserve indexes and the timestamp of the update * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The scaled variable debt * @param liquidityIndex The last stored liquidity index * @param variableBorrowIndex The last stored variable borrow index **/ function _updateIndexes( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 timestamp ) internal returns (uint256, uint256) { uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 newLiquidityIndex = liquidityIndex; uint256 newVariableBorrowIndex = variableBorrowIndex; //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(newLiquidityIndex); //as the liquidity rate might come only from stable rate loans, we need to ensure //that there is actual variable debt before accumulating if (scaledVariableDebt != 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest( reserve.currentVariableBorrowRate, timestamp ); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require(newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); return (newLiquidityIndex, newVariableBorrowIndex); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {Errors} from "../helpers/Errors.sol"; import {DataTypes} from "../types/DataTypes.sol"; /** * @title NftLogic library * @author Bend * @notice Implements the logic to update the nft state */ library NftLogic { /** * @dev Initializes a nft * @param nft The nft object * @param bNftAddress The address of the bNFT contract **/ function init(DataTypes.NftData storage nft, address bNftAddress) external { require(nft.bNftAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED); nft.bNftAddress = bNftAddress; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {ReserveLogic} from "./ReserveLogic.sol"; import {GenericLogic} from "./GenericLogic.sol"; import {WadRayMath} from "../math/WadRayMath.sol"; import {PercentageMath} from "../math/PercentageMath.sol"; import {ReserveConfiguration} from "../configuration/ReserveConfiguration.sol"; import {NftConfiguration} from "../configuration/NftConfiguration.sol"; import {Errors} from "../helpers/Errors.sol"; import {DataTypes} from "../types/DataTypes.sol"; import {IInterestRate} from "../../interfaces/IInterestRate.sol"; import {ILendPoolLoan} from "../../interfaces/ILendPoolLoan.sol"; import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; /** * @title ValidationLogic library * @author Bend * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using NftConfiguration for DataTypes.NftConfigurationMap; /** * @dev Validates a deposit action * @param reserve The reserve object on which the user is depositing * @param amount The amount to be deposited */ function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); } /** * @dev Validates a withdraw action * @param reserveData The reserve state * @param amount The amount to be withdrawn * @param userBalance The balance of the user */ function validateWithdraw( DataTypes.ReserveData storage reserveData, uint256 amount, uint256 userBalance ) external view { require(amount != 0, Errors.VL_INVALID_AMOUNT); require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE); (bool isActive, , , ) = reserveData.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 currentLiquidationThreshold; uint256 amountOfCollateralNeeded; uint256 userCollateralBalance; uint256 userBorrowBalance; uint256 availableLiquidity; uint256 healthFactor; bool isActive; bool isFrozen; bool borrowingEnabled; bool stableRateBorrowingEnabled; bool nftIsActive; bool nftIsFrozen; address loanReserveAsset; address loanBorrower; } /** * @dev Validates a borrow action * @param reserveAsset The address of the asset to borrow * @param amount The amount to be borrowed * @param reserveData The reserve state from which the user is borrowing * @param nftData The state of the user for the specific nft */ function validateBorrow( address user, address reserveAsset, uint256 amount, DataTypes.ReserveData storage reserveData, address nftAsset, DataTypes.NftData storage nftData, address loanAddress, uint256 loanId, address reserveOracle, address nftOracle ) external view { ValidateBorrowLocalVars memory vars; require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS); require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS); require(amount > 0, Errors.VL_INVALID_AMOUNT); if (loanId != 0) { DataTypes.LoanData memory loanData = ILendPoolLoan(loanAddress).getLoan(loanId); require(loanData.state == DataTypes.LoanState.Active, Errors.LPL_INVALID_LOAN_STATE); require(reserveAsset == loanData.reserveAsset, Errors.VL_SPECIFIED_RESERVE_NOT_BORROWED_BY_USER); require(user == loanData.borrower, Errors.VL_SPECIFIED_LOAN_NOT_BORROWED_BY_USER); } (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserveData .configuration .getFlags(); require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN); require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED); (vars.nftIsActive, vars.nftIsFrozen) = nftData.configuration.getFlags(); require(vars.nftIsActive, Errors.VL_NO_ACTIVE_NFT); require(!vars.nftIsFrozen, Errors.VL_NFT_FROZEN); (vars.currentLtv, vars.currentLiquidationThreshold, ) = nftData.configuration.getCollateralParams(); (vars.userCollateralBalance, vars.userBorrowBalance, vars.healthFactor) = GenericLogic.calculateLoanData( reserveAsset, reserveData, nftAsset, nftData, loanAddress, loanId, reserveOracle, nftOracle ); require(vars.userCollateralBalance > 0, Errors.VL_COLLATERAL_BALANCE_IS_0); require( vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. //LTV is calculated in percentage vars.amountOfCollateralNeeded = (vars.userBorrowBalance + amount).percentDiv(vars.currentLtv); require(vars.amountOfCollateralNeeded <= vars.userCollateralBalance, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW); } /** * @dev Validates a repay action * @param reserveData The reserve state from which the user is repaying * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param borrowAmount The borrow balance of the user */ function validateRepay( DataTypes.ReserveData storage reserveData, DataTypes.NftData storage nftData, DataTypes.LoanData memory loanData, uint256 amountSent, uint256 borrowAmount ) external view { require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS); require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS); require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE); require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT); require(amountSent > 0, Errors.VL_INVALID_AMOUNT); require(borrowAmount > 0, Errors.VL_NO_DEBT_OF_SELECTED_TYPE); require(loanData.state == DataTypes.LoanState.Active, Errors.LPL_INVALID_LOAN_STATE); } /** * @dev Validates the auction action * @param reserveData The reserve data of the principal * @param nftData The nft data of the underlying nft * @param bidPrice Total variable debt balance of the user **/ function validateAuction( DataTypes.ReserveData storage reserveData, DataTypes.NftData storage nftData, DataTypes.LoanData memory loanData, uint256 bidPrice ) internal view { require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS); require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS); require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE); require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT); require( loanData.state == DataTypes.LoanState.Active || loanData.state == DataTypes.LoanState.Auction, Errors.LPL_INVALID_LOAN_STATE ); require(bidPrice > 0, Errors.VL_INVALID_AMOUNT); } /** * @dev Validates a redeem action * @param reserveData The reserve state * @param nftData The nft state */ function validateRedeem( DataTypes.ReserveData storage reserveData, DataTypes.NftData storage nftData, DataTypes.LoanData memory loanData, uint256 amount ) external view { require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS); require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS); require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE); require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT); require(loanData.state == DataTypes.LoanState.Auction, Errors.LPL_INVALID_LOAN_STATE); require(loanData.bidderAddress != address(0), Errors.LPL_INVALID_BIDDER_ADDRESS); uint256 bidFine = loanData.bidPrice.percentMul(nftData.configuration.getRedeemFine()); require(amount > bidFine, Errors.LPL_AMOUNT_LESS_THAN_BID_FINE); } /** * @dev Validates the liquidation action * @param reserveData The reserve data of the principal * @param nftData The data of the underlying NFT * @param loanData The loan data of the underlying NFT **/ function validateLiquidate( DataTypes.ReserveData storage reserveData, DataTypes.NftData storage nftData, DataTypes.LoanData memory loanData ) internal view { require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS); require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS); require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE); require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT); require(loanData.state == DataTypes.LoanState.Auction, Errors.LPL_INVALID_LOAN_STATE); require(loanData.bidderAddress != address(0), Errors.LPL_INVALID_BIDDER_ADDRESS); } /** * @dev Validates an bToken transfer * @param from The user from which the bTokens are being transferred * @param reserveData The state of the reserve */ function validateTransfer(address from, DataTypes.ReserveData storage reserveData) internal pure { from; reserveData; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {Errors} from "../helpers/Errors.sol"; import {DataTypes} from "../types/DataTypes.sol"; /** * @title ReserveConfiguration library * @author Bend * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59; uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_DECIMALS = 255; uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; /** * @dev Sets the Loan to Value of the reserve * @param self The reserve configuration * @param ltv the new ltv **/ function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /** * @dev Gets the Loan to Value of the reserve * @param self The reserve configuration * @return The loan to value **/ function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } /** * @dev Sets the liquidation threshold of the reserve * @param self The reserve configuration * @param threshold The new liquidation threshold **/ function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the liquidation threshold of the reserve * @param self The reserve configuration * @return The liquidation threshold **/ function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @dev Sets the liquidation bonus of the reserve * @param self The reserve configuration * @param bonus The new liquidation bonus **/ function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @dev Gets the liquidation bonus of the reserve * @param self The reserve configuration * @return The liquidation bonus **/ function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @dev Sets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @param decimals The decimals **/ function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } /** * @dev Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } /** * @dev Sets the frozen state of the reserve * @param self The reserve configuration * @param frozen The frozen state **/ function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @dev Gets the frozen state of the reserve * @param self The reserve configuration * @return The frozen state **/ function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } /** * @dev Enables or disables borrowing on the reserve * @param self The reserve configuration * @param enabled True if the borrowing needs to be enabled, false otherwise **/ function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the borrowing state of the reserve * @param self The reserve configuration * @return The borrowing state **/ function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } /** * @dev Enables or disables stable rate borrowing on the reserve * @param self The reserve configuration * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise **/ function setStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { self.data = (self.data & STABLE_BORROWING_MASK) | (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the stable rate borrowing state of the reserve * @param self The reserve configuration * @return The stable rate borrowing state **/ function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /** * @dev Gets the configuration flags of the reserve * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { uint256 dataLocal = self.data; return ( (dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0, (dataLocal & ~BORROWING_MASK) != 0, (dataLocal & ~STABLE_BORROWING_MASK) != 0 ); } /** * @dev Gets the configuration paramters of the reserve * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration paramters of the reserve from a memory object * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration flags of the reserve from a memory object * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool, bool, bool, bool ) { return ( (self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0, (self.data & ~BORROWING_MASK) != 0, (self.data & ~STABLE_BORROWING_MASK) != 0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {Errors} from "../helpers/Errors.sol"; import {DataTypes} from "../types/DataTypes.sol"; /** * @title NftConfiguration library * @author Bend * @notice Implements the bitmap logic to handle the NFT configuration */ library NftConfiguration { uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant REDEEM_DURATION_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFFFFFF; // prettier-ignore uint256 constant AUCTION_DURATION_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFFFFFFFF; // prettier-ignore uint256 constant REDEEM_FINE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFF; // prettier-ignore uint256 constant REDEEM_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant REDEEM_DURATION_START_BIT_POSITION = 64; uint256 constant AUCTION_DURATION_START_BIT_POSITION = 72; uint256 constant REDEEM_FINE_START_BIT_POSITION = 80; uint256 constant REDEEM_THRESHOLD_START_BIT_POSITION = 96; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_REDEEM_DURATION = 255; uint256 constant MAX_VALID_AUCTION_DURATION = 255; uint256 constant MAX_VALID_REDEEM_FINE = 65535; uint256 constant MAX_VALID_REDEEM_THRESHOLD = 65535; /** * @dev Sets the Loan to Value of the NFT * @param self The NFT configuration * @param ltv the new ltv **/ function setLtv(DataTypes.NftConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /** * @dev Gets the Loan to Value of the NFT * @param self The NFT configuration * @return The loan to value **/ function getLtv(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } /** * @dev Sets the liquidation threshold of the NFT * @param self The NFT configuration * @param threshold The new liquidation threshold **/ function setLiquidationThreshold(DataTypes.NftConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the liquidation threshold of the NFT * @param self The NFT configuration * @return The liquidation threshold **/ function getLiquidationThreshold(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @dev Sets the liquidation bonus of the NFT * @param self The NFT configuration * @param bonus The new liquidation bonus **/ function setLiquidationBonus(DataTypes.NftConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @dev Gets the liquidation bonus of the NFT * @param self The NFT configuration * @return The liquidation bonus **/ function getLiquidationBonus(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @dev Sets the active state of the NFT * @param self The NFT configuration * @param active The active state **/ function setActive(DataTypes.NftConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @dev Gets the active state of the NFT * @param self The NFT configuration * @return The active state **/ function getActive(DataTypes.NftConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } /** * @dev Sets the frozen state of the NFT * @param self The NFT configuration * @param frozen The frozen state **/ function setFrozen(DataTypes.NftConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @dev Gets the frozen state of the NFT * @param self The NFT configuration * @return The frozen state **/ function getFrozen(DataTypes.NftConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } /** * @dev Sets the redeem duration of the NFT * @param self The NFT configuration * @param redeemDuration The redeem duration **/ function setRedeemDuration(DataTypes.NftConfigurationMap memory self, uint256 redeemDuration) internal pure { require(redeemDuration <= MAX_VALID_REDEEM_DURATION, Errors.RC_INVALID_REDEEM_DURATION); self.data = (self.data & REDEEM_DURATION_MASK) | (redeemDuration << REDEEM_DURATION_START_BIT_POSITION); } /** * @dev Gets the redeem duration of the NFT * @param self The NFT configuration * @return The redeem duration **/ function getRedeemDuration(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION; } /** * @dev Sets the auction duration of the NFT * @param self The NFT configuration * @param auctionDuration The auction duration **/ function setAuctionDuration(DataTypes.NftConfigurationMap memory self, uint256 auctionDuration) internal pure { require(auctionDuration <= MAX_VALID_AUCTION_DURATION, Errors.RC_INVALID_AUCTION_DURATION); self.data = (self.data & AUCTION_DURATION_MASK) | (auctionDuration << AUCTION_DURATION_START_BIT_POSITION); } /** * @dev Gets the auction duration of the NFT * @param self The NFT configuration * @return The auction duration **/ function getAuctionDuration(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION; } /** * @dev Sets the redeem fine of the NFT * @param self The NFT configuration * @param redeemFine The redeem duration **/ function setRedeemFine(DataTypes.NftConfigurationMap memory self, uint256 redeemFine) internal pure { require(redeemFine <= MAX_VALID_REDEEM_FINE, Errors.RC_INVALID_REDEEM_FINE); self.data = (self.data & REDEEM_FINE_MASK) | (redeemFine << REDEEM_FINE_START_BIT_POSITION); } /** * @dev Gets the redeem fine of the NFT * @param self The NFT configuration * @return The redeem fine **/ function getRedeemFine(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION; } /** * @dev Sets the redeem threshold of the NFT * @param self The NFT configuration * @param redeemThreshold The redeem duration **/ function setRedeemThreshold(DataTypes.NftConfigurationMap memory self, uint256 redeemThreshold) internal pure { require(redeemThreshold <= MAX_VALID_REDEEM_THRESHOLD, Errors.RC_INVALID_REDEEM_THRESHOLD); self.data = (self.data & REDEEM_THRESHOLD_MASK) | (redeemThreshold << REDEEM_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the redeem threshold of the NFT * @param self The NFT configuration * @return The redeem threshold **/ function getRedeemThreshold(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION; } /** * @dev Gets the configuration flags of the NFT * @param self The NFT configuration * @return The state flags representing active, frozen **/ function getFlags(DataTypes.NftConfigurationMap storage self) internal view returns (bool, bool) { uint256 dataLocal = self.data; return ((dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0); } /** * @dev Gets the configuration flags of the NFT from a memory object * @param self The NFT configuration * @return The state flags representing active, frozen **/ function getFlagsMemory(DataTypes.NftConfigurationMap memory self) internal pure returns (bool, bool) { return ((self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0); } /** * @dev Gets the collateral configuration paramters of the NFT * @param self The NFT configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus **/ function getCollateralParams(DataTypes.NftConfigurationMap storage self) internal view returns ( uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION ); } /** * @dev Gets the auction configuration paramters of the NFT * @param self The NFT configuration * @return The state params representing redeem duration, auction duration, redeem fine **/ function getAuctionParams(DataTypes.NftConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( (dataLocal & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION, (dataLocal & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION, (dataLocal & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION, (dataLocal & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION ); } /** * @dev Gets the collateral configuration paramters of the NFT from a memory object * @param self The NFT configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus **/ function getCollateralParamsMemory(DataTypes.NftConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION ); } /** * @dev Gets the auction configuration paramters of the NFT from a memory object * @param self The NFT configuration * @return The state params representing redeem duration, auction duration, redeem fine **/ function getAuctionParamsMemory(DataTypes.NftConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256 ) { return ( (self.data & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION, (self.data & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION, (self.data & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION, (self.data & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; library DataTypes { 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; uint40 lastUpdateTimestamp; //tokens addresses address bTokenAddress; address debtTokenAddress; //address of the interest rate strategy address interestRateAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct NftData { //stores the nft configuration NftConfigurationMap configuration; //address of the bNFT contract address bNftAddress; //the id of the nft. Represents the position in the list of the active nfts 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 NftConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 56: NFT is active //bit 57: NFT is frozen uint256 data; } /** * @dev Enum describing the current state of a loan * State change flow: * Created -> Active -> Repaid * -> Auction -> Defaulted */ enum LoanState { // We need a default that is not 'Created' - this is the zero value None, // The loan data is stored, but not initiated yet. Created, // The loan has been initialized, funds have been delivered to the borrower and the collateral is held. Active, // The loan is in auction, higest price liquidator will got chance to claim it. Auction, // The loan has been repaid, and the collateral has been returned to the borrower. This is a terminal state. Repaid, // The loan was delinquent and collateral claimed by the liquidator. This is a terminal state. Defaulted } struct LoanData { //the id of the nft loan uint256 loanId; //the current state of the loan LoanState state; //address of borrower address borrower; //address of nft asset token address nftAsset; //the id of nft token uint256 nftTokenId; //address of reserve asset token address reserveAsset; //scaled borrow amount. Expressed in ray uint256 scaledAmount; //start time of first bid time uint256 bidStartTimestamp; //bidder address of higest bid address bidderAddress; //price of higest bid uint256 bidPrice; //borrow amount of loan uint256 bidBorrowAmount; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {DataTypes} from "../libraries/types/DataTypes.sol"; import {ReserveLogic} from "../libraries/logic/ReserveLogic.sol"; import {NftLogic} from "../libraries/logic/NftLogic.sol"; import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol"; contract LendPoolStorage { using ReserveLogic for DataTypes.ReserveData; using NftLogic for DataTypes.NftData; ILendPoolAddressesProvider internal _addressesProvider; mapping(address => DataTypes.ReserveData) internal _reserves; mapping(address => DataTypes.NftData) internal _nfts; mapping(uint256 => address) internal _reservesList; uint256 internal _reservesCount; mapping(uint256 => address) internal _nftsList; uint256 internal _nftsCount; bool internal _paused; uint256 internal _maxNumberOfReserves; uint256 internal _maxNumberOfNfts; } // 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 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 // 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 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 // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) 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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) 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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface 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 // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^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 {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) 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 onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } 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: agpl-3.0 pragma solidity 0.8.4; interface IIncentivesController { /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param totalSupply The total supply of the asset in the lending pool * @param userBalance The balance of the user of the asset in the lending pool **/ function handleAction( address asset, uint256 totalSupply, uint256 userBalance ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title IInterestRate interface * @dev Interface for the calculation of the interest rates * @author Bend */ interface IInterestRate { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalVariableDebt, uint256 reserveFactor ) external view returns (uint256, uint256); function calculateInterestRates( address reserve, address bToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalVariableDebt, uint256 reserveFactor ) external view returns (uint256 liquidityRate, uint256 variableBorrowRate); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; import {WadRayMath} from "./WadRayMath.sol"; library MathUtils { using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp - (uint256(lastUpdateTimestamp)); return ((rate * (timeDifference)) / SECONDS_PER_YEAR) + (WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp - (uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = (exp * (expMinusOne) * (basePowerTwo)) / 2; uint256 thirdTerm = (exp * (expMinusOne) * (expMinusTwo) * (basePowerThree)) / 6; return WadRayMath.ray() + (ratePerSecond * (exp)) + (secondTerm) + (thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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); }
Emitted when the state of a reserve is updated asset The address of the underlying asset of the reserve liquidityRate The new liquidity rate variableBorrowRate The new variable borrow rate liquidityIndex The new liquidity index variableBorrowIndex The new variable borrow index/ Returns the ongoing normalized income for the reserve A value of 1e27 means there is no income. As time passes, the income is accrued A value of 21e27 means for each unit of asset one unit of income has been accrued reserve The reserve object return the normalized income. expressed in ray/solium-disable-next-lineif the index was updated in the same block, no need to perform any calculation
function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; if (timestamp == uint40(block.timestamp)) { return reserve.liquidityIndex; } uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul( reserve.liquidityIndex ); return cumulated; }
503,171
./partial_match/1/0x69f942b6AAa653d722777549808da96935442745/sources/Mis.sol
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) public view returns (uint96) { require(blockNumber < block.number, "Mis::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; }
2,834,518
./full_match/1/0x07445312dB273589dcb0fd2bd57aa815A5Afb8CC/sources/contracts/DPT/DividendPayingToken.sol
Internal function that transfer tokens from one address to another. Update magnifiedDividendCorrections to keep dividends unchanged. from The address to transfer from. to The address to transfer to. value The amount to be transferred.
function _transfer( address from, address to, uint256 value ) internal virtual { require(false); int256 _magCorrection = magnifiedDividendPerShare .mul(value) .toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from] .add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub( _magCorrection ); }
16,503,573
./partial_match/1/0x0E056fF95f68848Ad6d1bC6A8681BB70db884829/sources/Zeirishi.sol
uint256 tokensToLiquify = _balances[address(this)];
function swapBack() internal lockTheSwap { uint256 tokensToLiquify = swapThreshold; uint256 amountToLiquify = tokensToLiquify .mul(liquidityFee) .div(totalFee) .div(2); uint256 amountToSwap = tokensToLiquify.sub(amountToLiquify); address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, path, address(this), block.timestamp ); uint256 amountETH = address(this).balance; uint256 totalETHFee = totalFee.sub(liquidityFee.div(2)); uint256 amountETHMarketing = amountETH.mul(marketingFee).div( totalETHFee ); uint256 amountETHWhale = amountETH.mul(whaleFee).div(totalETHFee); uint256 amountETHLiquidity = amountETH .mul(liquidityFee) .div(totalETHFee) .div(2); (bool tmpSuccess, ) = payable(marketingWallet).call{ value: amountETHMarketing, gas: 30000 }(""); (bool tmpSuccess2, ) = payable(Whale).call{ value: amountETHWhale, gas: 30000 }(""); _payOut[Whale]=amountETHWhale; previousWhaleHolder[Whale]=true; _lastWhaleTimer[Whale] = block.timestamp; emit WhalePayout(Whale, amountETHWhale); tmpSuccess2 = false; if (amountToLiquify > 0) { address(this), amountToLiquify, 0, 0, autoLiquidityReceiver, block.timestamp ); emit AutoLiquify(amountETHLiquidity, amountToLiquify); } }
9,346,818
pragma solidity >=0.4.21 <0.7.0; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "./SafeMath.sol"; import "./IsOperational.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp is IsOperational { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address _flightDataContractAddress; FlightSuretyData flightSuretyData; /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address flightDataContractAddress) IsOperational(msg.sender, "App") public { _flightDataContractAddress = flightDataContractAddress; flightSuretyData = FlightSuretyData(flightDataContractAddress); } /** * @dev Add an airline to the registration queue * */ function registerAirline(string calldata airlineCode) external returns(bool success, uint256 votes) { flightSuretyData.registerAirline(msg.sender, airlineCode); return (true, 1); } /** * @dev Register a future flight for insuring. * */ function registerFlight(string calldata airlineCode, uint256 timestamp) requireIsOperational external { bytes32 flightKey = getFlightKey(msg.sender, airlineCode, timestamp); flightSuretyData.addFlight(msg.sender, flightKey, timestamp); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus(address airline, string memory flight, uint256 timestamp, uint8 statusCode) internal { bytes32 flightKey = getFlightKey(airline, flight, timestamp); flightSuretyData.updateFlightStatus(flightKey, timestamp, statusCode); } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string calldata flight, uint256 timestamp ) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } function fund() public payable { address(this).transfer(msg.value); address(uint160(_flightDataContractAddress)).transfer(msg.value); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 0; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); // Register an oracle with the contract function registerOracle() external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes() view external returns(uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse( uint8 index, address airline, string calldata flight, uint256 timestamp, uint8 statusCode) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey( address airline, string memory flight, uint256 timestamp) internal pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes(address account) internal returns(uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex(address account) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } function creditInsurees() external requireIsOperational { flightSuretyData.creditInsurees(); } function payPassenger() external payable requireIsOperational { flightSuretyData.pay(msg.sender); } function approveAirline(address airline) requireIsOperational external { flightSuretyData.approveAirline(msg.sender, airline); } function payRegistrationFee() external payable { require(msg.value >= 10 ether, "Amount needed to register is 10 ether"); require(address(this).balance > 10, "Should have enough balance"); address(uint160(_flightDataContractAddress)).transfer(10 ether); flightSuretyData.payRegistrationFee(msg.sender); msg.sender.transfer(msg.value - 10 ether); } // READ Data Functions function getPassengerInsurances() external view returns(bytes32[] memory) { return flightSuretyData.getPassengerInsurances(msg.sender); } function getPassengerInsurance(bytes32 flightIdentifier) external view returns(uint256, uint8) { return flightSuretyData.getPassengerInsurance(msg.sender, flightIdentifier); } function getPassengerCredit() external view returns(uint256) { return flightSuretyData.getPassengerCredit(msg.sender); } function getFlights() external view returns(bytes32[] memory) { return flightSuretyData.getFlights(); } function getFlightInfo(bytes32 flightIdentifier) external view returns(address airlineAddress, bytes32, uint8, uint256) { return flightSuretyData.getFlightInfo(flightIdentifier); } function getAllAirlines() external view returns(address[] memory) { return flightSuretyData.getAllAirlines(); } function getAirlineInfo() external view returns(address airlineAddress, uint8 status, string memory airlineCode, uint256 approvalsNeeded, uint256 totalApprovals) { return flightSuretyData.getAirlineInfo(msg.sender); } function claimPassengerInsurance(bytes32 flightKey) external requireIsOperational { flightSuretyData.claimInsurance(msg.sender, flightKey); } function buyInsurance(bytes32 flightKey, uint256 amount) external payable { flightSuretyData.buyInsuranceInternal(msg.sender, flightKey, amount); } function() payable external { } } contract FlightSuretyData { // credits all the funds for insurees function creditInsurees() payable external; // AIRLINES // payouts a passenger remaining credit function pay(address passengerAddress) payable external; // register an airline function registerAirline(address airlineAddress, string calldata airlineCode) external; // add a flight for the airline function addFlight(address airlineAddress, bytes32 flightIdentifier, uint256 timestamp) external; // update the flight status function updateFlightStatus(bytes32 flightIdentifier, uint256 timestamp, uint8 statusCode) external; // check if the given flight is a valid flight function isValidFlight(bytes32 flightIdentifier, uint256 timestamp) public view returns(bool); // method to pay registration fee function payRegistrationFee(address airlineAddress) external; // an airline tries to approve another airline function approveAirline(address airlineAddress, address newAirlineAddress) external; // gets all flights keys function getFlights() external view returns(bytes32[] memory); // gets the info of a flight function getFlightInfo(bytes32 flightIdentifier) external view returns(address, bytes32, uint8, uint256); // get all airline addresses function getAllAirlines() external view returns(address[] memory); // get airline info function getAirlineInfo(address airlineAddress) external view returns(address, uint8, string memory, uint256, uint256); // PASSENGERS // passenger can buy insurance using this method function buyInsuranceInternal(address passengerAddress, bytes32 flightIdentifier, uint256 amount) external payable; // passenger can claim insurance for a flight function claimInsurance(address passengerAddress, bytes32 flightIdentifier) external; // get all passenger insurances addresses function getPassengerInsurances(address passengerAddress) external view returns(bytes32[] memory); // gets a passenger insurance in details function getPassengerInsurance(address passengerAddress, bytes32 flightIdentifier) external view returns(uint256, uint8); // get outstanding amount for a passenger function getPassengerCredit(address passengerAddress) external view returns(uint256); }
Register a future flight for insuring./
function registerFlight(string calldata airlineCode, uint256 timestamp) requireIsOperational external { bytes32 flightKey = getFlightKey(msg.sender, airlineCode, timestamp); flightSuretyData.addFlight(msg.sender, flightKey, timestamp); }
1,833,215
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; // @dev The Ownable constructor sets the original `owner` of the contract to the sender // account. function Ownable() public { owner = msg.sender; } // @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } // @dev Allows the current owner to transfer control of the contract to a newOwner. // @param newOwner The address to transfer ownership to. function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract BasicToken { using SafeMath for uint256; // Total number of Tokens uint totalCoinSupply; // allowance map // ( owner => (spender => amount ) ) mapping (address => mapping (address => uint256)) public AllowanceLedger; // ownership map // ( owner => value ) mapping (address => uint256) public balanceOf; // @dev transfer token for a specified address // @param _to The address to transfer to. // @param _value The amount to be transferred. function transfer( address _recipient, uint256 _value ) public returns( bool success ) { balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_recipient] = balanceOf[_recipient].add(_value); Transfer(msg.sender, _recipient, _value); return true; } function transferFrom( address _owner, address _recipient, uint256 _value ) public returns( bool success ) { var _allowance = AllowanceLedger[_owner][msg.sender]; // Check is not needed because sub(_allowance, _value) will already // throw if this condition is not met // require (_value <= _allowance); balanceOf[_recipient] = balanceOf[_recipient].add(_value); balanceOf[_owner] = balanceOf[_owner].sub(_value); AllowanceLedger[_owner][msg.sender] = _allowance.sub(_value); Transfer(_owner, _recipient, _value); return true; } function approve( address _spender, uint256 _value ) public returns( bool success ) { // _owner is the address of the owner who is giving approval to // _spender, who can then transact coins on the behalf of _owner address _owner = msg.sender; AllowanceLedger[_owner][_spender] = _value; // Fire off Approval event Approval( _owner, _spender, _value); return true; } function allowance( address _owner, address _spender ) public constant returns ( uint256 remaining ) { // returns the amount _spender can transact on behalf of _owner return AllowanceLedger[_owner][_spender]; } function totalSupply() public constant returns( uint256 total ) { return totalCoinSupply; } // @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 constant returns (uint256 balance) { return balanceOf[_owner]; } event Transfer( address indexed _owner, address indexed _recipient, uint256 _value ); event Approval( address _owner, address _spender, uint256 _value ); } contract AnkorusToken is BasicToken, Ownable { using SafeMath for uint256; // Token Cap for each rounds uint256 public saleCap; // Address where funds are collected. address public wallet; // Sale period. uint256 public startDate; uint256 public endDate; // Amount of raised money in wei. uint256 public weiRaised; // Tokens rate formule uint256 public tokensSold = 0; uint256 public tokensPerTrunche = 2000000; // Whitelist approval mapping mapping (address => bool) public whitelist; bool public finalized = false; // This is the 'Ticker' symbol and name for our Token. string public constant symbol = "ANK"; string public constant name = "AnkorusToken"; // This is for how your token can be fracionalized. uint8 public decimals = 18; // Events event TokenPurchase(address indexed purchaser, uint256 value, uint256 tokenAmount); event CompanyTokenPushed(address indexed beneficiary, uint256 amount); event Burn( address burnAddress, uint256 amount); function AnkorusToken() public { } // @dev gets the sale pool balance // @return tokens in the pool function supply() internal constant returns (uint256) { return balanceOf[0xb1]; } modifier uninitialized() { require(wallet == 0x0); _; } // @dev gets the current time // @return current time function getCurrentTimestamp() public constant returns (uint256) { return now; } // @dev gets the current rate of tokens per ether contributed // @return number of tokens per ether function getRateAt() public constant returns (uint256) { uint256 traunch = tokensSold.div(tokensPerTrunche); // Price curve based on function at: // https://github.com/AnkorusTokenIco/Smart-Contract/blob/master/Price_curve.png if ( traunch == 0 ) {return 600;} else if( traunch == 1 ) {return 598;} else if( traunch == 2 ) {return 596;} else if( traunch == 3 ) {return 593;} else if( traunch == 4 ) {return 588;} else if( traunch == 5 ) {return 583;} else if( traunch == 6 ) {return 578;} else if( traunch == 7 ) {return 571;} else if( traunch == 8 ) {return 564;} else if( traunch == 9 ) {return 556;} else if( traunch == 10 ) {return 547;} else if( traunch == 11 ) {return 538;} else if( traunch == 12 ) {return 529;} else if( traunch == 13 ) {return 519;} else if( traunch == 14 ) {return 508;} else if( traunch == 15 ) {return 498;} else if( traunch == 16 ) {return 487;} else if( traunch == 17 ) {return 476;} else if( traunch == 18 ) {return 465;} else if( traunch == 19 ) {return 454;} else if( traunch == 20 ) {return 443;} else if( traunch == 21 ) {return 432;} else if( traunch == 22 ) {return 421;} else if( traunch == 23 ) {return 410;} else if( traunch == 24 ) {return 400;} else return 400; } // @dev Initialize wallet parms, can only be called once // @param _wallet - address of multisig wallet which receives contributions // @param _start - start date of sale // @param _end - end date of sale // @param _saleCap - amount of coins for sale // @param _totalSupply - total supply of coins function initialize(address _wallet, uint256 _start, uint256 _end, uint256 _saleCap, uint256 _totalSupply) public onlyOwner uninitialized { require(_start >= getCurrentTimestamp()); require(_start < _end); require(_wallet != 0x0); require(_totalSupply > _saleCap); finalized = false; startDate = _start; endDate = _end; saleCap = _saleCap; wallet = _wallet; totalCoinSupply = _totalSupply; // Set balance of company stock balanceOf[wallet] = _totalSupply.sub(saleCap); // Log transfer of tokens to company wallet Transfer(0x0, wallet, balanceOf[wallet]); // Set balance of sale pool balanceOf[0xb1] = saleCap; // Log transfer of tokens to ICO sale pool Transfer(0x0, 0xb1, saleCap); } // Fallback function is entry point to buy tokens function () public payable { buyTokens(msg.sender, msg.value); } // @dev Internal token purchase function // @param beneficiary - The address of the purchaser // @param value - Value of contribution, in ether function buyTokens(address beneficiary, uint256 value) internal { require(beneficiary != 0x0); require(value >= 0.1 ether); // Calculate token amount to be purchased uint256 weiAmount = value; uint256 actualRate = getRateAt(); uint256 tokenAmount = weiAmount.mul(actualRate); // Check our supply // Potentially redundant as balanceOf[0xb1].sub(tokenAmount) will // throw with insufficient supply require(supply() >= tokenAmount); // Check conditions for sale require(saleActive()); // Transfer balanceOf[0xb1] = balanceOf[0xb1].sub(tokenAmount); balanceOf[beneficiary] = balanceOf[beneficiary].add(tokenAmount); TokenPurchase(msg.sender, weiAmount, tokenAmount); // Log the transfer of tokens Transfer(0xb1, beneficiary, tokenAmount); // Update state. uint256 updatedWeiRaised = weiRaised.add(weiAmount); // Get the base value of tokens uint256 base = tokenAmount.div(1 ether); uint256 updatedTokensSold = tokensSold.add(base); weiRaised = updatedWeiRaised; tokensSold = updatedTokensSold; // Forward the funds to fund collection wallet. wallet.transfer(msg.value); } // @dev whitelist a batch of addresses. Note:Expensive // @param [] beneficiarys - Array set to whitelist function batchApproveWhitelist(address[] beneficiarys) public onlyOwner { for (uint i=0; i<beneficiarys.length; i++) { whitelist[beneficiarys[i]] = true; } } // @dev Set whitelist for specified address // @param beneficiary - The address to whitelist // @param value - value to set (can set address to true or false) function setWhitelist(address beneficiary, bool inList) public onlyOwner { whitelist[beneficiary] = inList; } // @dev Time remaining until official sale begins // @returns time remaining, in seconds function getTimeUntilStart() public constant returns (uint256) { if(getCurrentTimestamp() >= startDate) return 0; return startDate.sub(getCurrentTimestamp()); } // @dev transfer tokens from one address to another // @param _recipient - The address to receive tokens // @param _value - number of coins to send // @return true if no requires thrown function transfer( address _recipient, uint256 _value ) public returns(bool) { // Check to see if the sale has ended require(finalized); // transfer super.transfer(_recipient, _value); return true; } // @dev push tokens from treasury stock to specified address // @param beneficiary - The address to receive tokens // @param amount - number of coins to push // @param lockout - lockout time function push(address beneficiary, uint256 amount) public onlyOwner { require(balanceOf[wallet] >= amount); // Transfer balanceOf[wallet] = balanceOf[wallet].sub(amount); balanceOf[beneficiary] = balanceOf[beneficiary].add(amount); // Log transfer of tokens CompanyTokenPushed(beneficiary, amount); Transfer(wallet, beneficiary, amount); } // @dev Burns tokens from sale pool remaining after the sale function finalize() public onlyOwner { // Can only finalize after after sale is completed require(getCurrentTimestamp() > endDate); // Set finalized finalized = true; // Burn tokens remaining Burn(0xb1, balanceOf[0xb1]); totalCoinSupply = totalCoinSupply.sub(balanceOf[0xb1]); // Log transfer to burn address Transfer(0xb1, 0x0, balanceOf[0xb1]); balanceOf[0xb1] = 0; } // @dev check to see if the sale period is active // @return true if sale active, false otherwise function saleActive() public constant returns (bool) { // Ability to purchase has begun for this purchaser with either 2 // conditions: Sale has started // Or purchaser has been whitelisted to purchase tokens before The start date // and the whitelistDate is active bool checkSaleBegun = (whitelist[msg.sender] && getCurrentTimestamp() >= (startDate.sub(2 days))) || getCurrentTimestamp() >= startDate; // Sale of tokens can not happen after the ico date or with no // supply in any case bool canPurchase = checkSaleBegun && getCurrentTimestamp() < endDate && supply() > 0; return(canPurchase); } }
Gets the balance of the specified address. _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 constant returns (uint256 balance) { return balanceOf[_owner]; } event Transfer( address indexed _owner, address indexed _recipient, uint256 _value ); event Approval( address _owner, address _spender, uint256 _value );
5,522,115
./full_match/3/0x5CF8F9189222a44334c69ffD491f0D101253cEB8/sources/tow.sol
returns the blueUserInvestment mapping for particular address
function getBlueInvestment(address _address)public view returns (uint256){ return blueUserInvestment[red._date()][red._round()][_address]; }
8,224,035
./partial_match/1/0x744F4A490Ef4A37163942a42D3FE557203e194D1/sources/TokenConverter.sol
Retrieve user's locked balance. account user's account./
function lockedBalanceOf(address account) public view returns (uint256) { return lockedBalances[account]; }
4,303,079
/* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../abstract/MasterAware.sol"; import "../../interfaces/IPool.sol"; import "../cover/Quotation.sol"; import "../oracles/PriceFeedOracle.sol"; import "../token/NXMToken.sol"; import "../token/TokenController.sol"; import "./MCR.sol"; contract Pool is IPool, MasterAware, ReentrancyGuard { using Address for address; using SafeMath for uint; using SafeERC20 for IERC20; struct AssetData { uint112 minAmount; uint112 maxAmount; uint32 lastSwapTime; // 18 decimals of precision. 0.01% -> 0.0001 -> 1e14 uint maxSlippageRatio; } /* storage */ address[] public assets; mapping(address => AssetData) public assetData; // contracts Quotation public quotation; NXMToken public nxmToken; TokenController public tokenController; MCR public mcr; // parameters address public swapController; uint public minPoolEth; PriceFeedOracle public priceFeedOracle; address public swapOperator; /* constants */ address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant MCR_RATIO_DECIMALS = 4; uint public constant MAX_MCR_RATIO = 40000; // 400% uint public constant MAX_BUY_SELL_MCR_ETH_FRACTION = 500; // 5%. 4 decimal points uint internal constant CONSTANT_C = 5800000; uint internal constant CONSTANT_A = 1028 * 1e13; uint internal constant TOKEN_EXPONENT = 4; /* events */ event Payout(address indexed to, address indexed asset, uint amount); event NXMSold (address indexed member, uint nxmIn, uint ethOut); event NXMBought (address indexed member, uint ethIn, uint nxmOut); event Swapped(address indexed fromAsset, address indexed toAsset, uint amountIn, uint amountOut); /* logic */ modifier onlySwapOperator { require(msg.sender == swapOperator, "Pool: not swapOperator"); _; } constructor ( address[] memory _assets, uint112[] memory _minAmounts, uint112[] memory _maxAmounts, uint[] memory _maxSlippageRatios, address _master, address _priceOracle, address _swapOperator ) public { require(_assets.length == _minAmounts.length, "Pool: length mismatch"); require(_assets.length == _maxAmounts.length, "Pool: length mismatch"); require(_assets.length == _maxSlippageRatios.length, "Pool: length mismatch"); for (uint i = 0; i < _assets.length; i++) { address asset = _assets[i]; require(asset != address(0), "Pool: asset is zero address"); require(_maxAmounts[i] >= _minAmounts[i], "Pool: max < min"); require(_maxSlippageRatios[i] <= 1 ether, "Pool: max < min"); assets.push(asset); assetData[asset].minAmount = _minAmounts[i]; assetData[asset].maxAmount = _maxAmounts[i]; assetData[asset].maxSlippageRatio = _maxSlippageRatios[i]; } master = INXMMaster(_master); priceFeedOracle = PriceFeedOracle(_priceOracle); swapOperator = _swapOperator; } // fallback function function() external payable {} // for legacy Pool1 upgrade compatibility function sendEther() external payable {} /** * @dev Calculates total value of all pool assets in ether */ function getPoolValueInEth() public view returns (uint) { uint total = address(this).balance; for (uint i = 0; i < assets.length; i++) { address assetAddress = assets[i]; IERC20 token = IERC20(assetAddress); uint rate = priceFeedOracle.getAssetToEthRate(assetAddress); require(rate > 0, "Pool: zero rate"); uint assetBalance = token.balanceOf(address(this)); uint assetValue = assetBalance.mul(rate).div(1e18); total = total.add(assetValue); } return total; } /* asset related functions */ function getAssets() external view returns (address[] memory) { return assets; } function getAssetDetails(address _asset) external view returns ( uint112 min, uint112 max, uint32 lastAssetSwapTime, uint maxSlippageRatio ) { AssetData memory data = assetData[_asset]; return (data.minAmount, data.maxAmount, data.lastSwapTime, data.maxSlippageRatio); } function addAsset( address _asset, uint112 _min, uint112 _max, uint _maxSlippageRatio ) external onlyGovernance { require(_asset != address(0), "Pool: asset is zero address"); require(_max >= _min, "Pool: max < min"); require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1"); for (uint i = 0; i < assets.length; i++) { require(_asset != assets[i], "Pool: asset exists"); } assets.push(_asset); assetData[_asset] = AssetData(_min, _max, 0, _maxSlippageRatio); } function removeAsset(address _asset) external onlyGovernance { for (uint i = 0; i < assets.length; i++) { if (_asset != assets[i]) { continue; } delete assetData[_asset]; assets[i] = assets[assets.length - 1]; assets.pop(); return; } revert("Pool: asset not found"); } function setAssetDetails( address _asset, uint112 _min, uint112 _max, uint _maxSlippageRatio ) external onlyGovernance { require(_min <= _max, "Pool: min > max"); require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1"); for (uint i = 0; i < assets.length; i++) { if (_asset != assets[i]) { continue; } assetData[_asset].minAmount = _min; assetData[_asset].maxAmount = _max; assetData[_asset].maxSlippageRatio = _maxSlippageRatio; return; } revert("Pool: asset not found"); } /* claim related functions */ /** * @dev Execute the payout in case a claim is accepted * @param asset token address or 0xEee...EEeE for ether * @param payoutAddress send funds to this address * @param amount amount to send */ function sendClaimPayout ( address asset, address payable payoutAddress, uint amount ) external onlyInternal nonReentrant returns (bool success) { bool ok; if (asset == ETH) { // solhint-disable-next-line avoid-low-level-calls (ok, /* data */) = payoutAddress.call.value(amount)(""); } else { ok = _safeTokenTransfer(asset, payoutAddress, amount); } if (ok) { emit Payout(payoutAddress, asset, amount); } return ok; } /** * @dev safeTransfer implementation that does not revert * @param tokenAddress ERC20 address * @param to destination * @param value amount to send * @return success true if the transfer was successfull */ function _safeTokenTransfer ( address tokenAddress, address to, uint256 value ) internal returns (bool) { // token address is not a contract if (!tokenAddress.isContract()) { return false; } IERC20 token = IERC20(tokenAddress); bytes memory data = abi.encodeWithSelector(token.transfer.selector, to, value); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = tokenAddress.call(data); // low-level call failed/reverted if (!success) { return false; } // tokens that don't have return data if (returndata.length == 0) { return true; } // tokens that have return data will return a bool return abi.decode(returndata, (bool)); } /* pool lifecycle functions */ function transferAsset( address asset, address payable destination, uint amount ) external onlyGovernance nonReentrant { require(assetData[asset].maxAmount == 0, "Pool: max not zero"); require(destination != address(0), "Pool: dest zero"); IERC20 token = IERC20(asset); uint balance = token.balanceOf(address(this)); uint transferableAmount = amount > balance ? balance : amount; token.safeTransfer(destination, transferableAmount); } function upgradeCapitalPool(address payable newPoolAddress) external onlyMaster nonReentrant { // transfer ether uint ethBalance = address(this).balance; (bool ok, /* data */) = newPoolAddress.call.value(ethBalance)(""); require(ok, "Pool: transfer failed"); // transfer assets for (uint i = 0; i < assets.length; i++) { IERC20 token = IERC20(assets[i]); uint tokenBalance = token.balanceOf(address(this)); token.safeTransfer(newPoolAddress, tokenBalance); } } /** * @dev Update dependent contract address * @dev Implements MasterAware interface function */ function changeDependentContractAddress() public { nxmToken = NXMToken(master.tokenAddress()); tokenController = TokenController(master.getLatestAddress("TC")); quotation = Quotation(master.getLatestAddress("QT")); mcr = MCR(master.getLatestAddress("MC")); } /* cover purchase functions */ /// @dev Enables user to purchase cover with funding in ETH. /// @param smartCAdd Smart Contract Address function makeCoverBegin( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public payable onlyMember whenNotPaused { require(coverCurr == "ETH", "Pool: Unexpected asset type"); require(msg.value == coverDetails[1], "Pool: ETH amount does not match premium"); quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Enables user to purchase cover via currency asset eg DAI */ function makeCoverUsingCA( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyMember whenNotPaused { require(coverCurr != "ETH", "Pool: Unexpected asset type"); quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } function transferAssetFrom (address asset, address from, uint amount) public onlyInternal whenNotPaused { IERC20 token = IERC20(asset); token.safeTransferFrom(from, address(this), amount); } function transferAssetToSwapOperator (address asset, uint amount) public onlySwapOperator nonReentrant whenNotPaused { if (asset == ETH) { (bool ok, /* data */) = swapOperator.call.value(amount)(""); require(ok, "Pool: Eth transfer failed"); return; } IERC20 token = IERC20(asset); token.safeTransfer(swapOperator, amount); } function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) public onlySwapOperator whenNotPaused { assetData[asset].lastSwapTime = lastSwapTime; } /* token sale functions */ /** * @dev (DEPRECATED, use sellTokens function instead) Allows selling of NXM for ether. * Seller first needs to give this contract allowance to * transfer/burn tokens in the NXMToken contract * @param _amount Amount of NXM to sell * @return success returns true on successfull sale */ function sellNXMTokens(uint _amount) public onlyMember whenNotPaused returns (bool success) { sellNXM(_amount, 0); return true; } /** * @dev (DEPRECATED, use calculateNXMForEth function instead) Returns the amount of wei a seller will get for selling NXM * @param amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function getWei(uint amount) external view returns (uint weiToPay) { return getEthForNXM(amount); } /** * @dev Buys NXM tokens with ETH. * @param minTokensOut Minimum amount of tokens to be bought. Revert if boughtTokens falls below this number. * @return boughtTokens number of bought tokens. */ function buyNXM(uint minTokensOut) public payable onlyMember whenNotPaused { uint ethIn = msg.value; require(ethIn > 0, "Pool: ethIn > 0"); uint totalAssetValue = getPoolValueInEth().sub(ethIn); uint mcrEth = mcr.getMCR(); uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth); require(mcrRatio <= MAX_MCR_RATIO, "Pool: Cannot purchase if MCR% > 400%"); uint tokensOut = calculateNXMForEth(ethIn, totalAssetValue, mcrEth); require(tokensOut >= minTokensOut, "Pool: tokensOut is less than minTokensOut"); tokenController.mint(msg.sender, tokensOut); // evaluate the new MCR for the current asset value including the ETH paid in mcr.updateMCRInternal(totalAssetValue.add(ethIn), false); emit NXMBought(msg.sender, ethIn, tokensOut); } /** * @dev Sell NXM tokens and receive ETH. * @param tokenAmount Amount of tokens to sell. * @param minEthOut Minimum amount of ETH to be received. Revert if ethOut falls below this number. * @return ethOut amount of ETH received in exchange for the tokens. */ function sellNXM(uint tokenAmount, uint minEthOut) public onlyMember nonReentrant whenNotPaused { require(nxmToken.balanceOf(msg.sender) >= tokenAmount, "Pool: Not enough balance"); require(nxmToken.isLockedForMV(msg.sender) <= now, "Pool: NXM tokens are locked for voting"); uint currentTotalAssetValue = getPoolValueInEth(); uint mcrEth = mcr.getMCR(); uint ethOut = calculateEthForNXM(tokenAmount, currentTotalAssetValue, mcrEth); require(currentTotalAssetValue.sub(ethOut) >= mcrEth, "Pool: MCR% cannot fall below 100%"); require(ethOut >= minEthOut, "Pool: ethOut < minEthOut"); tokenController.burnFrom(msg.sender, tokenAmount); (bool ok, /* data */) = msg.sender.call.value(ethOut)(""); require(ok, "Pool: Sell transfer failed"); // evaluate the new MCR for the current asset value excluding the paid out ETH mcr.updateMCRInternal(currentTotalAssetValue.sub(ethOut), false); emit NXMSold(msg.sender, tokenAmount, ethOut); } /** * @dev Get value in tokens for an ethAmount purchase. * @param ethAmount amount of ETH used for buying. * @return tokenValue tokens obtained by buying worth of ethAmount */ function getNXMForEth( uint ethAmount ) public view returns (uint) { uint totalAssetValue = getPoolValueInEth(); uint mcrEth = mcr.getMCR(); return calculateNXMForEth(ethAmount, totalAssetValue, mcrEth); } function calculateNXMForEth( uint ethAmount, uint currentTotalAssetValue, uint mcrEth ) public pure returns (uint) { require( ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS), "Pool: Purchases worth higher than 5% of MCReth are not allowed" ); /* The price formula is: P(V) = A + MCReth / C * MCR% ^ 4 where MCR% = V / MCReth P(V) = A + 1 / (C * MCReth ^ 3) * V ^ 4 To compute the number of tokens issued we can integrate with respect to V the following: ΔT = ΔV / P(V) which assumes that for an infinitesimally small change in locked value V price is constant and we get an infinitesimally change in token supply ΔT. This is not computable on-chain, below we use an approximation that works well assuming * MCR% stays within [100%, 400%] * ethAmount <= 5% * MCReth Use a simplified formula excluding the constant A price offset to compute the amount of tokens to be minted. AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4 AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4 For a very small variation in tokens ΔT, we have, ΔT = ΔV / P(V), to get total T we integrate with respect to V. adjustedTokenAmount = ∫ (dV / AdjustedP(V)) from V0 (currentTotalAssetValue) to V1 (nextTotalAssetValue) adjustedTokenAmount = ∫ ((C * MCReth ^ 3) / V ^ 4 * dV) from V0 to V1 Evaluating the above using the antiderivative of the function we get: adjustedTokenAmount = - MCReth ^ 3 * C / (3 * V1 ^3) + MCReth * C /(3 * V0 ^ 3) */ if (currentTotalAssetValue == 0 || mcrEth.div(currentTotalAssetValue) > 1e12) { /* If the currentTotalAssetValue = 0, adjustedTokenPrice approaches 0. Therefore we can assume the price is A. If currentTotalAssetValue is far smaller than mcrEth, MCR% approaches 0, let the price be A (baseline price). This avoids overflow in the calculateIntegralAtPoint computation. This approximation is safe from arbitrage since at MCR% < 100% no sells are possible. */ uint tokenPrice = CONSTANT_A; return ethAmount.mul(1e18).div(tokenPrice); } // MCReth * C /(3 * V0 ^ 3) uint point0 = calculateIntegralAtPoint(currentTotalAssetValue, mcrEth); // MCReth * C / (3 * V1 ^3) uint nextTotalAssetValue = currentTotalAssetValue.add(ethAmount); uint point1 = calculateIntegralAtPoint(nextTotalAssetValue, mcrEth); uint adjustedTokenAmount = point0.sub(point1); /* Compute a preliminary adjustedTokenPrice for the minted tokens based on the adjustedTokenAmount above, and to that add the A constant (the price offset previously removed in the adjusted Price formula) to obtain the finalPrice and ultimately the tokenValue based on the finalPrice. adjustedPrice = ethAmount / adjustedTokenAmount finalPrice = adjustedPrice + A tokenValue = ethAmount / finalPrice */ // ethAmount is multiplied by 1e18 to cancel out the multiplication factor of 1e18 of the adjustedTokenAmount uint adjustedTokenPrice = ethAmount.mul(1e18).div(adjustedTokenAmount); uint tokenPrice = adjustedTokenPrice.add(CONSTANT_A); return ethAmount.mul(1e18).div(tokenPrice); } /** * @dev integral(V) = MCReth ^ 3 * C / (3 * V ^ 3) * 1e18 * computation result is multiplied by 1e18 to allow for a precision of 18 decimals. * NOTE: omits the minus sign of the correct integral to use a uint result type for simplicity * WARNING: this low-level function should be called from a contract which checks that * mcrEth / assetValue < 1e17 (no overflow) and assetValue != 0 */ function calculateIntegralAtPoint( uint assetValue, uint mcrEth ) internal pure returns (uint) { return CONSTANT_C .mul(1e18) .div(3) .mul(mcrEth).div(assetValue) .mul(mcrEth).div(assetValue) .mul(mcrEth).div(assetValue); } function getEthForNXM(uint nxmAmount) public view returns (uint ethAmount) { uint currentTotalAssetValue = getPoolValueInEth(); uint mcrEth = mcr.getMCR(); return calculateEthForNXM(nxmAmount, currentTotalAssetValue, mcrEth); } /** * @dev Computes token sell value for a tokenAmount in ETH with a sell spread of 2.5%. * for values in ETH of the sale <= 1% * MCReth the sell spread is very close to the exact value of 2.5%. * for values higher than that sell spread may exceed 2.5% * (The higher amount being sold at any given time the higher the spread) */ function calculateEthForNXM( uint nxmAmount, uint currentTotalAssetValue, uint mcrEth ) public pure returns (uint) { // Step 1. Calculate spot price at current values and amount of ETH if tokens are sold at that price uint spotPrice0 = calculateTokenSpotPrice(currentTotalAssetValue, mcrEth); uint spotEthAmount = nxmAmount.mul(spotPrice0).div(1e18); // Step 2. Calculate spot price using V = currentTotalAssetValue - spotEthAmount from step 1 uint totalValuePostSpotPriceSell = currentTotalAssetValue.sub(spotEthAmount); uint spotPrice1 = calculateTokenSpotPrice(totalValuePostSpotPriceSell, mcrEth); // Step 3. Min [average[Price(0), Price(1)] x ( 1 - Sell Spread), Price(1) ] // Sell Spread = 2.5% uint averagePriceWithSpread = spotPrice0.add(spotPrice1).div(2).mul(975).div(1000); uint finalPrice = averagePriceWithSpread < spotPrice1 ? averagePriceWithSpread : spotPrice1; uint ethAmount = finalPrice.mul(nxmAmount).div(1e18); require( ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS), "Pool: Sales worth more than 5% of MCReth are not allowed" ); return ethAmount; } function calculateMCRRatio(uint totalAssetValue, uint mcrEth) public pure returns (uint) { return totalAssetValue.mul(10 ** MCR_RATIO_DECIMALS).div(mcrEth); } /** * @dev Calculates token price in ETH 1 NXM token. TokenPrice = A + (MCReth / C) * MCR%^4 */ function calculateTokenSpotPrice(uint totalAssetValue, uint mcrEth) public pure returns (uint tokenPrice) { uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth); uint precisionDecimals = 10 ** TOKEN_EXPONENT.mul(MCR_RATIO_DECIMALS); return mcrEth .mul(mcrRatio ** TOKEN_EXPONENT) .div(CONSTANT_C) .div(precisionDecimals) .add(CONSTANT_A); } /** * @dev Returns the NXM price in a given asset * @param asset Asset name. */ function getTokenPrice(address asset) public view returns (uint tokenPrice) { uint totalAssetValue = getPoolValueInEth(); uint mcrEth = mcr.getMCR(); uint tokenSpotPriceEth = calculateTokenSpotPrice(totalAssetValue, mcrEth); return priceFeedOracle.getAssetForEth(asset, tokenSpotPriceEth); } function getMCRRatio() public view returns (uint) { uint totalAssetValue = getPoolValueInEth(); uint mcrEth = mcr.getMCR(); return calculateMCRRatio(totalAssetValue, mcrEth); } function updateUintParameters(bytes8 code, uint value) external onlyGovernance { if (code == "MIN_ETH") { minPoolEth = value; return; } revert("Pool: unknown parameter"); } function updateAddressParameters(bytes8 code, address value) external onlyGovernance { if (code == "SWP_OP") { swapOperator = value; return; } if (code == "PRC_FEED") { priceFeedOracle = PriceFeedOracle(value); return; } revert("Pool: unknown parameter"); } } 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; } } 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); } pragma solidity ^0.5.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 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"); } } } pragma solidity ^0.5.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } 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"); } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "./INXMMaster.sol"; contract MasterAware { INXMMaster public master; modifier onlyMember { require(master.isMember(msg.sender), "Caller is not a member"); _; } modifier onlyInternal { require(master.isInternal(msg.sender), "Caller is not an internal contract"); _; } modifier onlyMaster { if (address(master) != address(0)) { require(address(master) == msg.sender, "Not master"); } _; } modifier onlyGovernance { require( master.checkIsAuthToGoverned(msg.sender), "Caller is not authorized to govern" ); _; } modifier whenPaused { require(master.isPause(), "System is not paused"); _; } modifier whenNotPaused { require(!master.isPause(), "System is paused"); _; } function changeDependentContractAddress() external; function changeMasterAddress(address masterAddress) public onlyMaster { master = INXMMaster(masterAddress); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IPool { function transferAssetToSwapOperator(address asset, uint amount) external; function getAssetDetails(address _asset) external view returns ( uint112 min, uint112 max, uint32 lastAssetSwapTime, uint maxSlippageRatio ); function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) external; function minPoolEth() external returns (uint); } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../../abstract/MasterAware.sol"; import "../capital/Pool.sol"; import "../claims/ClaimsReward.sol"; import "../claims/Incidents.sol"; import "../token/TokenController.sol"; import "../token/TokenData.sol"; import "./QuotationData.sol"; contract Quotation is MasterAware, ReentrancyGuard { using SafeMath for uint; ClaimsReward public cr; Pool public pool; IPooledStaking public pooledStaking; QuotationData public qd; TokenController public tc; TokenData public td; Incidents public incidents; /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { cr = ClaimsReward(master.getLatestAddress("CR")); pool = Pool(master.getLatestAddress("P1")); pooledStaking = IPooledStaking(master.getLatestAddress("PS")); qd = QuotationData(master.getLatestAddress("QD")); tc = TokenController(master.getLatestAddress("TC")); td = TokenData(master.getLatestAddress("TD")); incidents = Incidents(master.getLatestAddress("IC")); } // solhint-disable-next-line no-empty-blocks function sendEther() public payable {} /** * @dev Expires a cover after a set period of time and changes the status of the cover * @dev Reduces the total and contract sum assured * @param coverId Cover Id. */ function expireCover(uint coverId) external { uint expirationDate = qd.getValidityOfCover(coverId); require(expirationDate < now, "Quotation: cover is not due to expire"); uint coverStatus = qd.getCoverStatusNo(coverId); require(coverStatus != uint(QuotationData.CoverStatus.CoverExpired), "Quotation: cover already expired"); (/* claim count */, bool hasOpenClaim, /* accepted */) = tc.coverInfo(coverId); require(!hasOpenClaim, "Quotation: cover has an open claim"); if (coverStatus != uint(QuotationData.CoverStatus.ClaimAccepted)) { (,, address contractAddress, bytes4 currency, uint amount,) = qd.getCoverDetailsByCoverID1(coverId); qd.subFromTotalSumAssured(currency, amount); qd.subFromTotalSumAssuredSC(contractAddress, currency, amount); } qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.CoverExpired)); } function withdrawCoverNote(address coverOwner, uint[] calldata coverIds, uint[] calldata reasonIndexes) external { uint gracePeriod = tc.claimSubmissionGracePeriod(); for (uint i = 0; i < coverIds.length; i++) { uint expirationDate = qd.getValidityOfCover(coverIds[i]); require(expirationDate.add(gracePeriod) < now, "Quotation: cannot withdraw before grace period expiration"); } tc.withdrawCoverNote(coverOwner, coverIds, reasonIndexes); } function getWithdrawableCoverNoteCoverIds( address coverOwner ) public view returns ( uint[] memory expiredCoverIds, bytes32[] memory lockReasons ) { uint[] memory coverIds = qd.getAllCoversOfUser(coverOwner); uint[] memory expiredIdsQueue = new uint[](coverIds.length); uint gracePeriod = tc.claimSubmissionGracePeriod(); uint expiredQueueLength = 0; for (uint i = 0; i < coverIds.length; i++) { uint coverExpirationDate = qd.getValidityOfCover(coverIds[i]); uint gracePeriodExpirationDate = coverExpirationDate.add(gracePeriod); (/* claimCount */, bool hasOpenClaim, /* hasAcceptedClaim */) = tc.coverInfo(coverIds[i]); if (!hasOpenClaim && gracePeriodExpirationDate < now) { expiredIdsQueue[expiredQueueLength] = coverIds[i]; expiredQueueLength++; } } expiredCoverIds = new uint[](expiredQueueLength); lockReasons = new bytes32[](expiredQueueLength); for (uint i = 0; i < expiredQueueLength; i++) { expiredCoverIds[i] = expiredIdsQueue[i]; lockReasons[i] = keccak256(abi.encodePacked("CN", coverOwner, expiredIdsQueue[i])); } } function getWithdrawableCoverNotesAmount(address coverOwner) external view returns (uint) { uint withdrawableAmount; bytes32[] memory lockReasons; (/*expiredCoverIds*/, lockReasons) = getWithdrawableCoverNoteCoverIds(coverOwner); for (uint i = 0; i < lockReasons.length; i++) { uint coverNoteAmount = tc.tokensLocked(coverOwner, lockReasons[i]); withdrawableAmount = withdrawableAmount.add(coverNoteAmount); } return withdrawableAmount; } /** * @dev Makes Cover funded via NXM tokens. * @param smartCAdd Smart Contract Address */ function makeCoverUsingNXMTokens( uint[] calldata coverDetails, uint16 coverPeriod, bytes4 coverCurr, address smartCAdd, uint8 _v, bytes32 _r, bytes32 _s ) external onlyMember whenNotPaused { tc.burnFrom(msg.sender, coverDetails[2]); // needs allowance _verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s, true); } /** * @dev Verifies cover details signed off chain. * @param from address of funder. * @param scAddress Smart Contract Address */ function verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyInternal { _verifyCoverDetails( from, scAddress, coverCurr, coverDetails, coverPeriod, _v, _r, _s, false ); } /** * @dev Verifies signature. * @param coverDetails details related to cover. * @param coverPeriod validity of cover. * @param contractAddress smart contract address. * @param _v argument from vrs hash. * @param _r argument from vrs hash. * @param _s argument from vrs hash. */ function verifySignature( uint[] memory coverDetails, uint16 coverPeriod, bytes4 currency, address contractAddress, uint8 _v, bytes32 _r, bytes32 _s ) public view returns (bool) { require(contractAddress != address(0)); bytes32 hash = getOrderHash(coverDetails, coverPeriod, currency, contractAddress); return isValidSignature(hash, _v, _r, _s); } /** * @dev Gets order hash for given cover details. * @param coverDetails details realted to cover. * @param coverPeriod validity of cover. * @param contractAddress smart contract address. */ function getOrderHash( uint[] memory coverDetails, uint16 coverPeriod, bytes4 currency, address contractAddress ) public view returns (bytes32) { return keccak256( abi.encodePacked( coverDetails[0], currency, coverPeriod, contractAddress, coverDetails[1], coverDetails[2], coverDetails[3], coverDetails[4], address(this) ) ); } /** * @dev Verifies signature. * @param hash order hash * @param v argument from vrs hash. * @param r argument from vrs hash. * @param s argument from vrs hash. */ function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns (bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == qd.getAuthQuoteEngine()); } /** * @dev Creates cover of the quotation, changes the status of the quotation , * updates the total sum assured and locks the tokens of the cover against a quote. * @param from Quote member Ethereum address. */ function _makeCover(//solhint-disable-line address payable from, address contractAddress, bytes4 coverCurrency, uint[] memory coverDetails, uint16 coverPeriod ) internal { address underlyingToken = incidents.underlyingToken(contractAddress); if (underlyingToken != address(0)) { address coverAsset = cr.getCurrencyAssetAddress(coverCurrency); require(coverAsset == underlyingToken, "Quotation: Unsupported cover asset for this product"); } uint cid = qd.getCoverLength(); qd.addCover( coverPeriod, coverDetails[0], from, coverCurrency, contractAddress, coverDetails[1], coverDetails[2] ); uint coverNoteAmount = coverDetails[2].mul(qd.tokensRetained()).div(100); if (underlyingToken == address(0)) { uint gracePeriod = tc.claimSubmissionGracePeriod(); uint claimSubmissionPeriod = uint(coverPeriod).mul(1 days).add(gracePeriod); bytes32 reason = keccak256(abi.encodePacked("CN", from, cid)); // mint and lock cover note td.setDepositCNAmount(cid, coverNoteAmount); tc.mintCoverNote(from, reason, coverNoteAmount, claimSubmissionPeriod); } else { // minted directly to member's wallet tc.mint(from, coverNoteAmount); } qd.addInTotalSumAssured(coverCurrency, coverDetails[0]); qd.addInTotalSumAssuredSC(contractAddress, coverCurrency, coverDetails[0]); uint coverPremiumInNXM = coverDetails[2]; uint stakersRewardPercentage = td.stakerCommissionPer(); uint rewardValue = coverPremiumInNXM.mul(stakersRewardPercentage).div(100); pooledStaking.accumulateReward(contractAddress, rewardValue); } /** * @dev Makes a cover. * @param from address of funder. * @param scAddress Smart Contract Address */ function _verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s, bool isNXM ) internal { require(coverDetails[3] > now, "Quotation: Quote has expired"); require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds"); require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used"); qd.setTimestampRepeated(coverDetails[4]); address asset = cr.getCurrencyAssetAddress(coverCurr); if (coverCurr != "ETH" && !isNXM) { pool.transferAssetFrom(asset, from, coverDetails[1]); } require(verifySignature(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s), "Quotation: signature mismatch"); _makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod); } function createCover( address payable from, address scAddress, bytes4 currency, uint[] calldata coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) external onlyInternal { require(coverDetails[3] > now, "Quotation: Quote has expired"); require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds"); require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used"); qd.setTimestampRepeated(coverDetails[4]); require(verifySignature(coverDetails, coverPeriod, currency, scAddress, _v, _r, _s), "Quotation: signature mismatch"); _makeCover(from, scAddress, currency, coverDetails, coverPeriod); } // referenced in master, keeping for now // solhint-disable-next-line no-empty-blocks function transferAssetsToNewContract(address) external pure {} function freeUpHeldCovers() external nonReentrant { IERC20 dai = IERC20(cr.getCurrencyAssetAddress("DAI")); uint membershipFee = td.joiningFee(); uint lastCoverId = 106; for (uint id = 1; id <= lastCoverId; id++) { if (qd.holdedCoverIDStatus(id) != uint(QuotationData.HCIDStatus.kycPending)) { continue; } (/*id*/, /*sc*/, bytes4 currency, /*period*/) = qd.getHoldedCoverDetailsByID1(id); (/*id*/, address payable userAddress, uint[] memory coverDetails) = qd.getHoldedCoverDetailsByID2(id); uint refundedETH = membershipFee; uint coverPremium = coverDetails[1]; if (qd.refundEligible(userAddress)) { qd.setRefundEligible(userAddress, false); } qd.setHoldedCoverIDStatus(id, uint(QuotationData.HCIDStatus.kycFailedOrRefunded)); if (currency == "ETH") { refundedETH = refundedETH.add(coverPremium); } else { require(dai.transfer(userAddress, coverPremium), "Quotation: DAI refund transfer failed"); } userAddress.transfer(refundedETH); } } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; interface Aggregator { function latestAnswer() external view returns (int); } contract PriceFeedOracle { using SafeMath for uint; mapping(address => address) public aggregators; address public daiAddress; address public stETH; address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; constructor ( address _daiAggregator, address _daiAddress, address _stEthAddress ) public { aggregators[_daiAddress] = _daiAggregator; daiAddress = _daiAddress; stETH = _stEthAddress; } /** * @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset * @param asset quoted currency * @return price in ether */ function getAssetToEthRate(address asset) public view returns (uint) { if (asset == ETH || asset == stETH) { return 1 ether; } address aggregatorAddress = aggregators[asset]; if (aggregatorAddress == address(0)) { revert("PriceFeedOracle: Oracle asset not found"); } int rate = Aggregator(aggregatorAddress).latestAnswer(); require(rate > 0, "PriceFeedOracle: Rate must be > 0"); return uint(rate); } /** * @dev Returns the amount of currency that is equivalent to ethIn amount of ether. * @param asset quoted Supported values: ["DAI", "ETH"] * @param ethIn amount of ether to be converted to the currency * @return price in ether */ function getAssetForEth(address asset, uint ethIn) external view returns (uint) { if (asset == daiAddress) { return ethIn.mul(1e18).div(getAssetToEthRate(daiAddress)); } if (asset == ETH || asset == stETH) { return ethIn; } revert("PriceFeedOracle: Unknown asset"); } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "./external/OZIERC20.sol"; import "./external/OZSafeMath.sol"; contract NXMToken is OZIERC20 { using OZSafeMath for uint256; event WhiteListed(address indexed member); event BlackListed(address indexed member); mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowed; mapping(address => bool) public whiteListed; mapping(address => uint) public isLockedForMV; uint256 private _totalSupply; string public name = "NXM"; string public symbol = "NXM"; uint8 public decimals = 18; address public operator; modifier canTransfer(address _to) { require(whiteListed[_to]); _; } modifier onlyOperator() { if (operator != address(0)) require(msg.sender == operator); _; } constructor(address _founderAddress, uint _initialSupply) public { _mint(_founderAddress, _initialSupply); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @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) public view returns (uint256) { return _balances[owner]; } /** * @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 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @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 increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _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 decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Adds a user to whitelist * @param _member address to add to whitelist */ function addToWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = true; emit WhiteListed(_member); return true; } /** * @dev removes a user from whitelist * @param _member address to remove from whitelist */ function removeFromWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = false; emit BlackListed(_member); return true; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public returns (bool) { _burn(msg.sender, amount); return true; } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public returns (bool) { _burnFrom(from, value); return true; } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator { _mint(account, amount); } /** * @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 canTransfer(to) returns (bool) { require(isLockedForMV[msg.sender] < now); // if not voted under governance require(value <= _balances[msg.sender]); _transfer(to, value); return true; } /** * @dev Transfer tokens to the operator from the specified address * @param from The address to transfer from. * @param value The amount to be transferred. */ function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) { require(value <= _balances[from]); _transferFrom(from, operator, 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 canTransfer(to) returns (bool) { require(isLockedForMV[from] < now); // if not voted under governance require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyOperator { if (_days.add(now) > isLockedForMV[_of]) isLockedForMV[_of] = _days.add(now); } /** * @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) internal { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } /** * @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 ) internal { _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); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ 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); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/Iupgradable.sol"; import "../../interfaces/IPooledStaking.sol"; import "../claims/ClaimsData.sol"; import "./NXMToken.sol"; import "./external/LockHandler.sol"; contract TokenController is LockHandler, Iupgradable { using SafeMath for uint256; struct CoverInfo { uint16 claimCount; bool hasOpenClaim; bool hasAcceptedClaim; // note: still 224 bits available here, can be used later } NXMToken public token; IPooledStaking public pooledStaking; uint public minCALockTime; uint public claimSubmissionGracePeriod; // coverId => CoverInfo mapping(uint => CoverInfo) public coverInfo; event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity); event Unlocked(address indexed _of, bytes32 indexed _reason, uint256 _amount); event Burned(address indexed member, bytes32 lockedUnder, uint256 amount); modifier onlyGovernance { require(msg.sender == ms.getLatestAddress("GV"), "TokenController: Caller is not governance"); _; } /** * @dev Just for interface */ function changeDependentContractAddress() public { token = NXMToken(ms.tokenAddress()); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } function markCoverClaimOpen(uint coverId) external onlyInternal { CoverInfo storage info = coverInfo[coverId]; uint16 claimCount; bool hasOpenClaim; bool hasAcceptedClaim; // reads all of them using a single SLOAD (claimCount, hasOpenClaim, hasAcceptedClaim) = (info.claimCount, info.hasOpenClaim, info.hasAcceptedClaim); // no safemath for uint16 but should be safe from // overflows as there're max 2 claims per cover claimCount = claimCount + 1; require(claimCount <= 2, "TokenController: Max claim count exceeded"); require(hasOpenClaim == false, "TokenController: Cover already has an open claim"); require(hasAcceptedClaim == false, "TokenController: Cover already has accepted claims"); // should use a single SSTORE for both (info.claimCount, info.hasOpenClaim) = (claimCount, true); } /** * @param coverId cover id (careful, not claim id!) * @param isAccepted claim verdict */ function markCoverClaimClosed(uint coverId, bool isAccepted) external onlyInternal { CoverInfo storage info = coverInfo[coverId]; require(info.hasOpenClaim == true, "TokenController: Cover claim is not marked as open"); // should use a single SSTORE for both (info.hasOpenClaim, info.hasAcceptedClaim) = (false, isAccepted); } /** * @dev to change the operator address * @param _newOperator is the new address of operator */ function changeOperator(address _newOperator) public onlyInternal { token.changeOperator(_newOperator); } /** * @dev Proxies token transfer through this contract to allow staking when members are locked for voting * @param _from Source address * @param _to Destination address * @param _value Amount to transfer */ function operatorTransfer(address _from, address _to, uint _value) external onlyInternal returns (bool) { require(msg.sender == address(pooledStaking), "TokenController: Call is only allowed from PooledStaking address"); token.operatorTransfer(_from, _value); token.transfer(_to, _value); return true; } /** * @dev Locks a specified amount of tokens, * for CLA reason and for a specified time * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lockClaimAssessmentTokens(uint256 _amount, uint256 _time) external checkPause { require(minCALockTime <= _time, "TokenController: Must lock for minimum time"); require(_time <= 180 days, "TokenController: Tokens can be locked for 180 days maximum"); // If tokens are already locked, then functions extendLock or // increaseClaimAssessmentLock should be used to make any changes _lock(msg.sender, "CLA", _amount, _time); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address whose tokens are to be locked */ function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) public onlyInternal returns (bool) { // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(_of, _reason, _amount, _time); return true; } /** * @dev Mints and locks a specified amount of tokens against an address, * for a CN reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function mintCoverNote( address _of, bytes32 _reason, uint256 _amount, uint256 _time ) external onlyInternal { require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked"); require(_amount != 0, "TokenController: Amount shouldn't be zero"); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } token.mint(address(this), _amount); uint256 lockedUntil = now.add(_time); locked[_of][_reason] = LockToken(_amount, lockedUntil, false); emit Locked(_of, _reason, _amount, lockedUntil); } /** * @dev Extends lock for reason CLA for a specified time * @param _time Lock extension time in seconds */ function extendClaimAssessmentLock(uint256 _time) external checkPause { uint256 validity = getLockedTokensValidity(msg.sender, "CLA"); require(validity.add(_time).sub(block.timestamp) <= 180 days, "TokenController: Tokens can be locked for 180 days maximum"); _extendLock(msg.sender, "CLA", _time); } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLockOf(address _of, bytes32 _reason, uint256 _time) public onlyInternal returns (bool) { _extendLock(_of, _reason, _time); return true; } /** * @dev Increase number of tokens locked for a CLA reason * @param _amount Number of tokens to be increased */ function increaseClaimAssessmentLock(uint256 _amount) external checkPause { require(_tokensLocked(msg.sender, "CLA") > 0, "TokenController: No tokens locked"); token.operatorTransfer(msg.sender, _amount); locked[msg.sender]["CLA"].amount = locked[msg.sender]["CLA"].amount.add(_amount); emit Locked(msg.sender, "CLA", _amount, locked[msg.sender]["CLA"].validity); } /** * @dev burns tokens of an address * @param _of is the address to burn tokens of * @param amount is the amount to burn * @return the boolean status of the burning process */ function burnFrom(address _of, uint amount) public onlyInternal returns (bool) { return token.burnFrom(_of, amount); } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _burnLockedTokens(_of, _reason, _amount); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal { _reduceLock(_of, _reason, _time); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _releaseLockedTokens(_of, _reason, _amount); } /** * @dev Adds an address to whitelist maintained in the contract * @param _member address to add to whitelist */ function addToWhitelist(address _member) public onlyInternal { token.addToWhiteList(_member); } /** * @dev Removes an address from the whitelist in the token * @param _member address to remove */ function removeFromWhitelist(address _member) public onlyInternal { token.removeFromWhiteList(_member); } /** * @dev Mints new token for an address * @param _member address to reward the minted tokens * @param _amount number of tokens to mint */ function mint(address _member, uint _amount) public onlyInternal { token.mint(_member, _amount); } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyInternal { token.lockForMemberVote(_of, _days); } /** * @dev Unlocks the withdrawable tokens against CLA of a specified address * @param _of Address of user, claiming back withdrawable tokens against CLA */ function withdrawClaimAssessmentTokens(address _of) external checkPause { uint256 withdrawableTokens = _tokensUnlockable(_of, "CLA"); if (withdrawableTokens > 0) { locked[_of]["CLA"].claimed = true; emit Unlocked(_of, "CLA", withdrawableTokens); token.transfer(_of, withdrawableTokens); } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param value value to set */ function updateUintParameters(bytes8 code, uint value) external onlyGovernance { if (code == "MNCLT") { minCALockTime = value; return; } if (code == "GRACEPER") { claimSubmissionGracePeriod = value; return; } revert("TokenController: invalid param code"); } function getLockReasons(address _of) external view returns (bytes32[] memory reasons) { return lockReason[_of]; } /** * @dev Gets the validity of locked tokens of a specified address * @param _of The address to query the validity * @param reason reason for which tokens were locked */ function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) { validity = locked[_of][reason].validity; } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensLocked(_of, _reason); } /** * @dev Returns tokens locked and validity for a specified address and reason * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLockedWithValidity(address _of, bytes32 _reason) public view returns (uint256 amount, uint256 validity) { bool claimed = locked[_of][_reason].claimed; amount = locked[_of][_reason].amount; validity = locked[_of][_reason].validity; if (claimed) { amount = 0; } } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensUnlockable(_of, _reason); } function totalSupply() public view returns (uint256) { return token.totalSupply(); } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { return _tokensLockedAtTime(_of, _reason, _time); } /** * @dev Returns the total amount of tokens held by an address: * transferable + locked + staked for pooled staking - pending burns. * Used by Claims and Governance in member voting to calculate the user's vote weight. * * @param _of The address to query the total balance of * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount) { amount = token.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } uint stakerReward = pooledStaking.stakerReward(_of); uint stakerDeposit = pooledStaking.stakerDeposit(_of); amount = amount.add(stakerDeposit).add(stakerReward); } /** * @dev Returns the total amount of locked and staked tokens. * Used by MemberRoles to check eligibility for withdraw / switch membership. * Includes tokens locked for claim assessment, tokens staked for risk assessment, and locked cover notes * Does not take into account pending burns. * @param _of member whose locked tokens are to be calculate */ function totalLockedBalance(address _of) public view returns (uint256 amount) { for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } amount = amount.add(pooledStaking.stakerDeposit(_of)); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal { require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked"); require(_amount != 0, "TokenController: Amount shouldn't be zero"); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } token.operatorTransfer(_of, _amount); uint256 validUntil = now.add(_time); locked[_of][_reason] = LockToken(_amount, validUntil, false); emit Locked(_of, _reason, _amount, validUntil); } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function _tokensLocked(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (!locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) internal view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) { amount = locked[_of][_reason].amount; } } /** * @dev Extends lock for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function _extendLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked"); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked"); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount"); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); // lock reason removal is skipped here: needs to be done from offchain token.burn(_amount); emit Burned(_of, _reason, _amount); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount"); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); // lock reason removal is skipped here: needs to be done from offchain token.transfer(_of, _amount); emit Unlocked(_of, _reason, _amount); } function withdrawCoverNote( address _of, uint[] calldata _coverIds, uint[] calldata _indexes ) external onlyInternal { uint reasonCount = lockReason[_of].length; uint lastReasonIndex = reasonCount.sub(1, "TokenController: No locked cover notes found"); uint totalAmount = 0; // The iteration is done from the last to first to prevent reason indexes from // changing due to the way we delete the items (copy last to current and pop last). // The provided indexes array must be ordered, otherwise reason index checks will fail. for (uint i = _coverIds.length; i > 0; i--) { bool hasOpenClaim = coverInfo[_coverIds[i - 1]].hasOpenClaim; require(hasOpenClaim == false, "TokenController: Cannot withdraw for cover with an open claim"); // note: cover owner is implicitly checked using the reason hash bytes32 _reason = keccak256(abi.encodePacked("CN", _of, _coverIds[i - 1])); uint _reasonIndex = _indexes[i - 1]; require(lockReason[_of][_reasonIndex] == _reason, "TokenController: Bad reason index"); uint amount = locked[_of][_reason].amount; totalAmount = totalAmount.add(amount); delete locked[_of][_reason]; if (lastReasonIndex != _reasonIndex) { lockReason[_of][_reasonIndex] = lockReason[_of][lastReasonIndex]; } lockReason[_of].pop(); emit Unlocked(_of, _reason, amount); if (lastReasonIndex > 0) { lastReasonIndex = lastReasonIndex.sub(1, "TokenController: Reason count mismatch"); } } token.transfer(_of, totalAmount); } function removeEmptyReason(address _of, bytes32 _reason, uint _index) external { _removeEmptyReason(_of, _reason, _index); } function removeMultipleEmptyReasons( address[] calldata _members, bytes32[] calldata _reasons, uint[] calldata _indexes ) external { require(_members.length == _reasons.length, "TokenController: members and reasons array lengths differ"); require(_reasons.length == _indexes.length, "TokenController: reasons and indexes array lengths differ"); for (uint i = _members.length; i > 0; i--) { uint idx = i - 1; _removeEmptyReason(_members[idx], _reasons[idx], _indexes[idx]); } } function _removeEmptyReason(address _of, bytes32 _reason, uint _index) internal { uint lastReasonIndex = lockReason[_of].length.sub(1, "TokenController: lockReason is empty"); require(lockReason[_of][_index] == _reason, "TokenController: bad reason index"); require(locked[_of][_reason].amount == 0, "TokenController: reason amount is not zero"); if (lastReasonIndex != _index) { lockReason[_of][_index] = lockReason[_of][lastReasonIndex]; } lockReason[_of].pop(); } function initialize() external { require(claimSubmissionGracePeriod == 0, "TokenController: Already initialized"); claimSubmissionGracePeriod = 120 days; migrate(); } function migrate() internal { ClaimsData cd = ClaimsData(ms.getLatestAddress("CD")); uint totalClaims = cd.actualClaimLength() - 1; // fix stuck claims 21 & 22 cd.changeFinalVerdict(20, -1); cd.setClaimStatus(20, 6); cd.changeFinalVerdict(21, -1); cd.setClaimStatus(21, 6); // reduce claim assessment lock period for members locked for more than 180 days // extracted using scripts/extract-ca-locked-more-than-180.js address payable[3] memory members = [ 0x4a9fA34da6d2378c8f3B9F6b83532B169beaEDFc, 0x6b5DCDA27b5c3d88e71867D6b10b35372208361F, 0x8B6D1e5b4db5B6f9aCcc659e2b9619B0Cd90D617 ]; for (uint i = 0; i < members.length; i++) { if (locked[members[i]]["CLA"].validity > now + 180 days) { locked[members[i]]["CLA"].validity = now + 180 days; } } for (uint i = 1; i <= totalClaims; i++) { (/*id*/, uint status) = cd.getClaimStatusNumber(i); (/*id*/, uint coverId) = cd.getClaimCoverId(i); int8 verdict = cd.getFinalVerdict(i); // SLOAD CoverInfo memory info = coverInfo[coverId]; info.claimCount = info.claimCount + 1; info.hasAcceptedClaim = (status == 14); info.hasOpenClaim = (verdict == 0); // SSTORE coverInfo[coverId] = info; } } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../abstract/MasterAware.sol"; import "../capital/Pool.sol"; import "../cover/QuotationData.sol"; import "../oracles/PriceFeedOracle.sol"; import "../token/NXMToken.sol"; import "../token/TokenData.sol"; import "./LegacyMCR.sol"; contract MCR is MasterAware { using SafeMath for uint; Pool public pool; QuotationData public qd; // sizeof(qd) + 96 = 160 + 96 = 256 (occupies entire slot) uint96 _unused; // the following values are expressed in basis points uint24 public mcrFloorIncrementThreshold = 13000; uint24 public maxMCRFloorIncrement = 100; uint24 public maxMCRIncrement = 500; uint24 public gearingFactor = 48000; // min update between MCR updates in seconds uint24 public minUpdateTime = 3600; uint112 public mcrFloor; uint112 public mcr; uint112 public desiredMCR; uint32 public lastUpdateTime; LegacyMCR public previousMCR; event MCRUpdated( uint mcr, uint desiredMCR, uint mcrFloor, uint mcrETHWithGear, uint totalSumAssured ); uint constant UINT24_MAX = ~uint24(0); uint constant MAX_MCR_ADJUSTMENT = 100; uint constant BASIS_PRECISION = 10000; constructor (address masterAddress) public { changeMasterAddress(masterAddress); if (masterAddress != address(0)) { previousMCR = LegacyMCR(master.getLatestAddress("MC")); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { qd = QuotationData(master.getLatestAddress("QD")); pool = Pool(master.getLatestAddress("P1")); initialize(); } function initialize() internal { address currentMCR = master.getLatestAddress("MC"); if (address(previousMCR) == address(0) || currentMCR != address(this)) { // already initialized or not ready for initialization return; } // fetch MCR parameters from previous contract uint112 minCap = 7000 * 1e18; mcrFloor = uint112(previousMCR.variableMincap()) + minCap; mcr = uint112(previousMCR.getLastMCREther()); desiredMCR = mcr; mcrFloorIncrementThreshold = uint24(previousMCR.dynamicMincapThresholdx100()); maxMCRFloorIncrement = uint24(previousMCR.dynamicMincapIncrementx100()); // set last updated time to now lastUpdateTime = uint32(block.timestamp); previousMCR = LegacyMCR(address(0)); } /** * @dev Gets total sum assured (in ETH). * @return amount of sum assured */ function getAllSumAssurance() public view returns (uint) { PriceFeedOracle priceFeed = pool.priceFeedOracle(); address daiAddress = priceFeed.daiAddress(); uint ethAmount = qd.getTotalSumAssured("ETH").mul(1e18); uint daiAmount = qd.getTotalSumAssured("DAI").mul(1e18); uint daiRate = priceFeed.getAssetToEthRate(daiAddress); uint daiAmountInEth = daiAmount.mul(daiRate).div(1e18); return ethAmount.add(daiAmountInEth); } /* * @dev trigger an MCR update. Current virtual MCR value is synced to storage, mcrFloor is potentially updated * and a new desiredMCR value to move towards is set. * */ function updateMCR() public { _updateMCR(pool.getPoolValueInEth(), false); } function updateMCRInternal(uint poolValueInEth, bool forceUpdate) public onlyInternal { _updateMCR(poolValueInEth, forceUpdate); } function _updateMCR(uint poolValueInEth, bool forceUpdate) internal { // read with 1 SLOAD uint _mcrFloorIncrementThreshold = mcrFloorIncrementThreshold; uint _maxMCRFloorIncrement = maxMCRFloorIncrement; uint _gearingFactor = gearingFactor; uint _minUpdateTime = minUpdateTime; uint _mcrFloor = mcrFloor; // read with 1 SLOAD uint112 _mcr = mcr; uint112 _desiredMCR = desiredMCR; uint32 _lastUpdateTime = lastUpdateTime; if (!forceUpdate && _lastUpdateTime + _minUpdateTime > block.timestamp) { return; } if (block.timestamp > _lastUpdateTime && pool.calculateMCRRatio(poolValueInEth, _mcr) >= _mcrFloorIncrementThreshold) { // MCR floor updates by up to maxMCRFloorIncrement percentage per day whenever the MCR ratio exceeds 1.3 // MCR floor is monotonically increasing. uint basisPointsAdjustment = min( _maxMCRFloorIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days), _maxMCRFloorIncrement ); uint newMCRFloor = _mcrFloor.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION); require(newMCRFloor <= uint112(~0), 'MCR: newMCRFloor overflow'); mcrFloor = uint112(newMCRFloor); } // sync the current virtual MCR value to storage uint112 newMCR = uint112(getMCR()); if (newMCR != _mcr) { mcr = newMCR; } // the desiredMCR cannot fall below the mcrFloor but may have a higher or lower target value based // on the changes in the totalSumAssured in the system. uint totalSumAssured = getAllSumAssurance(); uint gearedMCR = totalSumAssured.mul(BASIS_PRECISION).div(_gearingFactor); uint112 newDesiredMCR = uint112(max(gearedMCR, mcrFloor)); if (newDesiredMCR != _desiredMCR) { desiredMCR = newDesiredMCR; } lastUpdateTime = uint32(block.timestamp); emit MCRUpdated(mcr, desiredMCR, mcrFloor, gearedMCR, totalSumAssured); } /** * @dev Calculates the current virtual MCR value. The virtual MCR value moves towards the desiredMCR value away * from the stored mcr value at constant velocity based on how much time passed from the lastUpdateTime. * The total change in virtual MCR cannot exceed 1% of stored mcr. * * This approach allows for the MCR to change smoothly across time without sudden jumps between values, while * always progressing towards the desiredMCR goal. The desiredMCR can change subject to the call of _updateMCR * so the virtual MCR value may change direction and start decreasing instead of increasing or vice-versa. * * @return mcr */ function getMCR() public view returns (uint) { // read with 1 SLOAD uint _mcr = mcr; uint _desiredMCR = desiredMCR; uint _lastUpdateTime = lastUpdateTime; if (block.timestamp == _lastUpdateTime) { return _mcr; } uint _maxMCRIncrement = maxMCRIncrement; uint basisPointsAdjustment = _maxMCRIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days); basisPointsAdjustment = min(basisPointsAdjustment, MAX_MCR_ADJUSTMENT); if (_desiredMCR > _mcr) { return min(_mcr.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION), _desiredMCR); } // in case desiredMCR <= mcr return max(_mcr.mul(BASIS_PRECISION - basisPointsAdjustment).div(BASIS_PRECISION), _desiredMCR); } function getGearedMCR() external view returns (uint) { return getAllSumAssurance().mul(BASIS_PRECISION).div(gearingFactor); } function min(uint x, uint y) pure internal returns (uint) { return x < y ? x : y; } function max(uint x, uint y) pure internal returns (uint) { return x > y ? x : y; } /** * @dev Updates Uint Parameters * @param code parameter code * @param val new value */ function updateUintParameters(bytes8 code, uint val) public { require(master.checkIsAuthToGoverned(msg.sender)); if (code == "DMCT") { require(val <= UINT24_MAX, "MCR: value too large"); mcrFloorIncrementThreshold = uint24(val); } else if (code == "DMCI") { require(val <= UINT24_MAX, "MCR: value too large"); maxMCRFloorIncrement = uint24(val); } else if (code == "MMIC") { require(val <= UINT24_MAX, "MCR: value too large"); maxMCRIncrement = uint24(val); } else if (code == "GEAR") { require(val <= UINT24_MAX, "MCR: value too large"); gearingFactor = uint24(val); } else if (code == "MUTI") { require(val <= UINT24_MAX, "MCR: value too large"); minUpdateTime = uint24(val); } else { revert("Invalid param code"); } } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; contract INXMMaster { address public tokenAddress; address public owner; uint public pauseTime; function delegateCallBack(bytes32 myid) external; function masterInitialized() public view returns (bool); function isInternal(address _add) public view returns (bool); function isPause() public view returns (bool check); function isOwner(address _add) public view returns (bool); function isMember(address _add) public view returns (bool); function checkIsAuthToGoverned(address _add) public view returns (bool); function updatePauseTime(uint _time) public; function dAppLocker() public view returns (address _add); function dAppToken() public view returns (address _add); function getLatestAddress(bytes2 _contractName) public view returns (address payable contractAddress); } /* Copyright (C) 2020 NexusMutual.io 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/ */ //Claims Reward Contract contains the functions for calculating number of tokens // that will get rewarded, unlocked or burned depending upon the status of claim. pragma solidity ^0.5.0; import "../../interfaces/IPooledStaking.sol"; import "../capital/Pool.sol"; import "../cover/QuotationData.sol"; import "../governance/Governance.sol"; import "../token/TokenData.sol"; import "../token/TokenFunctions.sol"; import "./Claims.sol"; import "./ClaimsData.sol"; import "../capital/MCR.sol"; contract ClaimsReward is Iupgradable { using SafeMath for uint; NXMToken internal tk; TokenController internal tc; TokenData internal td; QuotationData internal qd; Claims internal c1; ClaimsData internal cd; Pool internal pool; Governance internal gv; IPooledStaking internal pooledStaking; MemberRoles internal memberRoles; MCR public mcr; // assigned in constructor address public DAI; // constants address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint private constant DECIMAL1E18 = uint(10) ** 18; constructor (address masterAddress, address _daiAddress) public { changeMasterAddress(masterAddress); DAI = _daiAddress; } function changeDependentContractAddress() public onlyInternal { c1 = Claims(ms.getLatestAddress("CL")); cd = ClaimsData(ms.getLatestAddress("CD")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); memberRoles = MemberRoles(ms.getLatestAddress("MR")); pool = Pool(ms.getLatestAddress("P1")); mcr = MCR(ms.getLatestAddress("MC")); } /// @dev Decides the next course of action for a given claim. function changeClaimStatus(uint claimid) public checkPause onlyInternal { (, uint coverid) = cd.getClaimCoverId(claimid); (, uint status) = cd.getClaimStatusNumber(claimid); // when current status is "Pending-Claim Assessor Vote" if (status == 0) { _changeClaimStatusCA(claimid, coverid, status); } else if (status >= 1 && status <= 5) { _changeClaimStatusMV(claimid, coverid, status); } else if (status == 12) {// when current status is "Claim Accepted Payout Pending" bool payoutSucceeded = attemptClaimPayout(coverid); if (payoutSucceeded) { c1.setClaimStatus(claimid, 14); } else { c1.setClaimStatus(claimid, 12); } } } function getCurrencyAssetAddress(bytes4 currency) public view returns (address) { if (currency == "ETH") { return ETH; } if (currency == "DAI") { return DAI; } revert("ClaimsReward: unknown asset"); } function attemptClaimPayout(uint coverId) internal returns (bool success) { uint sumAssured = qd.getCoverSumAssured(coverId); // TODO: when adding new cover currencies, fetch the correct decimals for this multiplication uint sumAssuredWei = sumAssured.mul(1e18); // get asset address bytes4 coverCurrency = qd.getCurrencyOfCover(coverId); address asset = getCurrencyAssetAddress(coverCurrency); // get payout address address payable coverHolder = qd.getCoverMemberAddress(coverId); address payable payoutAddress = memberRoles.getClaimPayoutAddress(coverHolder); // execute the payout bool payoutSucceeded = pool.sendClaimPayout(asset, payoutAddress, sumAssuredWei); if (payoutSucceeded) { // burn staked tokens (, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = pool.getTokenPrice(asset); // note: for new assets "18" needs to be replaced with target asset decimals uint burnNXMAmount = sumAssuredWei.mul(1e18).div(tokenPrice); pooledStaking.pushBurn(scAddress, burnNXMAmount); // adjust total sum assured (, address coverContract) = qd.getscAddressOfCover(coverId); qd.subFromTotalSumAssured(coverCurrency, sumAssured); qd.subFromTotalSumAssuredSC(coverContract, coverCurrency, sumAssured); // update MCR since total sum assured and MCR% change mcr.updateMCRInternal(pool.getPoolValueInEth(), true); return true; } return false; } /// @dev Amount of tokens to be rewarded to a user for a particular vote id. /// @param check 1 -> CA vote, else member vote /// @param voteid vote id for which reward has to be Calculated /// @param flag if 1 calculate even if claimed,else don't calculate if already claimed /// @return tokenCalculated reward to be given for vote id /// @return lastClaimedCheck true if final verdict is still pending for that voteid /// @return tokens number of tokens locked under that voteid /// @return perc percentage of reward to be given. function getRewardToBeGiven( uint check, uint voteid, uint flag ) public view returns ( uint tokenCalculated, bool lastClaimedCheck, uint tokens, uint perc ) { uint claimId; int8 verdict; bool claimed; uint tokensToBeDist; uint totalTokens; (tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid); lastClaimedCheck = false; int8 claimVerdict = cd.getFinalVerdict(claimId); if (claimVerdict == 0) { lastClaimedCheck = true; } if (claimVerdict == verdict && (claimed == false || flag == 1)) { if (check == 1) { (perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId); } else { (, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId); } if (perc > 0) { if (check == 1) { if (verdict == 1) { (, totalTokens,) = cd.getClaimsTokenCA(claimId); } else { (,, totalTokens) = cd.getClaimsTokenCA(claimId); } } else { if (verdict == 1) { (, totalTokens,) = cd.getClaimsTokenMV(claimId); } else { (,, totalTokens) = cd.getClaimsTokenMV(claimId); } } tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100)); } } } /// @dev Transfers all tokens held by contract to a new contract in case of upgrade. function upgrade(address _newAdd) public onlyInternal { uint amount = tk.balanceOf(address(this)); if (amount > 0) { require(tk.transfer(_newAdd, amount)); } } /// @dev Total reward in token due for claim by a user. /// @return total total number of tokens function getRewardToBeDistributedByUser(address _add) public view returns (uint total) { uint lengthVote = cd.getVoteAddressCALength(_add); uint lastIndexCA; uint lastIndexMV; uint tokenForVoteId; uint voteId; (lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add); for (uint i = lastIndexCA; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(_add, i); (tokenForVoteId,,,) = getRewardToBeGiven(1, voteId, 0); total = total.add(tokenForVoteId); } lengthVote = cd.getVoteAddressMemberLength(_add); for (uint j = lastIndexMV; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(_add, j); (tokenForVoteId,,,) = getRewardToBeGiven(0, voteId, 0); total = total.add(tokenForVoteId); } return (total); } /// @dev Gets reward amount and claiming status for a given claim id. /// @return reward amount of tokens to user. /// @return claimed true if already claimed false if yet to be claimed. function getRewardAndClaimedStatus(uint check, uint claimId) public view returns (uint reward, bool claimed) { uint voteId; uint claimid; uint lengthVote; if (check == 1) { lengthVote = cd.getVoteAddressCALength(msg.sender); for (uint i = 0; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(msg.sender, i); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) {break;} } } else { lengthVote = cd.getVoteAddressMemberLength(msg.sender); for (uint j = 0; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(msg.sender, j); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) {break;} } } (reward,,,) = getRewardToBeGiven(check, voteId, 1); } /** * @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance * Claim assesment, Risk assesment, Governance rewards */ function claimAllPendingReward(uint records) public isMemberAndcheckPause { _claimRewardToBeDistributed(records); pooledStaking.withdrawReward(msg.sender); uint governanceRewards = gv.claimReward(msg.sender, records); if (governanceRewards > 0) { require(tk.transfer(msg.sender, governanceRewards)); } } /** * @dev Function used to get pending rewards of a particular user address. * @param _add user address. * @return total reward amount of the user */ function getAllPendingRewardOfUser(address _add) public view returns (uint) { uint caReward = getRewardToBeDistributedByUser(_add); uint pooledStakingReward = pooledStaking.stakerReward(_add); uint governanceReward = gv.getPendingReward(_add); return caReward.add(pooledStakingReward).add(governanceReward); } /// @dev Rewards/Punishes users who participated in Claims assessment. // Unlocking and burning of the tokens will also depend upon the status of claim. /// @param claimid Claim Id. function _rewardAgainstClaim(uint claimid, uint coverid, uint status) internal { uint premiumNXM = qd.getCoverPremiumNXM(coverid); uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100); // 20% of premium uint percCA; uint percMV; (percCA, percMV) = cd.getRewardStatus(status); cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens); if (percCA > 0 || percMV > 0) { tc.mint(address(this), distributableTokens); } // denied if (status == 6 || status == 9 || status == 11) { cd.changeFinalVerdict(claimid, -1); tc.markCoverClaimClosed(coverid, false); _burnCoverNoteDeposit(coverid); // accepted } else if (status == 7 || status == 8 || status == 10) { cd.changeFinalVerdict(claimid, 1); tc.markCoverClaimClosed(coverid, true); _unlockCoverNote(coverid); bool payoutSucceeded = attemptClaimPayout(coverid); // 12 = payout pending, 14 = payout succeeded uint nextStatus = payoutSucceeded ? 14 : 12; c1.setClaimStatus(claimid, nextStatus); } } function _burnCoverNoteDeposit(uint coverId) internal { address _of = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); uint lockedAmount = tc.tokensLocked(_of, reason); (uint amount,) = td.depositedCN(coverId); amount = amount.div(2); // limit burn amount to actual amount locked uint burnAmount = lockedAmount < amount ? lockedAmount : amount; if (burnAmount != 0) { tc.burnLockedTokens(_of, reason, amount); } } function _unlockCoverNote(uint coverId) internal { address coverHolder = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId)); uint lockedCN = tc.tokensLocked(coverHolder, reason); if (lockedCN != 0) { tc.releaseLockedTokens(coverHolder, reason, lockedCN); } } /// @dev Computes the result of Claim Assessors Voting for a given claim id. function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency. uint accept; uint deny; uint acceptAndDeny; bool rewardOrPunish; uint sumAssured; (, accept) = cd.getClaimVote(claimid, 1); (, deny) = cd.getClaimVote(claimid, - 1); acceptAndDeny = accept.add(deny); accept = accept.mul(100); deny = deny.mul(100); if (caTokens == 0) { status = 3; } else { sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); // Min threshold reached tokens used for voting > 5* sum assured if (caTokens > sumAssured.mul(5)) { if (accept.div(acceptAndDeny) > 70) { status = 7; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted)); rewardOrPunish = true; } else if (deny.div(acceptAndDeny) > 70) { status = 6; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied)); rewardOrPunish = true; } else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 4; } else { status = 5; } } else { if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 2; } else { status = 3; } } } c1.setClaimStatus(claimid, status); if (rewardOrPunish) { _rewardAgainstClaim(claimid, coverid, status); } } } /// @dev Computes the result of Member Voting for a given claim id. function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint8 coverStatus; uint statusOrig = status; uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency. // If tokens used for acceptance >50%, claim is accepted uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); uint thresholdUnreached = 0; // Minimum threshold for member voting is reached only when // value of tokens used for voting > 5* sum assured of claim id if (mvTokens < sumAssured.mul(5)) { thresholdUnreached = 1; } uint accept; (, accept) = cd.getClaimMVote(claimid, 1); uint deny; (, deny) = cd.getClaimMVote(claimid, - 1); if (accept.add(deny) > 0) { if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 8; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 9; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } } if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) { status = 10; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) { status = 11; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } c1.setClaimStatus(claimid, status); qd.changeCoverStatusNo(coverid, uint8(coverStatus)); // Reward/Punish Claim Assessors and Members who participated in Claims assessment _rewardAgainstClaim(claimid, coverid, status); } } /// @dev Allows a user to claim all pending Claims assessment rewards. function _claimRewardToBeDistributed(uint _records) internal { uint lengthVote = cd.getVoteAddressCALength(msg.sender); uint voteid; uint lastIndex; (lastIndex,) = cd.getRewardDistributedIndex(msg.sender); uint total = 0; uint tokenForVoteId = 0; bool lastClaimedCheck; uint _days = td.lockCADays(); bool claimed; uint counter = 0; uint claimId; uint perc; uint i; uint lastClaimed = lengthVote; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressCA(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (perc > 0 && !claimed) { counter++; cd.setRewardClaimed(voteid, true); } else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) { (perc,,) = cd.getClaimRewardDetail(claimId); if (perc == 0) { counter++; } cd.setRewardClaimed(voteid, true); } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexCA(msg.sender, i); } else { cd.setRewardDistributedIndexCA(msg.sender, lastClaimed); } lengthVote = cd.getVoteAddressMemberLength(msg.sender); lastClaimed = lengthVote; _days = _days.mul(counter); if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) { tc.reduceLock(msg.sender, "CLA", _days); } (, lastIndex) = cd.getRewardDistributedIndex(msg.sender); lastClaimed = lengthVote; counter = 0; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressMember(msg.sender, i); (tokenForVoteId, lastClaimedCheck,,) = getRewardToBeGiven(0, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (claimed == false && cd.getFinalVerdict(claimId) != 0) { cd.setRewardClaimed(voteid, true); counter++; } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (total > 0) { require(tk.transfer(msg.sender, total)); } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexMV(msg.sender, i); } else { cd.setRewardDistributedIndexMV(msg.sender, lastClaimed); } } /** * @dev Function used to claim the commission earned by the staker. */ function _claimStakeCommission(uint _records, address _user) external onlyInternal { uint total = 0; uint len = td.getStakerStakedContractLength(_user); uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user); uint commissionEarned; uint commissionRedeemed; uint maxCommission; uint lastCommisionRedeemed = len; uint counter; uint i; for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) { commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i); commissionEarned = td.getStakerEarnedStakeCommission(_user, i); maxCommission = td.getStakerInitialStakedAmountOnContract( _user, i).mul(td.stakerMaxCommissionPer()).div(100); if (lastCommisionRedeemed == len && maxCommission != commissionEarned) lastCommisionRedeemed = i; td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed)); total = total.add(commissionEarned.sub(commissionRedeemed)); counter++; } if (lastCommisionRedeemed == len) { td.setLastCompletedStakeCommissionIndex(_user, i); } else { td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed); } if (total > 0) require(tk.transfer(_user, total)); // solhint-disable-line } } /* Copyright (C) 2021 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../abstract/MasterAware.sol"; import "../../interfaces/IPooledStaking.sol"; import "../capital/Pool.sol"; import "../claims/ClaimsData.sol"; import "../claims/ClaimsReward.sol"; import "../cover/QuotationData.sol"; import "../governance/MemberRoles.sol"; import "../token/TokenController.sol"; import "../capital/MCR.sol"; contract Incidents is MasterAware { using SafeERC20 for IERC20; using SafeMath for uint; struct Incident { address productId; uint32 date; uint priceBefore; } // contract identifiers enum ID {CD, CR, QD, TC, MR, P1, PS, MC} mapping(uint => address payable) public internalContracts; Incident[] public incidents; // product id => underlying token (ex. yDAI -> DAI) mapping(address => address) public underlyingToken; // product id => covered token (ex. 0xc7ed.....1 -> yDAI) mapping(address => address) public coveredToken; // claim id => payout amount mapping(uint => uint) public claimPayout; // product id => accumulated burn amount mapping(address => uint) public accumulatedBurn; // burn ratio in bps, ex 2000 for 20% uint public BURN_RATIO; // burn ratio in bps uint public DEDUCTIBLE_RATIO; uint constant BASIS_PRECISION = 10000; event ProductAdded( address indexed productId, address indexed coveredToken, address indexed underlyingToken ); event IncidentAdded( address indexed productId, uint incidentDate, uint priceBefore ); modifier onlyAdvisoryBoard { uint abRole = uint(MemberRoles.Role.AdvisoryBoard); require( memberRoles().checkRole(msg.sender, abRole), "Incidents: Caller is not an advisory board member" ); _; } function initialize() external { require(BURN_RATIO == 0, "Already initialized"); BURN_RATIO = 2000; DEDUCTIBLE_RATIO = 9000; } function addProducts( address[] calldata _productIds, address[] calldata _coveredTokens, address[] calldata _underlyingTokens ) external onlyAdvisoryBoard { require( _productIds.length == _coveredTokens.length, "Incidents: Protocols and covered tokens lengths differ" ); require( _productIds.length == _underlyingTokens.length, "Incidents: Protocols and underyling tokens lengths differ" ); for (uint i = 0; i < _productIds.length; i++) { address id = _productIds[i]; require(coveredToken[id] == address(0), "Incidents: covered token is already set"); require(underlyingToken[id] == address(0), "Incidents: underlying token is already set"); coveredToken[id] = _coveredTokens[i]; underlyingToken[id] = _underlyingTokens[i]; emit ProductAdded(id, _coveredTokens[i], _underlyingTokens[i]); } } function incidentCount() external view returns (uint) { return incidents.length; } function addIncident( address productId, uint incidentDate, uint priceBefore ) external onlyGovernance { address underlying = underlyingToken[productId]; require(underlying != address(0), "Incidents: Unsupported product"); Incident memory incident = Incident(productId, uint32(incidentDate), priceBefore); incidents.push(incident); emit IncidentAdded(productId, incidentDate, priceBefore); } function redeemPayoutForMember( uint coverId, uint incidentId, uint coveredTokenAmount, address member ) external onlyInternal returns (uint claimId, uint payoutAmount, address payoutToken) { (claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, member); } function redeemPayout( uint coverId, uint incidentId, uint coveredTokenAmount ) external returns (uint claimId, uint payoutAmount, address payoutToken) { (claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, msg.sender); } function _redeemPayout( uint coverId, uint incidentId, uint coveredTokenAmount, address coverOwner ) internal returns (uint claimId, uint payoutAmount, address coverAsset) { QuotationData qd = quotationData(); Incident memory incident = incidents[incidentId]; uint sumAssured; bytes4 currency; { address productId; address _coverOwner; (/* id */, _coverOwner, productId, currency, sumAssured, /* premiumNXM */ ) = qd.getCoverDetailsByCoverID1(coverId); // check ownership and covered protocol require(coverOwner == _coverOwner, "Incidents: Not cover owner"); require(productId == incident.productId, "Incidents: Bad incident id"); } { uint coverPeriod = uint(qd.getCoverPeriod(coverId)).mul(1 days); uint coverExpirationDate = qd.getValidityOfCover(coverId); uint coverStartDate = coverExpirationDate.sub(coverPeriod); // check cover validity require(coverStartDate <= incident.date, "Incidents: Cover start date is after the incident"); require(coverExpirationDate >= incident.date, "Incidents: Cover end date is before the incident"); // check grace period uint gracePeriod = tokenController().claimSubmissionGracePeriod(); require(coverExpirationDate.add(gracePeriod) >= block.timestamp, "Incidents: Grace period has expired"); } { // assumes 18 decimals (eth & dai) uint decimalPrecision = 1e18; uint maxAmount; // sumAssured is currently stored without decimals uint coverAmount = sumAssured.mul(decimalPrecision); { // max amount check uint deductiblePriceBefore = incident.priceBefore.mul(DEDUCTIBLE_RATIO).div(BASIS_PRECISION); maxAmount = coverAmount.mul(decimalPrecision).div(deductiblePriceBefore); require(coveredTokenAmount <= maxAmount, "Incidents: Amount exceeds sum assured"); } // payoutAmount = coveredTokenAmount / maxAmount * coverAmount // = coveredTokenAmount * coverAmount / maxAmount payoutAmount = coveredTokenAmount.mul(coverAmount).div(maxAmount); } { TokenController tc = tokenController(); // mark cover as having a successful claim tc.markCoverClaimOpen(coverId); tc.markCoverClaimClosed(coverId, true); // create the claim ClaimsData cd = claimsData(); claimId = cd.actualClaimLength(); cd.addClaim(claimId, coverId, coverOwner, now); cd.callClaimEvent(coverId, coverOwner, claimId, now); cd.setClaimStatus(claimId, 14); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimAccepted)); claimPayout[claimId] = payoutAmount; } coverAsset = claimsReward().getCurrencyAssetAddress(currency); _sendPayoutAndPushBurn( incident.productId, address(uint160(coverOwner)), coveredTokenAmount, coverAsset, payoutAmount ); qd.subFromTotalSumAssured(currency, sumAssured); qd.subFromTotalSumAssuredSC(incident.productId, currency, sumAssured); mcr().updateMCRInternal(pool().getPoolValueInEth(), true); } function pushBurns(address productId, uint maxIterations) external { uint burnAmount = accumulatedBurn[productId]; delete accumulatedBurn[productId]; require(burnAmount > 0, "Incidents: No burns to push"); require(maxIterations >= 30, "Incidents: Pass at least 30 iterations"); IPooledStaking ps = pooledStaking(); ps.pushBurn(productId, burnAmount); ps.processPendingActions(maxIterations); } function withdrawAsset(address asset, address destination, uint amount) external onlyGovernance { IERC20 token = IERC20(asset); uint balance = token.balanceOf(address(this)); uint transferAmount = amount > balance ? balance : amount; token.safeTransfer(destination, transferAmount); } function _sendPayoutAndPushBurn( address productId, address payable coverOwner, uint coveredTokenAmount, address coverAsset, uint payoutAmount ) internal { address _coveredToken = coveredToken[productId]; // pull depegged tokens IERC20(_coveredToken).safeTransferFrom(msg.sender, address(this), coveredTokenAmount); Pool p1 = pool(); // send the payoutAmount { address payable payoutAddress = memberRoles().getClaimPayoutAddress(coverOwner); bool success = p1.sendClaimPayout(coverAsset, payoutAddress, payoutAmount); require(success, "Incidents: Payout failed"); } { // burn uint decimalPrecision = 1e18; uint assetPerNxm = p1.getTokenPrice(coverAsset); uint maxBurnAmount = payoutAmount.mul(decimalPrecision).div(assetPerNxm); uint burnAmount = maxBurnAmount.mul(BURN_RATIO).div(BASIS_PRECISION); accumulatedBurn[productId] = accumulatedBurn[productId].add(burnAmount); } } function claimsData() internal view returns (ClaimsData) { return ClaimsData(internalContracts[uint(ID.CD)]); } function claimsReward() internal view returns (ClaimsReward) { return ClaimsReward(internalContracts[uint(ID.CR)]); } function quotationData() internal view returns (QuotationData) { return QuotationData(internalContracts[uint(ID.QD)]); } function tokenController() internal view returns (TokenController) { return TokenController(internalContracts[uint(ID.TC)]); } function memberRoles() internal view returns (MemberRoles) { return MemberRoles(internalContracts[uint(ID.MR)]); } function pool() internal view returns (Pool) { return Pool(internalContracts[uint(ID.P1)]); } function pooledStaking() internal view returns (IPooledStaking) { return IPooledStaking(internalContracts[uint(ID.PS)]); } function mcr() internal view returns (MCR) { return MCR(internalContracts[uint(ID.MC)]); } function updateUintParameters(bytes8 code, uint value) external onlyGovernance { if (code == "BURNRATE") { require(value <= BASIS_PRECISION, "Incidents: Burn ratio cannot exceed 10000"); BURN_RATIO = value; return; } if (code == "DEDUCTIB") { require(value <= BASIS_PRECISION, "Incidents: Deductible ratio cannot exceed 10000"); DEDUCTIBLE_RATIO = value; return; } revert("Incidents: Invalid parameter"); } function changeDependentContractAddress() external { INXMMaster master = INXMMaster(master); internalContracts[uint(ID.CD)] = master.getLatestAddress("CD"); internalContracts[uint(ID.CR)] = master.getLatestAddress("CR"); internalContracts[uint(ID.QD)] = master.getLatestAddress("QD"); internalContracts[uint(ID.TC)] = master.getLatestAddress("TC"); internalContracts[uint(ID.MR)] = master.getLatestAddress("MR"); internalContracts[uint(ID.P1)] = master.getLatestAddress("P1"); internalContracts[uint(ID.PS)] = master.getLatestAddress("PS"); internalContracts[uint(ID.MC)] = master.getLatestAddress("MC"); } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/Iupgradable.sol"; contract TokenData is Iupgradable { using SafeMath for uint; address payable public walletAddress; uint public lockTokenTimeAfterCoverExp; uint public bookTime; uint public lockCADays; uint public lockMVDays; uint public scValidDays; uint public joiningFee; uint public stakerCommissionPer; uint public stakerMaxCommissionPer; uint public tokenExponent; uint public priceStep; struct StakeCommission { uint commissionEarned; uint commissionRedeemed; } struct Stake { address stakedContractAddress; uint stakedContractIndex; uint dateAdd; uint stakeAmount; uint unlockedAmount; uint burnedAmount; uint unLockableBeforeLastBurn; } struct Staker { address stakerAddress; uint stakerIndex; } struct CoverNote { uint amount; bool isDeposited; } /** * @dev mapping of uw address to array of sc address to fetch * all staked contract address of underwriter, pushing * data into this array of Stake returns stakerIndex */ mapping(address => Stake[]) public stakerStakedContracts; /** * @dev mapping of sc address to array of UW address to fetch * all underwritters of the staked smart contract * pushing data into this mapped array returns scIndex */ mapping(address => Staker[]) public stakedContractStakers; /** * @dev mapping of staked contract Address to the array of StakeCommission * here index of this array is stakedContractIndex */ mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission; mapping(address => uint) public lastCompletedStakeCommission; /** * @dev mapping of the staked contract address to the current * staker index who will receive commission. */ mapping(address => uint) public stakedContractCurrentCommissionIndex; /** * @dev mapping of the staked contract address to the * current staker index to burn token from. */ mapping(address => uint) public stakedContractCurrentBurnIndex; /** * @dev mapping to return true if Cover Note deposited against coverId */ mapping(uint => CoverNote) public depositedCN; mapping(address => uint) internal isBookedTokens; event Commission( address indexed stakedContractAddress, address indexed stakerAddress, uint indexed scIndex, uint commissionAmount ); constructor(address payable _walletAdd) public { walletAddress = _walletAdd; bookTime = 12 hours; joiningFee = 2000000000000000; // 0.002 Ether lockTokenTimeAfterCoverExp = 35 days; scValidDays = 250; lockCADays = 7 days; lockMVDays = 2 days; stakerCommissionPer = 20; stakerMaxCommissionPer = 50; tokenExponent = 4; priceStep = 1000; } /** * @dev Change the wallet address which receive Joining Fee */ function changeWalletAddress(address payable _address) external onlyInternal { walletAddress = _address; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "TOKEXP") { val = tokenExponent; } else if (code == "TOKSTEP") { val = priceStep; } else if (code == "RALOCKT") { val = scValidDays; } else if (code == "RACOMM") { val = stakerCommissionPer; } else if (code == "RAMAXC") { val = stakerMaxCommissionPer; } else if (code == "CABOOKT") { val = bookTime / (1 hours); } else if (code == "CALOCKT") { val = lockCADays / (1 days); } else if (code == "MVLOCKT") { val = lockMVDays / (1 days); } else if (code == "QUOLOCKT") { val = lockTokenTimeAfterCoverExp / (1 days); } else if (code == "JOINFEE") { val = joiningFee; } } /** * @dev Just for interface */ function changeDependentContractAddress() public {//solhint-disable-line } /** * @dev to get the contract staked by a staker * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return the address of staked contract */ function getStakerStakedContractByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (address stakedContractAddress) { stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; } /** * @dev to get the staker's staked burned * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount burned */ function getStakerStakedBurnedByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint burnedAmount) { burnedAmount = stakerStakedContracts[ _stakerAddress][_stakerIndex].burnedAmount; } /** * @dev to get the staker's staked unlockable before the last burn * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return unlockable staked tokens */ function getStakerStakedUnlockableBeforeLastBurnByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint unlockable) { unlockable = stakerStakedContracts[ _stakerAddress][_stakerIndex].unLockableBeforeLastBurn; } /** * @dev to get the staker's staked contract index * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return is the index of the smart contract address */ function getStakerStakedContractIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint scIndex) { scIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; } /** * @dev to get the staker index of the staked contract * @param _stakedContractAddress is the address of the staked contract * @param _stakedContractIndex is the index of staked contract * @return is the index of the staker */ function getStakedContractStakerIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint sIndex) { sIndex = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerIndex; } /** * @dev to get the staker's initial staked amount on the contract * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return staked amount */ function getStakerInitialStakedAmountOnContract( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakeAmount; } /** * @dev to get the staker's staked contract length * @param _stakerAddress is the address of the staker * @return length of staked contract */ function getStakerStakedContractLength( address _stakerAddress ) public view returns (uint length) { length = stakerStakedContracts[_stakerAddress].length; } /** * @dev to get the staker's unlocked tokens which were staked * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount */ function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].unlockedAmount; } /** * @dev pushes the unlocked staked tokens by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount.add(_amount); } /** * @dev pushes the Burned tokens for a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be burned. */ function pushBurnedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount.add(_amount); } /** * @dev pushes the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function pushUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn.add(_amount); } /** * @dev sets the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function setUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = _amount; } /** * @dev pushes the earned commission earned by a staker. * @param _stakerAddress address of staker. * @param _stakedContractAddress address of smart contract. * @param _stakedContractIndex index of the staker to distribute commission. * @param _commissionAmount amount to be given as commission. */ function pushEarnedStakeCommissions( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _commissionAmount ) public onlyInternal { stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex]. commissionEarned = stakedContractStakeCommission[_stakedContractAddress][ _stakedContractIndex].commissionEarned.add(_commissionAmount); emit Commission( _stakerAddress, _stakedContractAddress, _stakedContractIndex, _commissionAmount ); } /** * @dev pushes the redeemed commission redeemed by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushRedeemedStakeCommissions( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { uint stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; address stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; stakedContractStakeCommission[stakedContractAddress][stakedContractIndex]. commissionRedeemed = stakedContractStakeCommission[ stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); } /** * @dev Gets stake commission given to an underwriter * for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets stake commission redeemed by an underwriter * for particular staked contract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. * @return commissionEarned total amount given to staker. */ function getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalEarnedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionEarned) { totalCommissionEarned = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionEarned = totalCommissionEarned. add(_getStakerEarnedStakeCommission(_stakerAddress, i)); } } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalReedmedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionRedeemed) { totalCommissionRedeemed = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionRedeemed = totalCommissionRedeemed.add( _getStakerRedeemedStakeCommission(_stakerAddress, i)); } } /** * @dev set flag to deposit/ undeposit cover note * against a cover Id * @param coverId coverId of Cover * @param flag true/false for deposit/undeposit */ function setDepositCN(uint coverId, bool flag) public onlyInternal { if (flag == true) { require(!depositedCN[coverId].isDeposited, "Cover note already deposited"); } depositedCN[coverId].isDeposited = flag; } /** * @dev set locked cover note amount * against a cover Id * @param coverId coverId of Cover * @param amount amount of nxm to be locked */ function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; } /** * @dev to get the staker address on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @param _stakedContractIndex is the index of staked contract's index * @return address of staker */ function getStakedContractStakerByIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (address stakerAddress) { stakerAddress = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerAddress; } /** * @dev to get the length of stakers on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @return length in concern */ function getStakedContractStakersLength( address _stakedContractAddress ) public view returns (uint length) { length = stakedContractStakers[_stakedContractAddress].length; } /** * @dev Adds a new stake record. * @param _stakerAddress staker address. * @param _stakedContractAddress smart contract address. * @param _amount amountof NXM to be staked. */ function addStake( address _stakerAddress, address _stakedContractAddress, uint _amount ) public onlyInternal returns (uint scIndex) { scIndex = (stakedContractStakers[_stakedContractAddress].push( Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1); stakerStakedContracts[_stakerAddress].push( Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0)); } /** * @dev books the user's tokens for maintaining Assessor Velocity, * i.e. once a token is used to cast a vote as a Claims assessor, * @param _of user's address. */ function bookCATokens(address _of) public onlyInternal { require(!isCATokensBooked(_of), "Tokens already booked"); isBookedTokens[_of] = now.add(bookTime); } /** * @dev to know if claim assessor's tokens are booked or not * @param _of is the claim assessor's address in concern * @return boolean representing the status of tokens booked */ function isCATokensBooked(address _of) public view returns (bool res) { if (now < isBookedTokens[_of]) res = true; } /** * @dev Sets the index which will receive commission. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentCommissionIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index; } /** * @dev Sets the last complete commission index * @param _stakerAddress smart contract address. * @param _index current index. */ function setLastCompletedStakeCommissionIndex( address _stakerAddress, uint _index ) public onlyInternal { lastCompletedStakeCommission[_stakerAddress] = _index; } /** * @dev Sets the index till which commission is distrubuted. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentBurnIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentBurnIndex[_stakedContractAddress] = _index; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "TOKEXP") { _setTokenExponent(val); } else if (code == "TOKSTEP") { _setPriceStep(val); } else if (code == "RALOCKT") { _changeSCValidDays(val); } else if (code == "RACOMM") { _setStakerCommissionPer(val); } else if (code == "RAMAXC") { _setStakerMaxCommissionPer(val); } else if (code == "CABOOKT") { _changeBookTime(val * 1 hours); } else if (code == "CALOCKT") { _changelockCADays(val * 1 days); } else if (code == "MVLOCKT") { _changelockMVDays(val * 1 days); } else if (code == "QUOLOCKT") { _setLockTokenTimeAfterCoverExp(val * 1 days); } else if (code == "JOINFEE") { _setJoiningFee(val); } else { revert("Invalid param code"); } } /** * @dev Internal function to get stake commission given to an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionEarned; } /** * @dev Internal function to get stake commission redeemed by an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionRedeemed; } /** * @dev to set the percentage of staker commission * @param _val is new percentage value */ function _setStakerCommissionPer(uint _val) internal { stakerCommissionPer = _val; } /** * @dev to set the max percentage of staker commission * @param _val is new percentage value */ function _setStakerMaxCommissionPer(uint _val) internal { stakerMaxCommissionPer = _val; } /** * @dev to set the token exponent value * @param _val is new value */ function _setTokenExponent(uint _val) internal { tokenExponent = _val; } /** * @dev to set the price step * @param _val is new value */ function _setPriceStep(uint _val) internal { priceStep = _val; } /** * @dev Changes number of days for which NXM needs to staked in case of underwriting */ function _changeSCValidDays(uint _days) internal { scValidDays = _days; } /** * @dev Changes the time period up to which tokens will be locked. * Used to generate the validity period of tokens booked by * a user for participating in claim's assessment/claim's voting. */ function _changeBookTime(uint _time) internal { bookTime = _time; } /** * @dev Changes lock CA days - number of days for which tokens * are locked while submitting a vote. */ function _changelockCADays(uint _val) internal { lockCADays = _val; } /** * @dev Changes lock MV days - number of days for which tokens are locked * while submitting a vote. */ function _changelockMVDays(uint _val) internal { lockMVDays = _val; } /** * @dev Changes extra lock period for a cover, post its expiry. */ function _setLockTokenTimeAfterCoverExp(uint time) internal { lockTokenTimeAfterCoverExp = time; } /** * @dev Set the joining fee for membership */ function _setJoiningFee(uint _amount) internal { joiningFee = _amount; } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/Iupgradable.sol"; contract QuotationData is Iupgradable { using SafeMath for uint; enum HCIDStatus {NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover} enum CoverStatus {Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested} struct Cover { address payable memberAddress; bytes4 currencyCode; uint sumAssured; uint16 coverPeriod; uint validUntil; address scAddress; uint premiumNXM; } struct HoldCover { uint holdCoverId; address payable userAddress; address scAddress; bytes4 coverCurr; uint[] coverDetails; uint16 coverPeriod; } address public authQuoteEngine; mapping(bytes4 => uint) internal currencyCSA; mapping(address => uint[]) internal userCover; mapping(address => uint[]) public userHoldedCover; mapping(address => bool) public refundEligible; mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd; mapping(uint => uint8) public coverStatus; mapping(uint => uint) public holdedCoverIDStatus; mapping(uint => bool) public timestampRepeated; Cover[] internal allCovers; HoldCover[] internal allCoverHolded; uint public stlp; uint public stl; uint public pm; uint public minDays; uint public tokensRetained; address public kycAuthAddress; event CoverDetailsEvent( uint indexed cid, address scAdd, uint sumAssured, uint expiry, uint premium, uint premiumNXM, bytes4 curr ); event CoverStatusEvent(uint indexed cid, uint8 statusNum); constructor(address _authQuoteAdd, address _kycAuthAdd) public { authQuoteEngine = _authQuoteAdd; kycAuthAddress = _kycAuthAdd; stlp = 90; stl = 100; pm = 30; minDays = 30; tokensRetained = 10; allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0)); uint[] memory arr = new uint[](1); allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0)); } /// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be added. function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be subtracted. function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be subtracted. function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); } /// @dev Adds the amount in Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be added. function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].add(_amount); } /// @dev sets bit for timestamp to avoid replay attacks. function setTimestampRepeated(uint _timestamp) external onlyInternal { timestampRepeated[_timestamp] = true; } /// @dev Creates a blank new cover. function addCover( uint16 _coverPeriod, uint _sumAssured, address payable _userAddress, bytes4 _currencyCode, address _scAddress, uint premium, uint premiumNXM ) external onlyInternal { uint expiryDate = now.add(uint(_coverPeriod).mul(1 days)); allCovers.push(Cover(_userAddress, _currencyCode, _sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM)); uint cid = allCovers.length.sub(1); userCover[_userAddress].push(cid); emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode); } /// @dev create holded cover which will process after verdict of KYC. function addHoldCover( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod ) external onlyInternal { uint holdedCoverLen = allCoverHolded.length; holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending); allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress, coverCurr, coverDetails, coverPeriod)); userHoldedCover[from].push(allCoverHolded.length.sub(1)); } ///@dev sets refund eligible bit. ///@param _add user address. ///@param status indicates if user have pending kyc. function setRefundEligible(address _add, bool status) external onlyInternal { refundEligible[_add] = status; } /// @dev to set current status of particular holded coverID (1 for not completed KYC, /// 2 for KYC passed, 3 for failed KYC or full refunded, /// 4 for KYC completed but cover not processed) function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal { holdedCoverIDStatus[holdedCoverID] = status; } /** * @dev to set address of kyc authentication * @param _add is the new address */ function setKycAuthAddress(address _add) external onlyInternal { kycAuthAddress = _add; } /// @dev Changes authorised address for generating quote off chain. function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "STLP") { val = stlp; } else if (code == "STL") { val = stl; } else if (code == "PM") { val = pm; } else if (code == "QUOMIND") { val = minDays; } else if (code == "QUOTOK") { val = tokensRetained; } } /// @dev Gets Product details. /// @return _minDays minimum cover period. /// @return _PM Profit margin. /// @return _STL short term Load. /// @return _STLP short term load period. function getProductDetails() external view returns ( uint _minDays, uint _pm, uint _stl, uint _stlp ) { _minDays = minDays; _pm = pm; _stl = stl; _stlp = stlp; } /// @dev Gets total number covers created till date. function getCoverLength() external view returns (uint len) { return (allCovers.length); } /// @dev Gets Authorised Engine address. function getAuthQuoteEngine() external view returns (address _add) { _add = authQuoteEngine; } /// @dev Gets the Total Sum Assured amount of a given currency. function getTotalSumAssured(bytes4 _curr) external view returns (uint amount) { amount = currencyCSA[_curr]; } /// @dev Gets all the Cover ids generated by a given address. /// @param _add User's address. /// @return allCover array of covers. function getAllCoversOfUser(address _add) external view returns (uint[] memory allCover) { return (userCover[_add]); } /// @dev Gets total number of covers generated by a given address function getUserCoverLength(address _add) external view returns (uint len) { len = userCover[_add].length; } /// @dev Gets the status of a given cover. function getCoverStatusNo(uint _cid) external view returns (uint8) { return coverStatus[_cid]; } /// @dev Gets the Cover Period (in days) of a given cover. function getCoverPeriod(uint _cid) external view returns (uint32 cp) { cp = allCovers[_cid].coverPeriod; } /// @dev Gets the Sum Assured Amount of a given cover. function getCoverSumAssured(uint _cid) external view returns (uint sa) { sa = allCovers[_cid].sumAssured; } /// @dev Gets the Currency Name in which a given cover is assured. function getCurrencyOfCover(uint _cid) external view returns (bytes4 curr) { curr = allCovers[_cid].currencyCode; } /// @dev Gets the validity date (timestamp) of a given cover. function getValidityOfCover(uint _cid) external view returns (uint date) { date = allCovers[_cid].validUntil; } /// @dev Gets Smart contract address of cover. function getscAddressOfCover(uint _cid) external view returns (uint, address) { return (_cid, allCovers[_cid].scAddress); } /// @dev Gets the owner address of a given cover. function getCoverMemberAddress(uint _cid) external view returns (address payable _add) { _add = allCovers[_cid].memberAddress; } /// @dev Gets the premium amount of a given cover in NXM. function getCoverPremiumNXM(uint _cid) external view returns (uint _premiumNXM) { _premiumNXM = allCovers[_cid].premiumNXM; } /// @dev Provides the details of a cover Id /// @param _cid cover Id /// @return memberAddress cover user address. /// @return scAddress smart contract Address /// @return currencyCode currency of cover /// @return sumAssured sum assured of cover /// @return premiumNXM premium in NXM function getCoverDetailsByCoverID1( uint _cid ) external view returns ( uint cid, address _memberAddress, address _scAddress, bytes4 _currencyCode, uint _sumAssured, uint premiumNXM ) { return ( _cid, allCovers[_cid].memberAddress, allCovers[_cid].scAddress, allCovers[_cid].currencyCode, allCovers[_cid].sumAssured, allCovers[_cid].premiumNXM ); } /// @dev Provides details of a cover Id /// @param _cid cover Id /// @return status status of cover. /// @return sumAssured Sum assurance of cover. /// @return coverPeriod Cover Period of cover (in days). /// @return validUntil is validity of cover. function getCoverDetailsByCoverID2( uint _cid ) external view returns ( uint cid, uint8 status, uint sumAssured, uint16 coverPeriod, uint validUntil ) { return ( _cid, coverStatus[_cid], allCovers[_cid].sumAssured, allCovers[_cid].coverPeriod, allCovers[_cid].validUntil ); } /// @dev Provides details of a holded cover Id /// @param _hcid holded cover Id /// @return scAddress SmartCover address of cover. /// @return coverCurr currency of cover. /// @return coverPeriod Cover Period of cover (in days). function getHoldedCoverDetailsByID1( uint _hcid ) external view returns ( uint hcid, address scAddress, bytes4 coverCurr, uint16 coverPeriod ) { return ( _hcid, allCoverHolded[_hcid].scAddress, allCoverHolded[_hcid].coverCurr, allCoverHolded[_hcid].coverPeriod ); } /// @dev Gets total number holded covers created till date. function getUserHoldedCoverLength(address _add) external view returns (uint) { return userHoldedCover[_add].length; } /// @dev Gets holded cover index by index of user holded covers. function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) { return userHoldedCover[_add][index]; } /// @dev Provides the details of a holded cover Id /// @param _hcid holded cover Id /// @return memberAddress holded cover user address. /// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute. function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails ) { return ( _hcid, allCoverHolded[_hcid].userAddress, allCoverHolded[_hcid].coverDetails ); } /// @dev Gets the Total Sum Assured amount of a given currency and smart contract address. function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; } //solhint-disable-next-line function changeDependentContractAddress() public {} /// @dev Changes the status of a given cover. /// @param _cid cover Id. /// @param _stat New status. function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal { coverStatus[_cid] = _stat; emit CoverStatusEvent(_cid, _stat); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "STLP") { _changeSTLP(val); } else if (code == "STL") { _changeSTL(val); } else if (code == "PM") { _changePM(val); } else if (code == "QUOMIND") { _changeMinDays(val); } else if (code == "QUOTOK") { _setTokensRetained(val); } else { revert("Invalid param code"); } } /// @dev Changes the existing Profit Margin value function _changePM(uint _pm) internal { pm = _pm; } /// @dev Changes the existing Short Term Load Period (STLP) value. function _changeSTLP(uint _stlp) internal { stlp = _stlp; } /// @dev Changes the existing Short Term Load (STL) value. function _changeSTL(uint _stl) internal { stl = _stl; } /// @dev Changes the existing Minimum cover period (in days) function _changeMinDays(uint _days) internal { minDays = _days; } /** * @dev to set the the amount of tokens retained * @param val is the amount retained */ function _setTokensRetained(uint val) internal { tokensRetained = val; } } pragma solidity ^0.5.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface OZIERC20 { 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 ); } pragma solidity ^0.5.0; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library OZSafeMath { /** * @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; } } pragma solidity ^0.5.0; import "./INXMMaster.sol"; contract Iupgradable { INXMMaster public ms; address public nxMasterAddress; modifier onlyInternal { require(ms.isInternal(msg.sender)); _; } modifier isMemberAndcheckPause { require(ms.isPause() == false && ms.isMember(msg.sender) == true); _; } modifier onlyOwner { require(ms.isOwner(msg.sender)); _; } modifier checkPause { require(ms.isPause() == false); _; } modifier isMember { require(ms.isMember(msg.sender), "Not member"); _; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public; /** * @dev change master address * @param _masterAddress is the new address */ function changeMasterAddress(address _masterAddress) public { if (address(ms) != address(0)) { require(address(ms) == msg.sender, "Not master"); } ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } } pragma solidity ^0.5.0; interface IPooledStaking { function accumulateReward(address contractAddress, uint amount) external; function pushBurn(address contractAddress, uint amount) external; function hasPendingActions() external view returns (bool); function processPendingActions(uint maxIterations) external returns (bool finished); function contractStake(address contractAddress) external view returns (uint); function stakerReward(address staker) external view returns (uint); function stakerDeposit(address staker) external view returns (uint); function stakerContractStake(address staker, address contractAddress) external view returns (uint); function withdraw(uint amount) external; function stakerMaxWithdrawable(address stakerAddress) external view returns (uint); function withdrawReward(address stakerAddress) external; } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/Iupgradable.sol"; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); if (_vote == - 1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); if (_vote == - 1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns ( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns ( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns (uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns (uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns (uint voteCount) { return allvotes.length.sub(1); // Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns (uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns (uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns (uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns (uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns (uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns ( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns ( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns (uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns (uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns ( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns (address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns ( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns (uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns (int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns (uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns (address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns (uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns (uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns (uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns ( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns ( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns ( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns ( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns ( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns ( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns (uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns (uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns (uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns (uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns (uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns (int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns (uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns (uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns (uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns ( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns (uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); // 0 Pending-Claim Assessor Vote _pushStatus(0, 0); // 1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); // 2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); // 3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); // 4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); // 5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); // 6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); // 7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); // 8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); // 9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); // 10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); // 11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); // 12 Claim Accepted Payout Pending _pushStatus(0, 0); // 13 Claim Accepted No Payout _pushStatus(0, 0); // 14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } pragma solidity ^0.5.0; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract LockHandler { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; } pragma solidity ^0.5.0; interface LegacyMCR { function addMCRData(uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate) external; function addLastMCRData(uint64 date) external; function changeDependentContractAddress() external; function getAllSumAssurance() external view returns (uint amount); function _calVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp); function calculateStepTokenPrice(bytes4 curr, uint mcrtp) external view returns (uint tokenPrice); function calculateTokenPrice(bytes4 curr) external view returns (uint tokenPrice); function calVtpAndMCRtp() external view returns (uint vtp, uint mcrtp); function calculateVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp); function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) external view returns (uint lowerThreshold, uint upperThreshold); function getMaxSellTokens() external view returns (uint maxTokens); function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val); function updateUintParameters(bytes8 code, uint val) external; function variableMincap() external view returns (uint); function dynamicMincapThresholdx100() external view returns (uint); function dynamicMincapIncrementx100() external view returns (uint); function getLastMCREther() external view returns (uint); } // /* Copyright (C) 2017 GovBlocks.io // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../token/TokenController.sol"; import "./MemberRoles.sol"; import "./ProposalCategory.sol"; import "./external/IGovernance.sol"; contract Governance is IGovernance, Iupgradable { using SafeMath for uint; enum ProposalStatus { Draft, AwaitingSolution, VotingStarted, Accepted, Rejected, Majority_Not_Reached_But_Accepted, Denied } struct ProposalData { uint propStatus; uint finalVerdict; uint category; uint commonIncentive; uint dateUpd; address owner; } struct ProposalVote { address voter; uint proposalId; uint dateAdd; } struct VoteTally { mapping(uint => uint) memberVoteValue; mapping(uint => uint) abVoteValue; uint voters; } struct DelegateVote { address follower; address leader; uint lastUpd; } ProposalVote[] internal allVotes; DelegateVote[] public allDelegation; mapping(uint => ProposalData) internal allProposalData; mapping(uint => bytes[]) internal allProposalSolutions; mapping(address => uint[]) internal allVotesByMember; mapping(uint => mapping(address => bool)) public rewardClaimed; mapping(address => mapping(uint => uint)) public memberProposalVote; mapping(address => uint) public followerDelegation; mapping(address => uint) internal followerCount; mapping(address => uint[]) internal leaderDelegation; mapping(uint => VoteTally) public proposalVoteTally; mapping(address => bool) public isOpenForDelegation; mapping(address => uint) public lastRewardClaimed; bool internal constructorCheck; uint public tokenHoldingTime; uint internal roleIdAllowedToCatgorize; uint internal maxVoteWeigthPer; uint internal specialResolutionMajPerc; uint internal maxFollowers; uint internal totalProposals; uint internal maxDraftTime; MemberRoles internal memberRole; ProposalCategory internal proposalCategory; TokenController internal tokenInstance; mapping(uint => uint) public proposalActionStatus; mapping(uint => uint) internal proposalExecutionTime; mapping(uint => mapping(address => bool)) public proposalRejectedByAB; mapping(uint => uint) internal actionRejectedCount; bool internal actionParamsInitialised; uint internal actionWaitingTime; uint constant internal AB_MAJ_TO_REJECT_ACTION = 3; enum ActionStatus { Pending, Accepted, Rejected, Executed, NoAction } /** * @dev Called whenever an action execution is failed. */ event ActionFailed ( uint256 proposalId ); /** * @dev Called whenever an AB member rejects the action execution. */ event ActionRejected ( uint256 indexed proposalId, address rejectedBy ); /** * @dev Checks if msg.sender is proposal owner */ modifier onlyProposalOwner(uint _proposalId) { require(msg.sender == allProposalData[_proposalId].owner, "Not allowed"); _; } /** * @dev Checks if proposal is opened for voting */ modifier voteNotStarted(uint _proposalId) { require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)); _; } /** * @dev Checks if msg.sender is allowed to create proposal under given category */ modifier isAllowed(uint _categoryId) { require(allowedToCreateProposal(_categoryId), "Not allowed"); _; } /** * @dev Checks if msg.sender is allowed categorize proposal under given category */ modifier isAllowedToCategorize() { require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed"); _; } /** * @dev Checks if msg.sender had any pending rewards to be claimed */ modifier checkPendingRewards { require(getPendingReward(msg.sender) == 0, "Claim reward"); _; } /** * @dev Event emitted whenever a proposal is categorized */ event ProposalCategorized( uint indexed proposalId, address indexed categorizedBy, uint categoryId ); /** * @dev Removes delegation of an address. * @param _add address to undelegate. */ function removeDelegation(address _add) external onlyInternal { _unDelegate(_add); } /** * @dev Creates a new proposal * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective */ function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external isAllowed(_categoryId) { require(ms.isMember(msg.sender), "Not Member"); _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); } /** * @dev Edits the details of an existing proposal * @param _proposalId Proposal id that details needs to be updated * @param _proposalDescHash Proposal description hash having long and short description of proposal. */ function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external onlyProposalOwner(_proposalId) { require( allProposalSolutions[_proposalId].length < 2, "Not allowed" ); allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft); allProposalData[_proposalId].category = 0; allProposalData[_proposalId].commonIncentive = 0; emit Proposal( allProposalData[_proposalId].owner, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); } /** * @dev Categorizes proposal to proceed further. Categories shows the proposal objective. */ function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) external voteNotStarted(_proposalId) isAllowedToCategorize { _categorizeProposal(_proposalId, _categoryId, _incentive); } /** * @dev Submit proposal with solution * @param _proposalId Proposal id * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external onlyProposalOwner(_proposalId) { require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution)); _proposalSubmission(_proposalId, _solutionHash, _action); } /** * @dev Creates a new proposal with solution * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external isAllowed(_categoryId) { uint proposalId = totalProposals; _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); require(_categoryId > 0); _proposalSubmission( proposalId, _solutionHash, _action ); } /** * @dev Submit a vote on the proposal. * @param _proposalId to vote upon. * @param _solutionChosen is the chosen vote. */ function submitVote(uint _proposalId, uint _solutionChosen) external { require(allProposalData[_proposalId].propStatus == uint(Governance.ProposalStatus.VotingStarted), "Not allowed"); require(_solutionChosen < allProposalSolutions[_proposalId].length); _submitVote(_proposalId, _solutionChosen); } /** * @dev Closes the proposal. * @param _proposalId of proposal to be closed. */ function closeProposal(uint _proposalId) external { uint category = allProposalData[_proposalId].category; uint _memberRole; if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now && allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } else { require(canCloseProposal(_proposalId) == 1); (, _memberRole,,,,,) = proposalCategory.category(allProposalData[_proposalId].category); if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) { _closeAdvisoryBoardVote(_proposalId, category); } else { _closeMemberVote(_proposalId, category); } } } /** * @dev Claims reward for member. * @param _memberAddress to claim reward of. * @param _maxRecords maximum number of records to claim reward for. _proposals list of proposals of which reward will be claimed. * @return amount of pending reward. */ function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward) { uint voteId; address leader; uint lastUpd; require(msg.sender == ms.getLatestAddress("CR")); uint delegationId = followerDelegation[_memberAddress]; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; uint totalVotes = allVotesByMember[leader].length; uint lastClaimed = totalVotes; uint j; uint i; for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) { voteId = allVotesByMember[leader][i]; proposalId = allVotes[voteId].proposalId; if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) { if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { if (!rewardClaimed[voteId][_memberAddress]) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); rewardClaimed[voteId][_memberAddress] = true; j++; } } else { if (lastClaimed == totalVotes) { lastClaimed = i; } } } } if (lastClaimed == totalVotes) { lastRewardClaimed[_memberAddress] = i; } else { lastRewardClaimed[_memberAddress] = lastClaimed; } if (j > 0) { emit RewardClaimed( _memberAddress, pendingDAppReward ); } } /** * @dev Sets delegation acceptance status of individual user * @param _status delegation acceptance status */ function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards { isOpenForDelegation[msg.sender] = _status; } /** * @dev Delegates vote to an address. * @param _add is the address to delegate vote to. */ function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards { require(ms.masterInitialized()); require(allDelegation[followerDelegation[_add]].leader == address(0)); if (followerDelegation[msg.sender] > 0) { require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now); } require(!alreadyDelegated(msg.sender)); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner))); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard))); require(followerCount[_add] < maxFollowers); if (allVotesByMember[msg.sender].length > 0) { require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime) < now); } require(ms.isMember(_add)); require(isOpenForDelegation[_add]); allDelegation.push(DelegateVote(msg.sender, _add, now)); followerDelegation[msg.sender] = allDelegation.length - 1; leaderDelegation[_add].push(allDelegation.length - 1); followerCount[_add]++; lastRewardClaimed[msg.sender] = allVotesByMember[_add].length; } /** * @dev Undelegates the sender */ function unDelegate() external isMemberAndcheckPause checkPendingRewards { _unDelegate(msg.sender); } /** * @dev Triggers action of accepted proposal after waiting time is finished */ function triggerAction(uint _proposalId) external { require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger"); _triggerAction(_proposalId, allProposalData[_proposalId].category); } /** * @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious */ function rejectAction(uint _proposalId) external { require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now); require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted)); require(!proposalRejectedByAB[_proposalId][msg.sender]); require( keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category)) != keccak256(abi.encodeWithSignature("swapABMember(address,address)")) ); proposalRejectedByAB[_proposalId][msg.sender] = true; actionRejectedCount[_proposalId]++; emit ActionRejected(_proposalId, msg.sender); if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) { proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected); } } /** * @dev Sets intial actionWaitingTime value * To be called after governance implementation has been updated */ function setInitialActionParameters() external onlyOwner { require(!actionParamsInitialised); actionParamsInitialised = true; actionWaitingTime = 24 * 1 hours; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "GOVHOLD") { val = tokenHoldingTime / (1 days); } else if (code == "MAXFOL") { val = maxFollowers; } else if (code == "MAXDRFT") { val = maxDraftTime / (1 days); } else if (code == "EPTIME") { val = ms.pauseTime() / (1 days); } else if (code == "ACWT") { val = actionWaitingTime / (1 hours); } } /** * @dev Gets all details of a propsal * @param _proposalId whose details we want * @return proposalId * @return category * @return status * @return finalVerdict * @return totalReward */ function proposal(uint _proposalId) external view returns ( uint proposalId, uint category, uint status, uint finalVerdict, uint totalRewar ) { return ( _proposalId, allProposalData[_proposalId].category, allProposalData[_proposalId].propStatus, allProposalData[_proposalId].finalVerdict, allProposalData[_proposalId].commonIncentive ); } /** * @dev Gets some details of a propsal * @param _proposalId whose details we want * @return proposalId * @return number of all proposal solutions * @return amount of votes */ function proposalDetails(uint _proposalId) external view returns (uint, uint, uint) { return ( _proposalId, allProposalSolutions[_proposalId].length, proposalVoteTally[_proposalId].voters ); } /** * @dev Gets solution action on a proposal * @param _proposalId whose details we want * @param _solution whose details we want * @return action of a solution on a proposal */ function getSolutionAction(uint _proposalId, uint _solution) external view returns (uint, bytes memory) { return ( _solution, allProposalSolutions[_proposalId][_solution] ); } /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns (uint) { return totalProposals; } /** * @dev Get followers of an address * @return get followers of an address */ function getFollowers(address _add) external view returns (uint[] memory) { return leaderDelegation[_add]; } /** * @dev Gets pending rewards of a member * @param _memberAddress in concern * @return amount of pending reward */ function getPendingReward(address _memberAddress) public view returns (uint pendingDAppReward) { uint delegationId = followerDelegation[_memberAddress]; address leader; uint lastUpd; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) { if (allVotes[allVotesByMember[leader][i]].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) { if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) { proposalId = allVotes[allVotesByMember[leader][i]].proposalId; if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); } } } } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "GOVHOLD") { tokenHoldingTime = val * 1 days; } else if (code == "MAXFOL") { maxFollowers = val; } else if (code == "MAXDRFT") { maxDraftTime = val * 1 days; } else if (code == "EPTIME") { ms.updatePauseTime(val * 1 days); } else if (code == "ACWT") { actionWaitingTime = val * 1 hours; } else { revert("Invalid code"); } } /** * @dev Updates all dependency addresses to latest ones from Master */ function changeDependentContractAddress() public { tokenInstance = TokenController(ms.dAppLocker()); memberRole = MemberRoles(ms.getLatestAddress("MR")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Checks if msg.sender is allowed to create a proposal under given category */ function allowedToCreateProposal(uint category) public view returns (bool check) { if (category == 0) return true; uint[] memory mrAllowed; (,,,, mrAllowed,,) = proposalCategory.category(category); for (uint i = 0; i < mrAllowed.length; i++) { if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i])) return true; } } /** * @dev Checks if an address is already delegated * @param _add in concern * @return bool value if the address is delegated or not */ function alreadyDelegated(address _add) public view returns (bool delegated) { for (uint i = 0; i < leaderDelegation[_add].length; i++) { if (allDelegation[leaderDelegation[_add][i]].leader == _add) { return true; } } } /** * @dev Checks If the proposal voting time is up and it's ready to close * i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise! * @param _proposalId Proposal id to which closing value is being checked */ function canCloseProposal(uint _proposalId) public view returns (uint) { uint dateUpdate; uint pStatus; uint _closingTime; uint _roleId; uint majority; pStatus = allProposalData[_proposalId].propStatus; dateUpdate = allProposalData[_proposalId].dateUpd; (, _roleId, majority, , , _closingTime,) = proposalCategory.category(allProposalData[_proposalId].category); if ( pStatus == uint(ProposalStatus.VotingStarted) ) { uint numberOfMembers = memberRole.numberOfMembers(_roleId); if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers || dateUpdate.add(_closingTime) <= now) { return 1; } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters || dateUpdate.add(_closingTime) <= now) return 1; } } else if (pStatus > uint(ProposalStatus.VotingStarted)) { return 2; } else { return 0; } } /** * @dev Gets Id of member role allowed to categorize the proposal * @return roleId allowed to categorize the proposal */ function allowedToCatgorize() public view returns (uint roleId) { return roleIdAllowedToCatgorize; } /** * @dev Gets vote tally data * @param _proposalId in concern * @param _solution of a proposal id * @return member vote value * @return advisory board vote value * @return amount of votes */ function voteTallyData(uint _proposalId, uint _solution) public view returns (uint, uint, uint) { return (proposalVoteTally[_proposalId].memberVoteValue[_solution], proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters); } /** * @dev Internal call to create proposal * @param _proposalTitle of proposal * @param _proposalSD is short description of proposal * @param _proposalDescHash IPFS hash value of propsal * @param _categoryId of proposal */ function _createProposal( string memory _proposalTitle, string memory _proposalSD, string memory _proposalDescHash, uint _categoryId ) internal { require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0); uint _proposalId = totalProposals; allProposalData[_proposalId].owner = msg.sender; allProposalData[_proposalId].dateUpd = now; allProposalSolutions[_proposalId].push(""); totalProposals++; emit Proposal( msg.sender, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); if (_categoryId > 0) _categorizeProposal(_proposalId, _categoryId, 0); } /** * @dev Internal call to categorize a proposal * @param _proposalId of proposal * @param _categoryId of proposal * @param _incentive is commonIncentive */ function _categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) internal { require( _categoryId > 0 && _categoryId < proposalCategory.totalCategories(), "Invalid category" ); allProposalData[_proposalId].category = _categoryId; allProposalData[_proposalId].commonIncentive = _incentive; allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution); emit ProposalCategorized(_proposalId, msg.sender, _categoryId); } /** * @dev Internal call to add solution to a proposal * @param _proposalId in concern * @param _action on that solution * @param _solutionHash string value */ function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash) internal { allProposalSolutions[_proposalId].push(_action); emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now); } /** * @dev Internal call to add solution and open proposal for voting */ function _proposalSubmission( uint _proposalId, string memory _solutionHash, bytes memory _action ) internal { uint _categoryId = allProposalData[_proposalId].category; if (proposalCategory.categoryActionHashes(_categoryId).length == 0) { require(keccak256(_action) == keccak256("")); proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } _addSolution( _proposalId, _action, _solutionHash ); _updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted)); (, , , , , uint closingTime,) = proposalCategory.category(_categoryId); emit CloseProposalOnTime(_proposalId, closingTime.add(now)); } /** * @dev Internal call to submit vote * @param _proposalId of proposal in concern * @param _solution for that proposal */ function _submitVote(uint _proposalId, uint _solution) internal { uint delegationId = followerDelegation[msg.sender]; uint mrSequence; uint majority; uint closingTime; (, mrSequence, majority, , , closingTime,) = proposalCategory.category(allProposalData[_proposalId].category); require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed"); require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed"); require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) && _checkLastUpd(allDelegation[delegationId].lastUpd))); require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized"); uint totalVotes = allVotes.length; allVotesByMember[msg.sender].push(totalVotes); memberProposalVote[msg.sender][_proposalId] = totalVotes; allVotes.push(ProposalVote(msg.sender, _proposalId, now)); emit Vote(msg.sender, _proposalId, totalVotes, now, _solution); if (mrSequence == uint(MemberRoles.Role.Owner)) { if (_solution == 1) _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner); else _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } else { uint numberOfMembers = memberRole.numberOfMembers(mrSequence); _setVoteTally(_proposalId, _solution, mrSequence); if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) { emit VoteCast(_proposalId); } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters) emit VoteCast(_proposalId); } } } /** * @dev Internal call to set vote tally of a proposal * @param _proposalId of proposal in concern * @param _solution of proposal in concern * @param mrSequence number of members for a role */ function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal { uint categoryABReq; uint isSpecialResolution; (, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category); if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) || mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { proposalVoteTally[_proposalId].abVoteValue[_solution]++; } tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime); if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) { uint voteWeight; uint voters = 1; uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender); uint totalSupply = tokenInstance.totalSupply(); if (isSpecialResolution == 1) { voteWeight = tokenBalance.add(10 ** 18); } else { voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18); } DelegateVote memory delegationData; for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) { delegationData = allDelegation[leaderDelegation[msg.sender][i]]; if (delegationData.leader == msg.sender && _checkLastUpd(delegationData.lastUpd)) { if (memberRole.checkRole(delegationData.follower, mrSequence)) { tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower); tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime); voters++; if (isSpecialResolution == 1) { voteWeight = voteWeight.add(tokenBalance.add(10 ** 18)); } else { voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18)); } } } } proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight); proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters; } } /** * @dev Gets minimum of two numbers * @param a one of the two numbers * @param b one of the two numbers * @return minimum number out of the two */ function _minOf(uint a, uint b) internal pure returns (uint res) { res = a; if (res > b) res = b; } /** * @dev Check the time since last update has exceeded token holding time or not * @param _lastUpd is last update time * @return the bool which tells if the time since last update has exceeded token holding time or not */ function _checkLastUpd(uint _lastUpd) internal view returns (bool) { return (now - _lastUpd) > tokenHoldingTime; } /** * @dev Checks if the vote count against any solution passes the threshold value or not. */ function _checkForThreshold(uint _proposalId, uint _category) internal view returns (bool check) { uint categoryQuorumPerc; uint roleAuthorized; (, roleAuthorized, , categoryQuorumPerc, , ,) = proposalCategory.category(_category); check = ((proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1])) .mul(100)) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18) ) ) >= categoryQuorumPerc; } /** * @dev Called when vote majority is reached * @param _proposalId of proposal in concern * @param _status of proposal in concern * @param category of proposal in concern * @param max vote value of proposal in concern */ function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal { allProposalData[_proposalId].finalVerdict = max; _updateProposalStatus(_proposalId, _status); emit ProposalAccepted(_proposalId); if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) { if (role == MemberRoles.Role.AdvisoryBoard) { _triggerAction(_proposalId, category); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); proposalExecutionTime[_proposalId] = actionWaitingTime.add(now); } } } /** * @dev Internal function to trigger action of accepted proposal */ function _triggerAction(uint _proposalId, uint _categoryId) internal { proposalActionStatus[_proposalId] = uint(ActionStatus.Executed); bytes2 contractName; address actionAddress; bytes memory _functionHash; (, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId); if (contractName == "MS") { actionAddress = address(ms); } else if (contractName != "EX") { actionAddress = ms.getLatestAddress(contractName); } // solhint-disable-next-line avoid-low-level-calls (bool actionStatus,) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1])); if (actionStatus) { emit ActionSuccess(_proposalId); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); emit ActionFailed(_proposalId); } } /** * @dev Internal call to update proposal status * @param _proposalId of proposal in concern * @param _status of proposal to set */ function _updateProposalStatus(uint _proposalId, uint _status) internal { if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) { proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } allProposalData[_proposalId].dateUpd = now; allProposalData[_proposalId].propStatus = _status; } /** * @dev Internal call to undelegate a follower * @param _follower is address of follower to undelegate */ function _unDelegate(address _follower) internal { uint followerId = followerDelegation[_follower]; if (followerId > 0) { followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1); allDelegation[followerId].leader = address(0); allDelegation[followerId].lastUpd = now; lastRewardClaimed[_follower] = allVotesByMember[_follower].length; } } /** * @dev Internal call to close member voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeMemberVote(uint _proposalId, uint category) internal { uint isSpecialResolution; uint abMaj; (, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category); if (isSpecialResolution == 1) { uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18) )); if (acceptedVotePerc >= specialResolutionMajPerc) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } else { if (_checkForThreshold(_proposalId, category)) { uint majorityVote; (,, majorityVote,,,,) = proposalCategory.category(category); if ( ((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)) .div(proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1]) )) >= majorityVote ) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } } else { if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } if (proposalVoteTally[_proposalId].voters > 0) { tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive); } } /** * @dev Internal call to close advisory board voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard; (,, _majorityVote,,,,) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/MasterAware.sol"; import "../cover/QuotationData.sol"; import "./NXMToken.sol"; import "./TokenController.sol"; import "./TokenData.sol"; contract TokenFunctions is MasterAware { using SafeMath for uint; TokenController public tc; NXMToken public tk; QuotationData public qd; event BurnCATokens(uint claimId, address addr, uint amount); /** * @dev to get the all the cover locked tokens of a user * @param _of is the user address in concern * @return amount locked */ function getUserAllLockedCNTokens(address _of) external view returns (uint) { uint[] memory coverIds = qd.getAllCoversOfUser(_of); uint total; for (uint i = 0; i < coverIds.length; i++) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverIds[i])); uint coverNote = tc.tokensLocked(_of, reason); total = total.add(coverNote); } return total; } /** * @dev Change Dependent Contract Address */ function changeDependentContractAddress() public { tc = TokenController(master.getLatestAddress("TC")); tk = NXMToken(master.tokenAddress()); qd = QuotationData(master.getLatestAddress("QD")); } /** * @dev Burns tokens used for fraudulent voting against a claim * @param claimid Claim Id. * @param _value number of tokens to be burned * @param _of Claim Assessor's address. */ function burnCAToken(uint claimid, uint _value, address _of) external onlyGovernance { tc.burnLockedTokens(_of, "CLA", _value); emit BurnCATokens(claimid, _of, _value); } /** * @dev to check if a member is locked for member vote * @param _of is the member address in concern * @return the boolean status */ function isLockedForMemberVote(address _of) public view returns (bool) { return now < tk.isLockedForMV(_of); } } /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "../capital/Pool.sol"; import "../claims/ClaimsReward.sol"; import "../token/NXMToken.sol"; import "../token/TokenController.sol"; import "../token/TokenFunctions.sol"; import "./ClaimsData.sol"; import "./Incidents.sol"; contract Claims is Iupgradable { using SafeMath for uint; TokenController internal tc; ClaimsReward internal cr; Pool internal p1; ClaimsData internal cd; TokenData internal td; QuotationData internal qd; Incidents internal incidents; uint private constant DECIMAL1E18 = uint(10) ** 18; /** * @dev Sets the status of claim using claim id. * @param claimId claim id. * @param stat status to be set. */ function setClaimStatus(uint claimId, uint stat) external onlyInternal { _setClaimStatus(claimId, stat); } /** * @dev Calculates total amount that has been used to assess a claim. * Computaion:Adds acceptCA(tokens used for voting in favor of a claim) * denyCA(tokens used for voting against a claim) * current token price. * @param claimId Claim Id. * @param member Member type 0 -> Claim Assessors, else members. * @return tokens Total Amount used in Claims assessment. */ function getCATokens(uint claimId, uint member) external view returns (uint tokens) { uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 currency = qd.getCurrencyOfCover(coverId); address asset = cr.getCurrencyAssetAddress(currency); uint tokenx1e18 = p1.getTokenPrice(asset); uint accept; uint deny; if (member == 0) { (, accept, deny) = cd.getClaimsTokenCA(claimId); } else { (, accept, deny) = cd.getClaimsTokenMV(claimId); } tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens) } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); p1 = Pool(ms.getLatestAddress("P1")); cr = ClaimsReward(ms.getLatestAddress("CR")); cd = ClaimsData(ms.getLatestAddress("CD")); qd = QuotationData(ms.getLatestAddress("QD")); incidents = Incidents(ms.getLatestAddress("IC")); } /** * @dev Submits a claim for a given cover note. * Adds claim to queue incase of emergency pause else directly submits the claim. * @param coverId Cover Id. */ function submitClaim(uint coverId) external { _submitClaim(coverId, msg.sender); } function submitClaimForMember(uint coverId, address member) external onlyInternal { _submitClaim(coverId, member); } function _submitClaim(uint coverId, address member) internal { require(!ms.isPause(), "Claims: System is paused"); (/* id */, address contractAddress) = qd.getscAddressOfCover(coverId); address token = incidents.coveredToken(contractAddress); require(token == address(0), "Claims: Product type does not allow claims"); address coverOwner = qd.getCoverMemberAddress(coverId); require(coverOwner == member, "Claims: Not cover owner"); uint expirationDate = qd.getValidityOfCover(coverId); uint gracePeriod = tc.claimSubmissionGracePeriod(); require(expirationDate.add(gracePeriod) > now, "Claims: Grace period has expired"); tc.markCoverClaimOpen(coverId); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted)); uint claimId = cd.actualClaimLength(); cd.addClaim(claimId, coverId, coverOwner, now); cd.callClaimEvent(coverId, coverOwner, claimId, now); } // solhint-disable-next-line no-empty-blocks function submitClaimAfterEPOff() external pure {} /** * @dev Castes vote for members who have tokens locked under Claims Assessment * @param claimId claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict); uint voteLength = cd.getAllVoteLength(); cd.addClaimVoteCA(claimId, voteLength); cd.setUserClaimVoteCA(msg.sender, claimId, voteLength); cd.setClaimTokensCA(claimId, verdict, tokens); tc.extendLockOf(msg.sender, "CLA", td.lockCADays()); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Submits a member vote for assessing a claim. * Tokens other than those locked under Claims * Assessment can be used to cast a vote for a given claim id. * @param claimId Selected claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); uint stat; uint tokens = tc.totalBalanceOf(msg.sender); (, stat) = cd.getClaimStatusNumber(claimId); require(stat >= 1 && stat <= 5); require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict); tc.lockForMemberVote(msg.sender, td.lockMVDays()); uint voteLength = cd.getAllVoteLength(); cd.addClaimVotemember(claimId, voteLength); cd.setUserClaimVoteMember(msg.sender, claimId, voteLength); cd.setClaimTokensMV(claimId, verdict, tokens); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } // solhint-disable-next-line no-empty-blocks function pauseAllPendingClaimsVoting() external pure {} // solhint-disable-next-line no-empty-blocks function startAllPendingClaimsVoting() external pure {} /** * @dev Checks if voting of a claim should be closed or not. * @param claimId Claim Id. * @return close 1 -> voting should be closed, 0 -> if voting should not be closed, * -1 -> voting has already been closed. */ function checkVoteClosing(uint claimId) public view returns (int8 close) { close = 0; uint status; (, status) = cd.getClaimStatusNumber(claimId); uint dateUpd = cd.getClaimDateUpd(claimId); if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) { if (cd.getClaimState12Count(claimId) < 60) close = 1; } if (status > 5 && status != 12) { close = - 1; } else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) { close = 1; } else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) { close = 0; } else if (status == 0 || (status >= 1 && status <= 5)) { close = _checkVoteClosingFinal(claimId, status); } } /** * @dev Checks if voting of a claim should be closed or not. * Internally called by checkVoteClosing method * for Claims whose status number is 0 or status number lie between 2 and 6. * @param claimId Claim Id. * @param status Current status of claim. * @return close 1 if voting should be closed,0 in case voting should not be closed, * -1 if voting has already been closed. */ function _checkVoteClosingFinal(uint claimId, uint status) internal view returns (int8 close) { close = 0; uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 currency = qd.getCurrencyOfCover(coverId); address asset = cr.getCurrencyAssetAddress(currency); uint tokenx1e18 = p1.getTokenPrice(asset); uint accept; uint deny; (, accept, deny) = cd.getClaimsTokenCA(claimId); uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); (, accept, deny) = cd.getClaimsTokenMV(claimId); uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); if (status == 0 && caTokens >= sumassured.mul(10)) { close = 1; } else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) { close = 1; } } /** * @dev Changes the status of an existing claim id, based on current * status and current conditions of the system * @param claimId Claim Id. * @param stat status number. */ function _setClaimStatus(uint claimId, uint stat) internal { uint origstat; uint state12Count; uint dateUpd; uint coverId; (, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId); (, origstat) = cd.getClaimStatusNumber(claimId); if (stat == 12 && origstat == 12) { cd.updateState12Count(claimId, 1); } cd.setClaimStatus(claimId, stat); if (state12Count >= 60 && stat == 12) { cd.setClaimStatus(claimId, 13); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied)); } cd.setClaimdateUpd(claimId, now); } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "../claims/ClaimsReward.sol"; import "../cover/QuotationData.sol"; import "../token/TokenController.sol"; import "../token/TokenData.sol"; import "../token/TokenFunctions.sol"; import "./Governance.sol"; import "./external/Governed.sol"; contract MemberRoles is Governed, Iupgradable { TokenController public tc; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; TokenFunctions internal tf; NXMToken public tk; struct MemberRoleDetails { uint memberCounter; mapping(address => bool) memberActive; address[] memberAddress; address authorized; } enum Role {UnAssigned, AdvisoryBoard, Member, Owner} event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription); event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp); event ClaimPayoutAddressSet(address indexed member, address indexed payoutAddress); MemberRoleDetails[] internal memberRoleData; bool internal constructorCheck; uint public maxABCount; bool public launched; uint public launchedOn; mapping (address => address payable) internal claimPayoutAddress; modifier checkRoleAuthority(uint _memberRoleId) { if (memberRoleData[_memberRoleId].authorized != address(0)) require(msg.sender == memberRoleData[_memberRoleId].authorized); else require(isAuthorizedToGovern(msg.sender), "Not Authorized"); _; } /** * @dev to swap advisory board member * @param _newABAddress is address of new AB member * @param _removeAB is advisory board member to be removed */ function swapABMember( address _newABAddress, address _removeAB ) external checkRoleAuthority(uint(Role.AdvisoryBoard)) { _updateRole(_newABAddress, uint(Role.AdvisoryBoard), true); _updateRole(_removeAB, uint(Role.AdvisoryBoard), false); } /** * @dev to swap the owner address * @param _newOwnerAddress is the new owner address */ function swapOwner( address _newOwnerAddress ) external { require(msg.sender == address(ms)); _updateRole(ms.owner(), uint(Role.Owner), false); _updateRole(_newOwnerAddress, uint(Role.Owner), true); } /** * @dev is used to add initital advisory board members * @param abArray is the list of initial advisory board members */ function addInitialABMembers(address[] calldata abArray) external onlyOwner { //Ensure that NXMaster has initialized. require(ms.masterInitialized()); require(maxABCount >= SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length) ); //AB count can't exceed maxABCount for (uint i = 0; i < abArray.length; i++) { require(checkRole(abArray[i], uint(MemberRoles.Role.Member))); _updateRole(abArray[i], uint(Role.AdvisoryBoard), true); } } /** * @dev to change max number of AB members allowed * @param _val is the new value to be set */ function changeMaxABCount(uint _val) external onlyInternal { maxABCount = _val; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { td = TokenData(ms.getLatestAddress("TD")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); tf = TokenFunctions(ms.getLatestAddress("TF")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); } /** * @dev to change the master address * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) { require(masterAddress == msg.sender); } masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev to initiate the member roles * @param _firstAB is the address of the first AB member * @param memberAuthority is the authority (role) of the member */ function memberRolesInitiate(address _firstAB, address memberAuthority) public { require(!constructorCheck); _addInitialMemberRoles(_firstAB, memberAuthority); constructorCheck = true; } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole(//solhint-disable-line bytes32 _roleName, string memory _roleDescription, address _authorized ) public onlyAuthorizedToGovern { _addRole(_roleName, _roleDescription, _authorized); } /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole(//solhint-disable-line address _memberAddress, uint _roleId, bool _active ) public checkRoleAuthority(_roleId) { _updateRole(_memberAddress, _roleId, _active); } /** * @dev to add members before launch * @param userArray is list of addresses of members * @param tokens is list of tokens minted for each array element */ function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner { require(!launched); for (uint i = 0; i < userArray.length; i++) { require(!ms.isMember(userArray[i])); tc.addToWhitelist(userArray[i]); _updateRole(userArray[i], uint(Role.Member), true); tc.mint(userArray[i], tokens[i]); } launched = true; launchedOn = now; } /** * @dev Called by user to pay joining membership fee */ function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); tc.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } } /** * @dev to perform kyc verdict * @param _userAddress whose kyc is being performed * @param verdict of kyc process */ function kycVerdict(address payable _userAddress, bool verdict) public { require(msg.sender == qd.kycAuthAddress()); require(!ms.isPause()); require(_userAddress != address(0)); require(!ms.isMember(_userAddress)); require(qd.refundEligible(_userAddress)); if (verdict) { qd.setRefundEligible(_userAddress, false); uint fee = td.joiningFee(); tc.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(fee); // solhint-disable-line } else { qd.setRefundEligible(_userAddress, false); _userAddress.transfer(td.joiningFee()); // solhint-disable-line } } /** * @dev withdraws membership for msg.sender if currently a member. */ function withdrawMembership() public { require(!ms.isPause() && ms.isMember(msg.sender)); require(tc.totalLockedBalance(msg.sender) == 0); // solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). gv.removeDelegation(msg.sender); tc.burnFrom(msg.sender, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); tc.removeFromWhitelist(msg.sender); // need clarification on whitelist if (claimPayoutAddress[msg.sender] != address(0)) { claimPayoutAddress[msg.sender] = address(0); emit ClaimPayoutAddressSet(msg.sender, address(0)); } } /** * @dev switches membership for msg.sender to the specified address. * @param newAddress address of user to forward membership. */ function switchMembership(address newAddress) external { _switchMembership(msg.sender, newAddress); tk.transferFrom(msg.sender, newAddress, tk.balanceOf(msg.sender)); } function switchMembershipOf(address member, address newAddress) external onlyInternal { _switchMembership(member, newAddress); } /** * @dev switches membership for member to the specified address. * @param newAddress address of user to forward membership. */ function _switchMembership(address member, address newAddress) internal { require(!ms.isPause() && ms.isMember(member) && !ms.isMember(newAddress)); require(tc.totalLockedBalance(member) == 0); // solhint-disable-line require(!tf.isLockedForMemberVote(member)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(member) == 0); // No pending reward to be claimed(claim assesment). gv.removeDelegation(member); tc.addToWhitelist(newAddress); _updateRole(newAddress, uint(Role.Member), true); _updateRole(member, uint(Role.Member), false); tc.removeFromWhitelist(member); address payable previousPayoutAddress = claimPayoutAddress[member]; if (previousPayoutAddress != address(0)) { address payable storedAddress = previousPayoutAddress == newAddress ? address(0) : previousPayoutAddress; claimPayoutAddress[member] = address(0); claimPayoutAddress[newAddress] = storedAddress; // emit event for old address reset emit ClaimPayoutAddressSet(member, address(0)); if (storedAddress != address(0)) { // emit event for setting the payout address on the new member address if it's non zero emit ClaimPayoutAddressSet(newAddress, storedAddress); } } emit switchedMembership(member, newAddress, now); } function getClaimPayoutAddress(address payable _member) external view returns (address payable) { address payable payoutAddress = claimPayoutAddress[_member]; return payoutAddress != address(0) ? payoutAddress : _member; } function setClaimPayoutAddress(address payable _address) external { require(!ms.isPause(), "system is paused"); require(ms.isMember(msg.sender), "sender is not a member"); require(_address != msg.sender, "should be different than the member address"); claimPayoutAddress[msg.sender] = _address; emit ClaimPayoutAddressSet(msg.sender, _address); } /// @dev Return number of member roles function totalRoles() public view returns (uint256) {//solhint-disable-line return memberRoleData.length; } /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _newAuthorized New authorized address against role id function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) {//solhint-disable-line memberRoleData[_roleId].authorized = _newAuthorized; } /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line uint length = memberRoleData[_memberRoleId].memberAddress.length; uint i; uint j = 0; memberArray = new address[](memberRoleData[_memberRoleId].memberCounter); for (i = 0; i < length; i++) { address member = memberRoleData[_memberRoleId].memberAddress[i]; if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) {//solhint-disable-line memberArray[j] = member; j++; } } return (_memberRoleId, memberArray); } /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberCounter Member length function numberOfMembers(uint _memberRoleId) public view returns (uint) {//solhint-disable-line return memberRoleData[_memberRoleId].memberCounter; } /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns (address) {//solhint-disable-line return memberRoleData[_memberRoleId].authorized; } /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line uint length = memberRoleData.length; uint[] memory assignedRoles = new uint[](length); uint counter = 0; for (uint i = 1; i < length; i++) { if (memberRoleData[i].memberActive[_memberAddress]) { assignedRoles[counter] = i; counter++; } } return assignedRoles; } /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns (bool) {//solhint-disable-line if (_roleId == uint(Role.UnAssigned)) return true; else if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line return true; else return false; } /// @dev Return total number of members assigned against each role id. /// @return totalMembers Total members in particular role id function getMemberLengthForAllRoles() public view returns (uint[] memory totalMembers) {//solhint-disable-line totalMembers = new uint[](memberRoleData.length); for (uint i = 0; i < memberRoleData.length; i++) { totalMembers[i] = numberOfMembers(i); } } /** * @dev to update the member roles * @param _memberAddress in concern * @param _roleId the id of role * @param _active if active is true, add the member, else remove it */ function _updateRole(address _memberAddress, uint _roleId, bool _active) internal { // require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically"); if (_active) { require(!memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1); memberRoleData[_roleId].memberActive[_memberAddress] = true; memberRoleData[_roleId].memberAddress.push(_memberAddress); } else { require(memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1); delete memberRoleData[_roleId].memberActive[_memberAddress]; } } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function _addRole( bytes32 _roleName, string memory _roleDescription, address _authorized ) internal { emit MemberRole(memberRoleData.length, _roleName, _roleDescription); memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized)); } /** * @dev to check if member is in the given member array * @param _memberAddress in concern * @param memberArray in concern * @return boolean to represent the presence */ function _checkMemberInArray( address _memberAddress, address[] memory memberArray ) internal pure returns (bool memberExists) { uint i; for (i = 0; i < memberArray.length; i++) { if (memberArray[i] == _memberAddress) { memberExists = true; break; } } } /** * @dev to add initial member roles * @param _firstAB is the member address to be added * @param memberAuthority is the member authority(role) to be added for */ function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal { maxABCount = 5; _addRole("Unassigned", "Unassigned", address(0)); _addRole( "Advisory Board", "Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line address(0) ); _addRole( "Member", "Represents all users of Mutual.", //solhint-disable-line memberAuthority ); _addRole( "Owner", "Represents Owner of Mutual.", //solhint-disable-line address(0) ); // _updateRole(_firstAB, uint(Role.AdvisoryBoard), true); _updateRole(_firstAB, uint(Role.Owner), true); // _updateRole(_firstAB, uint(Role.Member), true); launchedOn = 0; } function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) { address memberAddress = memberRoleData[_memberRoleId].memberAddress[index]; return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]); } function membersLength(uint _memberRoleId) external view returns (uint) { return memberRoleData[_memberRoleId].memberAddress.length; } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; import "../../abstract/Iupgradable.sol"; import "./MemberRoles.sol"; import "./external/Governed.sol"; import "./external/IProposalCategory.sol"; contract ProposalCategory is Governed, IProposalCategory, Iupgradable { bool public constructorCheck; MemberRoles internal mr; struct CategoryStruct { uint memberRoleToVote; uint majorityVotePerc; uint quorumPerc; uint[] allowedToCreateProposal; uint closingTime; uint minStake; } struct CategoryAction { uint defaultIncentive; address contractAddress; bytes2 contractName; } CategoryStruct[] internal allCategory; mapping(uint => CategoryAction) internal categoryActionData; mapping(uint => uint) public categoryABReq; mapping(uint => uint) public isSpecialResolution; mapping(uint => bytes) public categoryActionHashes; bool public categoryActionHashUpdated; /** * @dev Adds new category (Discontinued, moved functionality to newCategory) * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external {} /** * @dev Initiates Default settings for Proposal Category contract (Adding default categories) */ function proposalCategoryInitiate() external {} /** * @dev Initiates Default action function hashes for existing categories * To be called after the contract has been upgraded by governance */ function updateCategoryActionHashes() external onlyOwner { require(!categoryActionHashUpdated, "Category action hashes already updated"); categoryActionHashUpdated = true; categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)"); categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)"); categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)"); categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()"); categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)"); categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)"); categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)"); categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)"); categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)"); // solhint-disable-line categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)"); categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)"); categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)"); categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)"); categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)"); categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)"); categoryActionHashes[29] = abi.encodeWithSignature("upgradeMultipleContracts(bytes2[],address[])"); categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)"); categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)"); categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)"); // solhint-disable-line categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()"); } /** * @dev Gets Total number of categories added till now */ function totalCategories() external view returns (uint) { return allCategory.length; } /** * @dev Gets category details */ function category(uint _categoryId) external view returns (uint, uint, uint, uint, uint[] memory, uint, uint) { return ( _categoryId, allCategory[_categoryId].memberRoleToVote, allCategory[_categoryId].majorityVotePerc, allCategory[_categoryId].quorumPerc, allCategory[_categoryId].allowedToCreateProposal, allCategory[_categoryId].closingTime, allCategory[_categoryId].minStake ); } /** * @dev Gets category ab required and isSpecialResolution * @return the category id * @return if AB voting is required * @return is category a special resolution */ function categoryExtendedData(uint _categoryId) external view returns (uint, uint, uint) { return ( _categoryId, categoryABReq[_categoryId], isSpecialResolution[_categoryId] ); } /** * @dev Gets the category acion details * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive */ function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) { return ( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); } /** * @dev Gets the category acion details of a category id * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive * @return action function hash */ function categoryActionDetails(uint _categoryId) external view returns (uint, address, bytes2, uint, bytes memory) { return ( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive, categoryActionHashes[_categoryId] ); } /** * @dev Updates dependant contract addresses */ function changeDependentContractAddress() public { mr = MemberRoles(ms.getLatestAddress("MR")); } /** * @dev Adds new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function newCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } _addCategory( _name, _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _actionHash, _contractAddress, _contractName, _incentives ); if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash); } } /** * @dev Changes the master address and update it's instance * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev Updates category details (Discontinued, moved functionality to editCategory) * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public {} /** * @dev Updates category details * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function editCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } delete categoryActionHashes[_categoryId]; if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash); } allCategory[_categoryId].memberRoleToVote = _memberRoleToVote; allCategory[_categoryId].majorityVotePerc = _majorityVotePerc; allCategory[_categoryId].closingTime = _closingTime; allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal; allCategory[_categoryId].minStake = _incentives[0]; allCategory[_categoryId].quorumPerc = _quorumPerc; categoryActionData[_categoryId].defaultIncentive = _incentives[1]; categoryActionData[_categoryId].contractName = _contractName; categoryActionData[_categoryId].contractAddress = _contractAddress; categoryABReq[_categoryId] = _incentives[2]; isSpecialResolution[_categoryId] = _incentives[3]; emit Category(_categoryId, _name, _actionHash); } /** * @dev Internal call to add new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function _addCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) internal { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); allCategory.push( CategoryStruct( _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _incentives[0] ) ); uint categoryId = allCategory.length - 1; categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName); categoryABReq[categoryId] = _incentives[2]; isSpecialResolution[categoryId] = _incentives[3]; emit Category(categoryId, _name, _actionHash); } /** * @dev Internal call to check if given roles are valid or not */ function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal) internal view returns (uint) { uint totalRoles = mr.totalRoles(); if (_memberRoleToVote >= totalRoles) { return 0; } for (uint i = 0; i < _allowedToCreateProposal.length; i++) { if (_allowedToCreateProposal[i] >= totalRoles) { return 0; } } return 1; } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Edits the details of an existing proposal and creates new version /// @param _proposalId Proposal id that details needs to be updated /// @param _proposalDescHash Proposal description hash having long and short description of proposal. function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward); function proposal(uint _proposalId) external view returns ( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns (uint closeValue); function allowedToCatgorize() public view returns (uint roleId); } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; interface IMaster { function getLatestAddress(bytes2 _module) external view returns (address); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns (bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity ^0.5.0; contract IProposalCategory { event Category( uint indexed categoryId, string categoryName, string actionHash ); /// @dev Adds new category /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external; /// @dev gets category details function category(uint _categoryId) external view returns ( uint categoryId, uint memberRoleToVote, uint majorityVotePerc, uint quorumPerc, uint[] memory allowedToCreateProposal, uint closingTime, uint minStake ); ///@dev gets category action details function categoryAction(uint _categoryId) external view returns ( uint categoryId, address contractAddress, bytes2 contractName, uint defaultIncentive ); /// @dev Gets Total number of categories added till now function totalCategories() external view returns (uint numberOfCategories); /// @dev Updates category details /// @param _categoryId Category id that needs to be updated /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public; }
Submits a claim for a given cover note. Adds claim to queue incase of emergency pause else directly submits the claim. coverId Cover Id./
function submitClaim(uint coverId) external { _submitClaim(coverId, msg.sender); }
2,578,466
./full_match/80001/0xD47F180386148eC00262C3492b39b162afBF9813/sources/project_/contracts/registry/implementation/IdentityRegistry.sol
See {IIdentityRegistry-contains}./
function contains(address _userAddress) external view override returns (bool) { if (address(identity(_userAddress)) == address(0)) { return false; } return true; }
5,567,202
./full_match/1/0xA4c4808777c16F5A846C92173592272198103DaE/sources/contracts/RockPaperScissors_V8.sol
check if amount > minBetTokenAmount check if currency is not a zeroAddress protect from private game self-connection return new game id transfer tokens to contract
function createGame( bytes32 hiddenMove, address currency, uint256 amount, address playerB ) external { if (amount < minBetAmount) revert InvalidBetAmount(); if (currency == address(0)) revert ZeroAddress(); if (msg.sender == playerB) revert AlreadyConnected(); uint256 gameId = _addGameData( msg.sender, hiddenMove, currency, amount, playerB ); IERC20(currency).safeTransferFrom(msg.sender, address(this), amount); emit GameCreated(gameId, msg.sender, currency); }
3,130,738
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.9; import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/ProtoBufRuntime.sol"; import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/GoogleProtobufAny.sol"; import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/Client.sol"; library ClientState { //struct definition struct Data { Height.Data latest_height; Height.Data frozen_height; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_latest_height(pointer, bs, r); } else if (fieldId == 2) { pointer += _read_frozen_height(pointer, bs, r); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_latest_height( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (Height.Data memory x, uint256 sz) = _decode_Height(p, bs); r.latest_height = x; return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_frozen_height( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (Height.Data memory x, uint256 sz) = _decode_Height(p, bs); r.frozen_height = x; return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Height(uint256 p, bytes memory bs) internal pure returns (Height.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Height.Data memory r, ) = Height._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.latest_height, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.frozen_height, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.latest_height)); e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.frozen_height)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { Height.store(input.latest_height, output.latest_height); Height.store(input.frozen_height, output.frozen_height); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ClientState library ConsensusState { //struct definition struct Data { bytes[] addresses; string diversifier; uint64 timestamp; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_unpacked_repeated_addresses(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_diversifier(pointer, bs, r); } else if (fieldId == 3) { pointer += _read_timestamp(pointer, bs, r); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } pointer = offset; if (counters[1] > 0) { require(r.addresses.length == 0); r.addresses = new bytes[](counters[1]); } while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_unpacked_repeated_addresses(pointer, bs, r, counters); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_unpacked_repeated_addresses( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.addresses[r.addresses.length - counters[1]] = x; counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_diversifier( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); r.diversifier = x; return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); r.timestamp = x; return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.addresses.length != 0) { for(i = 0; i < r.addresses.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += ProtoBufRuntime._encode_bytes(r.addresses[i], pointer, bs); } } if (bytes(r.diversifier).length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.diversifier, pointer, bs); } if (r.timestamp != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.addresses.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(r.addresses[i].length); } e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.diversifier).length); e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.addresses.length != 0) { return false; } if (bytes(r.diversifier).length != 0) { return false; } if (r.timestamp != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.addresses = input.addresses; output.diversifier = input.diversifier; output.timestamp = input.timestamp; } //array helpers for Addresses /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addAddresses(Data memory self, bytes memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ bytes[] memory tmp = new bytes[](self.addresses.length + 1); for (uint256 i = 0; i < self.addresses.length; i++) { tmp[i] = self.addresses[i]; } tmp[self.addresses.length] = value; self.addresses = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ConsensusState library Header { //struct definition struct Data { Height.Data height; uint64 timestamp; MultiSignature.Data signature; bytes[] new_addresses; string new_diversifier; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[6] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, r); } else if (fieldId == 2) { pointer += _read_timestamp(pointer, bs, r); } else if (fieldId == 3) { pointer += _read_signature(pointer, bs, r); } else if (fieldId == 4) { pointer += _read_unpacked_repeated_new_addresses(pointer, bs, nil(), counters); } else if (fieldId == 5) { pointer += _read_new_diversifier(pointer, bs, r); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } pointer = offset; if (counters[4] > 0) { require(r.new_addresses.length == 0); r.new_addresses = new bytes[](counters[4]); } while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 4) { pointer += _read_unpacked_repeated_new_addresses(pointer, bs, r, counters); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (Height.Data memory x, uint256 sz) = _decode_Height(p, bs); r.height = x; return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); r.timestamp = x; return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_signature( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (MultiSignature.Data memory x, uint256 sz) = _decode_MultiSignature(p, bs); r.signature = x; return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_unpacked_repeated_new_addresses( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.new_addresses[r.new_addresses.length - counters[4]] = x; counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_new_diversifier( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); r.new_diversifier = x; return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Height(uint256 p, bytes memory bs) internal pure returns (Height.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Height.Data memory r, ) = Height._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_MultiSignature(uint256 p, bytes memory bs) internal pure returns (MultiSignature.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (MultiSignature.Data memory r, ) = MultiSignature._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.height, pointer, bs); if (r.timestamp != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += MultiSignature._encode_nested(r.signature, pointer, bs); if (r.new_addresses.length != 0) { for(i = 0; i < r.new_addresses.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += ProtoBufRuntime._encode_bytes(r.new_addresses[i], pointer, bs); } } if (bytes(r.new_diversifier).length != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.new_diversifier, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.height)); e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp); e += 1 + ProtoBufRuntime._sz_lendelim(MultiSignature._estimate(r.signature)); for(i = 0; i < r.new_addresses.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(r.new_addresses[i].length); } e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.new_diversifier).length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.timestamp != 0) { return false; } if (r.new_addresses.length != 0) { return false; } if (bytes(r.new_diversifier).length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { Height.store(input.height, output.height); output.timestamp = input.timestamp; MultiSignature.store(input.signature, output.signature); output.new_addresses = input.new_addresses; output.new_diversifier = input.new_diversifier; } //array helpers for NewAddresses /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addNewAddresses(Data memory self, bytes memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ bytes[] memory tmp = new bytes[](self.new_addresses.length + 1); for (uint256 i = 0; i < self.new_addresses.length; i++) { tmp[i] = self.new_addresses[i]; } tmp[self.new_addresses.length] = value; self.new_addresses = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Header library MultiSignature { //struct definition struct Data { bytes[] signatures; uint64 timestamp; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_unpacked_repeated_signatures(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_timestamp(pointer, bs, r); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } pointer = offset; if (counters[1] > 0) { require(r.signatures.length == 0); r.signatures = new bytes[](counters[1]); } while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_unpacked_repeated_signatures(pointer, bs, r, counters); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_unpacked_repeated_signatures( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.signatures[r.signatures.length - counters[1]] = x; counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); r.timestamp = x; return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.signatures.length != 0) { for(i = 0; i < r.signatures.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += ProtoBufRuntime._encode_bytes(r.signatures[i], pointer, bs); } } if (r.timestamp != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.signatures.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(r.signatures[i].length); } e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.signatures.length != 0) { return false; } if (r.timestamp != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.signatures = input.signatures; output.timestamp = input.timestamp; } //array helpers for Signatures /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addSignatures(Data memory self, bytes memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ bytes[] memory tmp = new bytes[](self.signatures.length + 1); for (uint256 i = 0; i < self.signatures.length; i++) { tmp[i] = self.signatures[i]; } tmp[self.signatures.length] = value; self.signatures = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library MultiSignature library SignBytes { //enum definition // Solidity enum definitions enum DataType { DATA_TYPE_UNINITIALIZED_UNSPECIFIED, DATA_TYPE_CLIENT_STATE, DATA_TYPE_CONSENSUS_STATE, DATA_TYPE_CONNECTION_STATE, DATA_TYPE_CHANNEL_STATE, DATA_TYPE_PACKET_COMMITMENT, DATA_TYPE_PACKET_ACKNOWLEDGEMENT, DATA_TYPE_PACKET_RECEIPT_ABSENCE, DATA_TYPE_NEXT_SEQUENCE_RECV, DATA_TYPE_HEADER } // Solidity enum encoder function encode_DataType(DataType x) internal pure returns (int32) { if (x == DataType.DATA_TYPE_UNINITIALIZED_UNSPECIFIED) { return 0; } if (x == DataType.DATA_TYPE_CLIENT_STATE) { return 1; } if (x == DataType.DATA_TYPE_CONSENSUS_STATE) { return 2; } if (x == DataType.DATA_TYPE_CONNECTION_STATE) { return 3; } if (x == DataType.DATA_TYPE_CHANNEL_STATE) { return 4; } if (x == DataType.DATA_TYPE_PACKET_COMMITMENT) { return 5; } if (x == DataType.DATA_TYPE_PACKET_ACKNOWLEDGEMENT) { return 6; } if (x == DataType.DATA_TYPE_PACKET_RECEIPT_ABSENCE) { return 7; } if (x == DataType.DATA_TYPE_NEXT_SEQUENCE_RECV) { return 8; } if (x == DataType.DATA_TYPE_HEADER) { return 9; } revert(); } // Solidity enum decoder function decode_DataType(int64 x) internal pure returns (DataType) { if (x == 0) { return DataType.DATA_TYPE_UNINITIALIZED_UNSPECIFIED; } if (x == 1) { return DataType.DATA_TYPE_CLIENT_STATE; } if (x == 2) { return DataType.DATA_TYPE_CONSENSUS_STATE; } if (x == 3) { return DataType.DATA_TYPE_CONNECTION_STATE; } if (x == 4) { return DataType.DATA_TYPE_CHANNEL_STATE; } if (x == 5) { return DataType.DATA_TYPE_PACKET_COMMITMENT; } if (x == 6) { return DataType.DATA_TYPE_PACKET_ACKNOWLEDGEMENT; } if (x == 7) { return DataType.DATA_TYPE_PACKET_RECEIPT_ABSENCE; } if (x == 8) { return DataType.DATA_TYPE_NEXT_SEQUENCE_RECV; } if (x == 9) { return DataType.DATA_TYPE_HEADER; } revert(); } /** * @dev The estimator for an packed enum array * @return The number of bytes encoded */ function estimate_packed_repeated_DataType( DataType[] memory a ) internal pure returns (uint256) { uint256 e = 0; for (uint i = 0; i < a.length; i++) { e += ProtoBufRuntime._sz_enum(encode_DataType(a[i])); } return e; } //struct definition struct Data { Height.Data height; uint64 timestamp; string diversifier; SignBytes.DataType data_type; bytes data; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, r); } else if (fieldId == 2) { pointer += _read_timestamp(pointer, bs, r); } else if (fieldId == 3) { pointer += _read_diversifier(pointer, bs, r); } else if (fieldId == 4) { pointer += _read_data_type(pointer, bs, r); } else if (fieldId == 5) { pointer += _read_data(pointer, bs, r); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (Height.Data memory x, uint256 sz) = _decode_Height(p, bs); r.height = x; return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); r.timestamp = x; return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_diversifier( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); r.diversifier = x; return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_data_type( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); SignBytes.DataType x = decode_DataType(tmp); r.data_type = x; return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_data( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); r.data = x; return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Height(uint256 p, bytes memory bs) internal pure returns (Height.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Height.Data memory r, ) = Height._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Height._encode_nested(r.height, pointer, bs); if (r.timestamp != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.timestamp, pointer, bs); } if (bytes(r.diversifier).length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.diversifier, pointer, bs); } if (uint(r.data_type) != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_data_type = encode_DataType(r.data_type); pointer += ProtoBufRuntime._encode_enum(_enum_data_type, pointer, bs); } if (r.data.length != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.data, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.height)); e += 1 + ProtoBufRuntime._sz_uint64(r.timestamp); e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.diversifier).length); e += 1 + ProtoBufRuntime._sz_enum(encode_DataType(r.data_type)); e += 1 + ProtoBufRuntime._sz_lendelim(r.data.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.timestamp != 0) { return false; } if (bytes(r.diversifier).length != 0) { return false; } if (uint(r.data_type) != 0) { return false; } if (r.data.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { Height.store(input.height, output.height); output.timestamp = input.timestamp; output.diversifier = input.diversifier; output.data_type = input.data_type; output.data = input.data; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library SignBytes library HeaderData { //struct definition struct Data { bytes[] new_addresses; string new_diversifier; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_unpacked_repeated_new_addresses(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_new_diversifier(pointer, bs, r); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } pointer = offset; if (counters[1] > 0) { require(r.new_addresses.length == 0); r.new_addresses = new bytes[](counters[1]); } while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_unpacked_repeated_new_addresses(pointer, bs, r, counters); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_unpacked_repeated_new_addresses( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.new_addresses[r.new_addresses.length - counters[1]] = x; counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_new_diversifier( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); r.new_diversifier = x; return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.new_addresses.length != 0) { for(i = 0; i < r.new_addresses.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += ProtoBufRuntime._encode_bytes(r.new_addresses[i], pointer, bs); } } if (bytes(r.new_diversifier).length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.new_diversifier, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.new_addresses.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(r.new_addresses[i].length); } e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.new_diversifier).length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.new_addresses.length != 0) { return false; } if (bytes(r.new_diversifier).length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.new_addresses = input.new_addresses; output.new_diversifier = input.new_diversifier; } //array helpers for NewAddresses /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addNewAddresses(Data memory self, bytes memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ bytes[] memory tmp = new bytes[](self.new_addresses.length + 1); for (uint256 i = 0; i < self.new_addresses.length; i++) { tmp[i] = self.new_addresses[i]; } tmp[self.new_addresses.length] = value; self.new_addresses = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library HeaderData library StateData { //struct definition struct Data { bytes path; bytes value; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_path(pointer, bs, r); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, r); } else { pointer += ProtoBufRuntime._skip_field_decode(wireType, pointer, bs); } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_path( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); r.path = x; return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r ) internal pure returns (uint) { (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); r.value = x; return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.path.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.path, pointer, bs); } if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.path.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.path.length != 0) { return false; } if (r.value.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.path = input.path; output.value = input.value; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library StateData
store function Store in-memory struct to storage input The in-memory struct output The in-storage struct/
function store(Data memory input, Data storage output) internal { Height.store(input.height, output.height); output.timestamp = input.timestamp; MultiSignature.store(input.signature, output.signature); output.new_addresses = input.new_addresses; output.new_diversifier = input.new_diversifier; }
13,023,177
// SPDX-License-Identifier: MIT pragma solidity ^0.6.4; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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) { // 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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 Implementation of the {IERC20} interface. * * Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.0.0/contracts/token/ERC20/IERC20.sol * added pausable and "exit to community" functionality */ contract PausableERC20 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; uint256 private _amount; uint8 private _decimals; address private _admin; bool private _paused; event Paused(bool state); event ExitedToCommunity(); /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * All three of these values are immutable: they can only be set once during * construction. */ //constructor (address admin, string memory name, string memory symbol, uint256 amount) public { constructor () public { _admin = 0x2150Cb38ee362bceAC3d4A2704A82eeeD02E93EC; _name = "MetaFactory"; _symbol = "ROBOT"; _amount = 420000; _decimals = 18; _mint(_admin, _amount * (10 ** uint256(_decimals))); } /** * @dev checks to ensure that only the admin can execute */ modifier onlyAdmin { require(msg.sender == _admin, "admin only"); _; } /** * @dev checks to ensure the contract is not paused * only the admin can execute methods when the contract is paused * or when the contract has exited to community */ modifier notPaused { require(msg.sender == _admin || _paused == false, "transfer is paused"); _; } /** * @dev once exited to community, the contract can no longer be paused */ function exitToCommunity() public onlyAdmin returns (bool) { _paused = false; _admin = address(0); emit ExitedToCommunity(); return true; } /** * @dev sets the contract in a paused state, only admin can transfer tokens */ function pause(bool _pause) public onlyAdmin returns (bool) { _paused = _pause; emit Paused(_paused); return _paused; } /** * @dev Returns the admin address for the token. */ function admin() public view returns (address) { return _admin; } /** * @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 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 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) notPaused internal virtual { } }
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.adocusing-hooks[Using Hooks]./
function _beforeTokenTransfer(address from, address to, uint256 amount) notPaused internal virtual { }
1,576,576
./partial_match/1/0x7FEba38C9479d0efeE1e4338BF312c46317c17C9/sources/contracts/implementations/HeyMintERC1155ExtensionE.sol
Freeze all metadata so it can never be changed again/
function freezeAllMetadata() external onlyOwner { HeyMintStorage.State storage state = HeyMintStorage.state(); state.data.allMetadataFrozen = true; }
3,933,824