Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
- Contract name:
- FAsset
- Optimization enabled
- true
- Compiler version
- v0.7.6+commit.7338295f
- Optimization runs
- 200
- EVM Version
- default
- Verified at
- 2024-06-03T14:37:27.484596Z
Constructor Arguments
0x0000000000000000000000005a11fa259c898e6973db2f3c9e82339a53c777c000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044658525000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000846546573745852500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008546573742058525000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000077465737458525000000000000000000000000000000000000000000000000000
Arg [0] (address) : 0x5a11fa259c898e6973db2f3c9e82339a53c777c0
Arg [1] (string) : FXRP
Arg [2] (string) : FTestXRP
Arg [3] (string) : Test XRP
Arg [4] (string) : testXRP
Arg [5] (uint8) : 6
contracts/fasset/implementation/FAsset.sol
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import { IERC165, IERC20, IVPToken, IIVPToken, IICleanable, VPToken } from "../../../flattened/FlareSmartContracts.sol"; import "../interfaces/IFAsset.sol"; contract FAsset is IFAsset, VPToken, IERC165 { /** * Get the asset manager, corresponding to this fAsset. * fAssets and asset managers are in 1:1 correspondence. */ address public override assetManager; /** * Nonzero if f-asset is terminated (in that case its value is terminate timestamp). * Stopped f-asset can never be re-enabled. * * When f-asset is terminated, no transfers can be made anymore. * This is an extreme measure to be used as an optional last phase of asset manager upgrade, * when the asset manager minting has already been paused for a long time but there still exist * unredeemable f-assets, which at this point are considered unrecoverable (lost wallet keys etc.). * In such case, the f-asset contract is terminated and then agents can buy back their collateral at market rate * (i.e. they burn market value of backed f-assets in collateral to release the rest of the collateral). */ uint64 public terminatedAt = 0; /** * The name of the underlying asset. */ string public override assetName; /** * The symbol of the underlying asset. */ string public override assetSymbol; modifier onlyAssetManager { require(msg.sender == assetManager, "only asset manager"); _; } constructor( address _governance, string memory _name, string memory _symbol, string memory _assetName, string memory _assetSymbol, uint8 _decimals ) VPToken(_governance, _name, _symbol) { _setupDecimals(_decimals); assetName = _assetName; assetSymbol = _assetSymbol; } /** * Set asset manager contract this can be done only once and must be just after deploy * (otherwise nothing can be minted). */ function setAssetManager(address _assetManager) external onlyGovernance { require(_assetManager != address(0), "zero asset manager"); require(assetManager == address(0), "cannot replace asset manager"); assetManager = _assetManager; } /** * Mints `_amount` od fAsset. * Only the assetManager corresponding to this fAsset may call `mint()`. */ function mint(address _owner, uint256 _amount) external override onlyAssetManager { _mint(_owner, _amount); } /** * Burns `_amount` od fAsset. * Only the assetManager corresponding to this fAsset may call `burn()`. */ function burn(address _owner, uint256 _amount) external override onlyAssetManager { _burn(_owner, _amount); } /** * Stops all transfers by setting `terminated` flag to true. * Only the assetManager corresponding to this fAsset may call `terminate()`. * Stop is irreversible. */ function terminate() external override onlyAssetManager { if (terminatedAt == 0) { terminatedAt = uint64(block.timestamp); // safe, block timestamp can never exceed 64bit } } /** * True if f-asset is terminated. */ function terminated() external view override returns (bool) { return terminatedAt != 0; } /** * Prevent transfer if f-asset is terminated. */ function _beforeTokenTransfer( address _from, address _to, uint256 _amount ) internal override (VPToken) { require(terminatedAt == 0, "f-asset terminated"); require(_from == address(0) || balanceOf(_from) >= _amount, "f-asset balance too low"); VPToken._beforeTokenTransfer(_from, _to, _amount); } /** * Implementation of ERC-165 interface. */ function supportsInterface(bytes4 _interfaceId) external pure override returns (bool) { return _interfaceId == type(IERC165).interfaceId || _interfaceId == type(IERC20).interfaceId || _interfaceId == type(IVPToken).interfaceId || _interfaceId == type(IFAsset).interfaceId || _interfaceId == type(IIVPToken).interfaceId || _interfaceId == type(IICleanable).interfaceId; } }
contracts/fasset/interfaces/IFAsset.sol
// SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; /** * Here we declare only the functionalities related to AssetManager. */ interface IFAsset { /** * Mints `_amount` od fAsset. * Only the assetManager corresponding to this fAsset may call `mint()`. */ function mint(address _owner, uint256 _amount) external; /** * Burns `_amount` od fAsset. * Only the assetManager corresponding to this fAsset may call `burn()`. */ function burn(address _owner, uint256 _amount) external; /** * Stops all transfers by setting `terminated` flag to true. * Only the assetManager corresponding to this fAsset may call `terminate()`. */ function terminate() external; /** * The name of the underlying asset. */ function assetName() external view returns (string memory); /** * The symbol of the underlying asset. */ function assetSymbol() external view returns (string memory); /** * Get the asset manager, corresponding to this fAsset. * fAssets and asset managers are in 1:1 correspondence. */ function assetManager() external view returns (address); /** * True if f-asset is terminated. Stopped f-asset can never be re-enabled. * * When f-asset is terminated, no transfers can be made anymore. * This is an extreme measure to be used as an optional last phase of asset manager upgrade, * when the asset manager minting has already been paused for a long time but there still exist * unredeemable f-assets, which at this point are considered unrecoverable (lost wallet keys etc.). * In such case, the f-asset contract is terminated and then agents can buy back their collateral at market rate * (i.e. they burn market value of backed f-assets in collateral to release the rest of the collateral). */ function terminated() external view returns (bool); }
flattened/FlareSmartContracts.sol
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; // Sources flattened with hardhat v2.4.3 https://hardhat.org // File @openzeppelin/contracts/introspection/[email protected] /** * @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 contracts/extra-imports.sol // File @openzeppelin/contracts/math/[email protected] /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File @openzeppelin/contracts/math/[email protected] /** * @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/[email protected] /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File contracts/token/lib/CheckPointHistory.sol /** * @title Check Point History library * @notice A contract to manage checkpoints as of a given block. * @dev Store value history by block number with detachable state. **/ library CheckPointHistory { using SafeMath for uint256; using SafeCast for uint256; /** * @dev `CheckPoint` is the structure that attaches a block number to a * given value; the block number attached is the one that last changed the * value **/ struct CheckPoint { // `value` is the amount of tokens at a specific block number uint192 value; // `fromBlock` is the block number that the value was generated from uint64 fromBlock; } struct CheckPointHistoryState { // `checkpoints` is an array that tracks values at non-contiguous block numbers mapping(uint256 => CheckPoint) checkpoints; // `checkpoints` before `startIndex` have been deleted // INVARIANT: checkpoints.endIndex == 0 || startIndex < checkpoints.endIndex (strict!) // startIndex and endIndex are both less then fromBlock, so 64 bits is enough uint64 startIndex; // the index AFTER last uint64 endIndex; } /** * @notice Binary search of _checkpoints array. * @param _checkpoints An array of CheckPoint to search. * @param _startIndex Smallest possible index to be returned. * @param _blockNumber The block number to search for. */ function _indexOfGreatestBlockLessThan( mapping(uint256 => CheckPoint) storage _checkpoints, uint256 _startIndex, uint256 _endIndex, uint256 _blockNumber ) private view returns (uint256 index) { // Binary search of the value by given block number in the array uint256 min = _startIndex; uint256 max = _endIndex.sub(1); while (max > min) { uint256 mid = (max.add(min).add(1)).div(2); if (_checkpoints[mid].fromBlock <= _blockNumber) { min = mid; } else { max = mid.sub(1); } } return min; } /** * @notice Queries the value at a specific `_blockNumber` * @param _self A CheckPointHistoryState instance to manage. * @param _blockNumber The block number of the value active at that time * @return _value The value at `_blockNumber` **/ function valueAt( CheckPointHistoryState storage _self, uint256 _blockNumber ) internal view returns (uint256 _value) { uint256 historyCount = _self.endIndex; // No _checkpoints, return 0 if (historyCount == 0) return 0; // Shortcut for the actual value (extra optimized for current block, to save one storage read) // historyCount - 1 is safe, since historyCount != 0 if (_blockNumber >= block.number || _blockNumber >= _self.checkpoints[historyCount - 1].fromBlock) { return _self.checkpoints[historyCount - 1].value; } // guard values at start uint256 startIndex = _self.startIndex; if (_blockNumber < _self.checkpoints[startIndex].fromBlock) { // reading data before `startIndex` is only safe before first cleanup require(startIndex == 0, "CheckPointHistory: reading from cleaned-up block"); return 0; } // Find the block with number less than or equal to block given uint256 index = _indexOfGreatestBlockLessThan(_self.checkpoints, startIndex, _self.endIndex, _blockNumber); return _self.checkpoints[index].value; } /** * @notice Queries the value at `block.number` * @param _self A CheckPointHistoryState instance to manage. * @return _value The value at `block.number` **/ function valueAtNow(CheckPointHistoryState storage _self) internal view returns (uint256 _value) { uint256 historyCount = _self.endIndex; // No _checkpoints, return 0 if (historyCount == 0) return 0; // Return last value return _self.checkpoints[historyCount - 1].value; } /** * @notice Writes the value at the current block. * @param _self A CheckPointHistoryState instance to manage. * @param _value Value to write. **/ function writeValue( CheckPointHistoryState storage _self, uint256 _value ) internal { uint256 historyCount = _self.endIndex; if (historyCount == 0) { // checkpoints array empty, push new CheckPoint _self.checkpoints[0] = CheckPoint({ fromBlock: block.number.toUint64(), value: _toUint192(_value) }); _self.endIndex = 1; } else { // historyCount - 1 is safe, since historyCount != 0 CheckPoint storage lastCheckpoint = _self.checkpoints[historyCount - 1]; uint256 lastBlock = lastCheckpoint.fromBlock; // slither-disable-next-line incorrect-equality if (block.number == lastBlock) { // If last check point is the current block, just update lastCheckpoint.value = _toUint192(_value); } else { // we should never have future blocks in history assert (block.number > lastBlock); // push new CheckPoint _self.checkpoints[historyCount] = CheckPoint({ fromBlock: block.number.toUint64(), value: _toUint192(_value) }); _self.endIndex = uint64(historyCount + 1); // 64 bit safe, because historyCount <= block.number } } } /** * Delete at most `_count` of the oldest checkpoints. * At least one checkpoint at or before `_cleanupBlockNumber` will remain * (unless the history was empty to start with). */ function cleanupOldCheckpoints( CheckPointHistoryState storage _self, uint256 _count, uint256 _cleanupBlockNumber ) internal returns (uint256) { if (_cleanupBlockNumber == 0) return 0; // optimization for when cleaning is not enabled uint256 length = _self.endIndex; if (length == 0) return 0; uint256 startIndex = _self.startIndex; // length - 1 is safe, since length != 0 (check above) uint256 endIndex = Math.min(startIndex.add(_count), length - 1); // last element can never be deleted uint256 index = startIndex; // we can delete `checkpoint[index]` while the next checkpoint is at `_cleanupBlockNumber` or before while (index < endIndex && _self.checkpoints[index + 1].fromBlock <= _cleanupBlockNumber) { delete _self.checkpoints[index]; index++; } if (index > startIndex) { // index is the first not deleted index _self.startIndex = index.toUint64(); } return index - startIndex; // safe: index >= startIndex at start and then increases } // SafeCast lib is missing cast to uint192 function _toUint192(uint256 _value) internal pure returns (uint192) { require(_value < 2**192, "value doesn't fit in 192 bits"); return uint192(_value); } } // File contracts/token/lib/CheckPointsByAddress.sol /** * @title Check Points By Address library * @notice A contract to manage checkpoint history for a collection of addresses. * @dev Store value history by address, and then by block number. **/ library CheckPointsByAddress { using SafeMath for uint256; using CheckPointHistory for CheckPointHistory.CheckPointHistoryState; struct CheckPointsByAddressState { // `historyByAddress` is the map that stores the check point history of each address mapping(address => CheckPointHistory.CheckPointHistoryState) historyByAddress; } /** /** * @notice Send `amount` value to `to` address from `from` address. * @param _self A CheckPointsByAddressState instance to manage. * @param _from Address of the history of from values * @param _to Address of the history of to values * @param _amount The amount of value to be transferred **/ function transmit( CheckPointsByAddressState storage _self, address _from, address _to, uint256 _amount ) internal { // Shortcut if (_amount == 0) return; // Both from and to can never be zero assert(!(_from == address(0) && _to == address(0))); // Update transferer value if (_from != address(0)) { // Compute the new from balance uint256 newValueFrom = valueOfAtNow(_self, _from).sub(_amount); writeValue(_self, _from, newValueFrom); } // Update transferee value if (_to != address(0)) { // Compute the new to balance uint256 newValueTo = valueOfAtNow(_self, _to).add(_amount); writeValue(_self, _to, newValueTo); } } /** * @notice Queries the value of `_owner` at a specific `_blockNumber`. * @param _self A CheckPointsByAddressState instance to manage. * @param _owner The address from which the value will be retrieved. * @param _blockNumber The block number to query for the then current value. * @return The value at `_blockNumber` for `_owner`. **/ function valueOfAt( CheckPointsByAddressState storage _self, address _owner, uint256 _blockNumber ) internal view returns (uint256) { // Get history for _owner CheckPointHistory.CheckPointHistoryState storage history = _self.historyByAddress[_owner]; // Return value at given block return history.valueAt(_blockNumber); } /** * @notice Get the value of the `_owner` at the current `block.number`. * @param _self A CheckPointsByAddressState instance to manage. * @param _owner The address of the value is being requested. * @return The value of `_owner` at the current block. **/ function valueOfAtNow(CheckPointsByAddressState storage _self, address _owner) internal view returns (uint256) { // Get history for _owner CheckPointHistory.CheckPointHistoryState storage history = _self.historyByAddress[_owner]; // Return value at now return history.valueAtNow(); } /** * @notice Writes the `value` at the current block number for `_owner`. * @param _self A CheckPointsByAddressState instance to manage. * @param _owner The address of `_owner` to write. * @param _value The value to write. * @dev Sender must be the owner of the contract. **/ function writeValue( CheckPointsByAddressState storage _self, address _owner, uint256 _value ) internal { // Get history for _owner CheckPointHistory.CheckPointHistoryState storage history = _self.historyByAddress[_owner]; // Write the value history.writeValue(_value); } /** * Delete at most `_count` of the oldest checkpoints. * At least one checkpoint at or before `_cleanupBlockNumber` will remain * (unless the history was empty to start with). */ function cleanupOldCheckpoints( CheckPointsByAddressState storage _self, address _owner, uint256 _count, uint256 _cleanupBlockNumber ) internal returns (uint256) { if (_owner != address(0)) { return _self.historyByAddress[_owner].cleanupOldCheckpoints(_count, _cleanupBlockNumber); } return 0; } } // File contracts/token/lib/CheckPointHistoryCache.sol library CheckPointHistoryCache { using SafeMath for uint256; using CheckPointHistory for CheckPointHistory.CheckPointHistoryState; struct CacheState { // mapping blockNumber => (value + 1) mapping(uint256 => uint256) cache; } function valueAt( CacheState storage _self, CheckPointHistory.CheckPointHistoryState storage _checkPointHistory, uint256 _blockNumber ) internal returns (uint256 _value, bool _cacheCreated) { // is it in cache? uint256 cachedValue = _self.cache[_blockNumber]; if (cachedValue != 0) { return (cachedValue - 1, false); // safe, cachedValue != 0 } // read from _checkPointHistory uint256 historyValue = _checkPointHistory.valueAt(_blockNumber); _self.cache[_blockNumber] = historyValue.add(1); // store to cache (add 1 to differentiate from empty) return (historyValue, true); } function deleteAt( CacheState storage _self, uint256 _blockNumber ) internal returns (uint256 _deleted) { if (_self.cache[_blockNumber] != 0) { _self.cache[_blockNumber] = 0; return 1; } return 0; } } // File contracts/token/implementation/CheckPointable.sol /** * @title Check Pointable ERC20 Behavior * @notice ERC20 behavior which adds balance check point features. **/ abstract contract CheckPointable { using CheckPointHistory for CheckPointHistory.CheckPointHistoryState; using CheckPointsByAddress for CheckPointsByAddress.CheckPointsByAddressState; using CheckPointHistoryCache for CheckPointHistoryCache.CacheState; using SafeMath for uint256; // The number of history cleanup steps executed for every write operation. // It is more than 1 to make as certain as possible that all history gets cleaned eventually. uint256 private constant CLEANUP_COUNT = 2; // Private member variables CheckPointsByAddress.CheckPointsByAddressState private balanceHistory; CheckPointHistory.CheckPointHistoryState private totalSupply; CheckPointHistoryCache.CacheState private totalSupplyCache; // Historic data for the blocks before `cleanupBlockNumber` can be erased, // history before that block should never be used since it can be inconsistent. uint256 private cleanupBlockNumber; // Address of the contract that is allowed to call methods for history cleaning. address public cleanerContract; /** * Emitted when a total supply cache entry is created. * Allows history cleaners to track total supply cache cleanup opportunities off-chain. */ event CreatedTotalSupplyCache(uint256 _blockNumber); // Most cleanup opportunities can be deduced from standard event // Transfer(from, to, amount): // - balance history for `from` (if nonzero) and `to` (if nonzero) // - total supply history when either `from` or `to` is zero modifier notBeforeCleanupBlock(uint256 _blockNumber) { require(_blockNumber >= cleanupBlockNumber, "CheckPointable: reading from cleaned-up block"); _; } modifier onlyCleaner { require(msg.sender == cleanerContract, "Only cleaner contract"); _; } /** * @dev Queries the token balance of `_owner` at a specific `_blockNumber`. * @param _owner The address from which the balance will be retrieved. * @param _blockNumber The block number when the balance is queried. * @return _balance The balance at `_blockNumber`. **/ function balanceOfAt(address _owner, uint256 _blockNumber) public virtual view notBeforeCleanupBlock(_blockNumber) returns (uint256 _balance) { return balanceHistory.valueOfAt(_owner, _blockNumber); } /** * @notice Burn current token `amount` for `owner` of checkpoints at current block. * @param _owner The address of the owner to burn tokens. * @param _amount The amount to burn. */ function _burnForAtNow(address _owner, uint256 _amount) internal virtual { uint256 newBalance = balanceOfAt(_owner, block.number).sub(_amount, "Burn too big for owner"); balanceHistory.writeValue(_owner, newBalance); balanceHistory.cleanupOldCheckpoints(_owner, CLEANUP_COUNT, cleanupBlockNumber); totalSupply.writeValue(totalSupplyAt(block.number).sub(_amount, "Burn too big for total supply")); totalSupply.cleanupOldCheckpoints(CLEANUP_COUNT, cleanupBlockNumber); } /** * @notice Mint current token `amount` for `owner` of checkpoints at current block. * @param _owner The address of the owner to burn tokens. * @param _amount The amount to burn. */ function _mintForAtNow(address _owner, uint256 _amount) internal virtual { uint256 newBalance = balanceOfAt(_owner, block.number).add(_amount); balanceHistory.writeValue(_owner, newBalance); balanceHistory.cleanupOldCheckpoints(_owner, CLEANUP_COUNT, cleanupBlockNumber); totalSupply.writeValue(totalSupplyAt(block.number).add(_amount)); totalSupply.cleanupOldCheckpoints(CLEANUP_COUNT, cleanupBlockNumber); } /** * @notice Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the _totalSupply is queried * @return _totalSupply The total amount of tokens at `_blockNumber` **/ function totalSupplyAt(uint256 _blockNumber) public virtual view notBeforeCleanupBlock(_blockNumber) returns(uint256 _totalSupply) { return totalSupply.valueAt(_blockNumber); } /** * @notice Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the _totalSupply is queried * @return _totalSupply The total amount of tokens at `_blockNumber` **/ function _totalSupplyAtCached(uint256 _blockNumber) internal notBeforeCleanupBlock(_blockNumber) returns(uint256 _totalSupply) { // use cache only for the past (the value will never change) require(_blockNumber < block.number, "Can only be used for past blocks"); (uint256 value, bool cacheCreated) = totalSupplyCache.valueAt(totalSupply, _blockNumber); if (cacheCreated) emit CreatedTotalSupplyCache(_blockNumber); return value; } /** * @notice Transmit token `_amount` `_from` address `_to` address of checkpoints at current block. * @param _from The address of the sender. * @param _to The address of the receiver. * @param _amount The amount to transmit. */ function _transmitAtNow(address _from, address _to, uint256 _amount) internal virtual { balanceHistory.transmit(_from, _to, _amount); balanceHistory.cleanupOldCheckpoints(_from, CLEANUP_COUNT, cleanupBlockNumber); balanceHistory.cleanupOldCheckpoints(_to, CLEANUP_COUNT, cleanupBlockNumber); } /** * Set the cleanup block number. */ function _setCleanupBlockNumber(uint256 _blockNumber) internal { require(_blockNumber >= cleanupBlockNumber, "Cleanup block number must never decrease"); require(_blockNumber < block.number, "Cleanup block must be in the past"); cleanupBlockNumber = _blockNumber; } /** * Get the cleanup block number. */ function _cleanupBlockNumber() internal view returns (uint256) { return cleanupBlockNumber; } /** * @notice Update history at token transfer, the CheckPointable part of `_beforeTokenTransfer` hook. * @param _from The address of the sender. * @param _to The address of the receiver. * @param _amount The amount to transmit. */ function _updateBalanceHistoryAtTransfer(address _from, address _to, uint256 _amount) internal virtual { if (_from == address(0)) { // mint checkpoint balance data for transferee _mintForAtNow(_to, _amount); } else if (_to == address(0)) { // burn checkpoint data for transferer _burnForAtNow(_from, _amount); } else { // transfer checkpoint balance data _transmitAtNow(_from, _to, _amount); } } // history cleanup methods /** * Set the contract that is allowed to call history cleaning methods. */ function _setCleanerContract(address _cleanerContract) internal { cleanerContract = _cleanerContract; } /** * Delete balance checkpoints that expired (i.e. are before `cleanupBlockNumber`). * Method can only be called from the `cleanerContract` (which may be a proxy to external cleaners). * @param _owner balance owner account address * @param _count maximum number of checkpoints to delete * @return the number of checkpoints deleted */ function balanceHistoryCleanup(address _owner, uint256 _count) external onlyCleaner returns (uint256) { return balanceHistory.cleanupOldCheckpoints(_owner, _count, cleanupBlockNumber); } /** * Delete total supply checkpoints that expired (i.e. are before `cleanupBlockNumber`). * Method can only be called from the `cleanerContract` (which may be a proxy to external cleaners). * @param _count maximum number of checkpoints to delete * @return the number of checkpoints deleted */ function totalSupplyHistoryCleanup(uint256 _count) external onlyCleaner returns (uint256) { return totalSupply.cleanupOldCheckpoints(_count, cleanupBlockNumber); } /** * Delete total supply cache entry that expired (i.e. is before `cleanupBlockNumber`). * Method can only be called from the `cleanerContract` (which may be a proxy to external cleaners). * @param _blockNumber the block number for which total supply value was cached * @return the number of cache entries deleted (always 0 or 1) */ function totalSupplyCacheCleanup(uint256 _blockNumber) external onlyCleaner returns (uint256) { require(_blockNumber < cleanupBlockNumber, "No cleanup after cleanup block"); return totalSupplyCache.deleteAt(_blockNumber); } } // File @openzeppelin/contracts/utils/[email protected] /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/token/ERC20/[email protected] /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/[email protected] /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/utils/implementation/SafePct.sol /** * @dev Compute percentages safely without phantom overflows. * * Intermediate operations can overflow even when the result will always * fit into computed type. Developers usually * assume that overflows raise errors. `SafePct` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafePct { using SafeMath for uint256; /** * Requirements: * * - intermediate operations must revert on overflow */ function mulDiv(uint256 x, uint256 y, uint256 z) internal pure returns (uint256) { require(z > 0, "Division by zero"); if (x == 0) return 0; uint256 xy = x * y; if (xy / x == y) { // no overflow happened - same as in SafeMath mul return xy / z; } //slither-disable-next-line divide-before-multiply uint256 a = x / z; uint256 b = x % z; // x = a * z + b //slither-disable-next-line divide-before-multiply uint256 c = y / z; uint256 d = y % z; // y = c * z + d return (a.mul(c).mul(z)).add(a.mul(d)).add(b.mul(c)).add(b.mul(d).div(z)); } } // File contracts/userInterfaces/IGovernanceVotePower.sol interface IGovernanceVotePower { /** * @notice Delegate all governance vote power of `msg.sender` to `_to`. * @param _to The address of the recipient **/ function delegate(address _to) external; /** * @notice Undelegate all governance vote power of `msg.sender``. **/ function undelegate() external; /** * @notice Get the governance vote power of `_who` at block `_blockNumber` * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return _votePower Governance vote power of `_who` at `_blockNumber`. */ function votePowerOfAt(address _who, uint256 _blockNumber) external view returns(uint256); /** * @notice Get the vote power of `account` at the current block. * @param account The address to get voting power. * @return Vote power of `account` at the current block number. */ function getVotes(address account) external view returns (uint256); /** * @notice Get the delegate's address of `_who` at block `_blockNumber` * @param _who The address to get delegate's address. * @param _blockNumber The block number at which to fetch. * @return Delegate's address of `_who` at `_blockNumber`. */ function getDelegateOfAt(address _who, uint256 _blockNumber) external view returns (address); /** * @notice Get the delegate's address of `_who` at the current block. * @param _who The address to get delegate's address. * @return Delegate's address of `_who` at the current block number. */ function getDelegateOfAtNow(address _who) external view returns (address); } // File contracts/userInterfaces/IVPContractEvents.sol interface IVPContractEvents { /** * Event triggered when an account delegates or undelegates another account. * Definition: `votePowerFromTo(from, to)` is `changed` from `priorVotePower` to `newVotePower`. * For undelegation, `newVotePower` is 0. * * Note: the event is always emitted from VPToken's `writeVotePowerContract`. */ event Delegate(address indexed from, address indexed to, uint256 priorVotePower, uint256 newVotePower); /** * Event triggered only when account `delegator` revokes delegation to `delegatee` * for a single block in the past (typically the current vote block). * * Note: the event is always emitted from VPToken's `writeVotePowerContract` and/or `readVotePowerContract`. */ event Revoke(address indexed delegator, address indexed delegatee, uint256 votePower, uint256 blockNumber); } // File contracts/userInterfaces/IVPToken.sol interface IVPToken is IERC20 { /** * @notice Delegate by percentage `_bips` of voting power to `_to` from `msg.sender`. * @param _to The address of the recipient * @param _bips The percentage of voting power to be delegated expressed in basis points (1/100 of one percent). * Not cumulative - every call resets the delegation value (and value of 0 undelegates `to`). **/ function delegate(address _to, uint256 _bips) external; /** * @notice Undelegate all percentage delegations from the sender and then delegate corresponding * `_bips` percentage of voting power from the sender to each member of `_delegatees`. * @param _delegatees The addresses of the new recipients. * @param _bips The percentages of voting power to be delegated expressed in basis points (1/100 of one percent). * Total of all `_bips` values must be at most 10000. **/ function batchDelegate(address[] memory _delegatees, uint256[] memory _bips) external; /** * @notice Explicitly delegate `_amount` of voting power to `_to` from `msg.sender`. * @param _to The address of the recipient * @param _amount An explicit vote power amount to be delegated. * Not cumulative - every call resets the delegation value (and value of 0 undelegates `to`). **/ function delegateExplicit(address _to, uint _amount) external; /** * @notice Revoke all delegation from sender to `_who` at given block. * Only affects the reads via `votePowerOfAtCached()` in the block `_blockNumber`. * Block `_blockNumber` must be in the past. * This method should be used only to prevent rogue delegate voting in the current voting block. * To stop delegating use delegate/delegateExplicit with value of 0 or undelegateAll/undelegateAllExplicit. * @param _who Address of the delegatee * @param _blockNumber The block number at which to revoke delegation. */ function revokeDelegationAt(address _who, uint _blockNumber) external; /** * @notice Undelegate all voting power for delegates of `msg.sender` * Can only be used with percentage delegation. * Does not reset delegation mode back to NOTSET. **/ function undelegateAll() external; /** * @notice Undelegate all explicit vote power by amount delegates for `msg.sender`. * Can only be used with explicit delegation. * Does not reset delegation mode back to NOTSET. * @param _delegateAddresses Explicit delegation does not store delegatees' addresses, * so the caller must supply them. * @return The amount still delegated (in case the list of delegates was incomplete). */ function undelegateAllExplicit(address[] memory _delegateAddresses) external returns (uint256); /** * @dev Should be compatible with ERC20 method */ function name() external view returns (string memory); /** * @dev Should be compatible with ERC20 method */ function symbol() external view returns (string memory); /** * @dev Should be compatible with ERC20 method */ function decimals() external view returns (uint8); /** * @notice Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the totalSupply is queried * @return The total amount of tokens at `_blockNumber` **/ function totalSupplyAt(uint _blockNumber) external view returns(uint256); /** * @dev Queries the token balance of `_owner` at a specific `_blockNumber`. * @param _owner The address from which the balance will be retrieved. * @param _blockNumber The block number when the balance is queried. * @return The balance at `_blockNumber`. **/ function balanceOfAt(address _owner, uint _blockNumber) external view returns (uint256); /** * @notice Get the current total vote power. * @return The current total vote power (sum of all accounts' vote powers). */ function totalVotePower() external view returns(uint256); /** * @notice Get the total vote power at block `_blockNumber` * @param _blockNumber The block number at which to fetch. * @return The total vote power at the block (sum of all accounts' vote powers). */ function totalVotePowerAt(uint _blockNumber) external view returns(uint256); /** * @notice Get the current vote power of `_owner`. * @param _owner The address to get voting power. * @return Current vote power of `_owner`. */ function votePowerOf(address _owner) external view returns(uint256); /** * @notice Get the vote power of `_owner` at block `_blockNumber` * @param _owner The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_owner` at `_blockNumber`. */ function votePowerOfAt(address _owner, uint256 _blockNumber) external view returns(uint256); /** * @notice Get the vote power of `_owner` at block `_blockNumber`, ignoring revocation information (and cache). * @param _owner The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_owner` at `_blockNumber`. Result doesn't change if vote power is revoked. */ function votePowerOfAtIgnoringRevocation(address _owner, uint256 _blockNumber) external view returns(uint256); /** * @notice Get the delegation mode for '_who'. This mode determines whether vote power is * allocated by percentage or by explicit value. Once the delegation mode is set, * it never changes, even if all delegations are removed. * @param _who The address to get delegation mode. * @return delegation mode: 0 = NOTSET, 1 = PERCENTAGE, 2 = AMOUNT (i.e. explicit) */ function delegationModeOf(address _who) external view returns(uint256); /** * @notice Get current delegated vote power `_from` delegator delegated `_to` delegatee. * @param _from Address of delegator * @param _to Address of delegatee * @return The delegated vote power. */ function votePowerFromTo(address _from, address _to) external view returns(uint256); /** * @notice Get delegated the vote power `_from` delegator delegated `_to` delegatee at `_blockNumber`. * @param _from Address of delegator * @param _to Address of delegatee * @param _blockNumber The block number at which to fetch. * @return The delegated vote power. */ function votePowerFromToAt(address _from, address _to, uint _blockNumber) external view returns(uint256); /** * @notice Compute the current undelegated vote power of `_owner` * @param _owner The address to get undelegated voting power. * @return The unallocated vote power of `_owner` */ function undelegatedVotePowerOf(address _owner) external view returns(uint256); /** * @notice Get the undelegated vote power of `_owner` at given block. * @param _owner The address to get undelegated voting power. * @param _blockNumber The block number at which to fetch. * @return The undelegated vote power of `_owner` (= owner's own balance minus all delegations from owner) */ function undelegatedVotePowerOfAt(address _owner, uint256 _blockNumber) external view returns(uint256); /** * @notice Get the vote power delegation `delegationAddresses` * and `_bips` of `_who`. Returned in two separate positional arrays. * @param _who The address to get delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOf(address _who) external view returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ); /** * @notice Get the vote power delegation `delegationAddresses` * and `pcts` of `_who`. Returned in two separate positional arrays. * @param _who The address to get delegations. * @param _blockNumber The block for which we want to know the delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOfAt(address _who, uint256 _blockNumber) external view returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ); /** * Returns VPContract used for readonly operations (view methods). * The only non-view method that might be called on it is `revokeDelegationAt`. * * @notice `readVotePowerContract` is almost always equal to `writeVotePowerContract` * except during upgrade from one VPContract to a new version (which should happen * rarely or never and will be anounced before). * * @notice You shouldn't call any methods on VPContract directly, all are exposed * via VPToken (and state changing methods are forbidden from direct calls). * This is the reason why this method returns `IVPContractEvents` - it should only be used * for listening to events (`Revoke` only). */ function readVotePowerContract() external view returns (IVPContractEvents); /** * Returns VPContract used for state changing operations (non-view methods). * The only non-view method that might be called on it is `revokeDelegationAt`. * * @notice `writeVotePowerContract` is almost always equal to `readVotePowerContract` * except during upgrade from one VPContract to a new version (which should happen * rarely or never and will be anounced before). In the case of upgrade, * `writeVotePowerContract` will be replaced first to establish delegations, and * after some perio (e.g. after a reward epoch ends) `readVotePowerContract` will be set equal to it. * * @notice You shouldn't call any methods on VPContract directly, all are exposed * via VPToken (and state changing methods are forbidden from direct calls). * This is the reason why this method returns `IVPContractEvents` - it should only be used * for listening to events (`Delegate` and `Revoke` only). */ function writeVotePowerContract() external view returns (IVPContractEvents); /** * When set, allows token owners to participate in governance voting * and delegate governance vote power. */ function governanceVotePower() external view returns (IGovernanceVotePower); } // File contracts/token/interface/IICleanable.sol interface IICleanable { /** * Set the contract that is allowed to call history cleaning methods. */ function setCleanerContract(address _cleanerContract) external; /** * Set the cleanup block number. * Historic data for the blocks before `cleanupBlockNumber` can be erased, * history before that block should never be used since it can be inconsistent. * In particular, cleanup block number must be before current vote power block. * @param _blockNumber The new cleanup block number. */ function setCleanupBlockNumber(uint256 _blockNumber) external; /** * Get the current cleanup block number. */ function cleanupBlockNumber() external view returns (uint256); } // File contracts/token/interface/IIVPContract.sol interface IIVPContract is IICleanable, IVPContractEvents { /** * Update vote powers when tokens are transfered. * Also update delegated vote powers for percentage delegation * and check for enough funds for explicit delegations. **/ function updateAtTokenTransfer( address _from, address _to, uint256 _fromBalance, uint256 _toBalance, uint256 _amount ) external; /** * @notice Delegate `_bips` percentage of voting power to `_to` from `_from` * @param _from The address of the delegator * @param _to The address of the recipient * @param _balance The delegator's current balance * @param _bips The percentage of voting power to be delegated expressed in basis points (1/100 of one percent). * Not cumulative - every call resets the delegation value (and value of 0 revokes delegation). **/ function delegate( address _from, address _to, uint256 _balance, uint256 _bips ) external; /** * @notice Explicitly delegate `_amount` of voting power to `_to` from `msg.sender`. * @param _from The address of the delegator * @param _to The address of the recipient * @param _balance The delegator's current balance * @param _amount An explicit vote power amount to be delegated. * Not cumulative - every call resets the delegation value (and value of 0 undelegates `to`). **/ function delegateExplicit( address _from, address _to, uint256 _balance, uint _amount ) external; /** * @notice Revoke all delegation from sender to `_who` at given block. * Only affects the reads via `votePowerOfAtCached()` in the block `_blockNumber`. * Block `_blockNumber` must be in the past. * This method should be used only to prevent rogue delegate voting in the current voting block. * To stop delegating use delegate/delegateExplicit with value of 0 or undelegateAll/undelegateAllExplicit. * @param _from The address of the delegator * @param _who Address of the delegatee * @param _balance The delegator's current balance * @param _blockNumber The block number at which to revoke delegation. **/ function revokeDelegationAt( address _from, address _who, uint256 _balance, uint _blockNumber ) external; /** * @notice Undelegate all voting power for delegates of `msg.sender` * Can only be used with percentage delegation. * Does not reset delegation mode back to NOTSET. * @param _from The address of the delegator **/ function undelegateAll( address _from, uint256 _balance ) external; /** * @notice Undelegate all explicit vote power by amount delegates for `msg.sender`. * Can only be used with explicit delegation. * Does not reset delegation mode back to NOTSET. * @param _from The address of the delegator * @param _delegateAddresses Explicit delegation does not store delegatees' addresses, * so the caller must supply them. * @return The amount still delegated (in case the list of delegates was incomplete). */ function undelegateAllExplicit( address _from, address[] memory _delegateAddresses ) external returns (uint256); /** * @notice Get the vote power of `_who` at block `_blockNumber` * Reads/updates cache and upholds revocations. * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. */ function votePowerOfAtCached(address _who, uint256 _blockNumber) external returns(uint256); /** * @notice Get the current vote power of `_who`. * @param _who The address to get voting power. * @return Current vote power of `_who`. */ function votePowerOf(address _who) external view returns(uint256); /** * @notice Get the vote power of `_who` at block `_blockNumber` * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. */ function votePowerOfAt(address _who, uint256 _blockNumber) external view returns(uint256); /** * @notice Get the vote power of `_who` at block `_blockNumber`, ignoring revocation information (and cache). * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. Result doesn't change if vote power is revoked. */ function votePowerOfAtIgnoringRevocation(address _who, uint256 _blockNumber) external view returns(uint256); /** * Return vote powers for several addresses in a batch. * @param _owners The list of addresses to fetch vote power of. * @param _blockNumber The block number at which to fetch. * @return A list of vote powers. */ function batchVotePowerOfAt( address[] memory _owners, uint256 _blockNumber ) external view returns(uint256[] memory); /** * @notice Get current delegated vote power `_from` delegator delegated `_to` delegatee. * @param _from Address of delegator * @param _to Address of delegatee * @param _balance The delegator's current balance * @return The delegated vote power. */ function votePowerFromTo( address _from, address _to, uint256 _balance ) external view returns(uint256); /** * @notice Get delegated the vote power `_from` delegator delegated `_to` delegatee at `_blockNumber`. * @param _from Address of delegator * @param _to Address of delegatee * @param _balance The delegator's current balance * @param _blockNumber The block number at which to fetch. * @return The delegated vote power. */ function votePowerFromToAt( address _from, address _to, uint256 _balance, uint _blockNumber ) external view returns(uint256); /** * @notice Compute the current undelegated vote power of `_owner` * @param _owner The address to get undelegated voting power. * @param _balance Owner's current balance * @return The unallocated vote power of `_owner` */ function undelegatedVotePowerOf( address _owner, uint256 _balance ) external view returns(uint256); /** * @notice Get the undelegated vote power of `_owner` at given block. * @param _owner The address to get undelegated voting power. * @param _blockNumber The block number at which to fetch. * @return The undelegated vote power of `_owner` (= owner's own balance minus all delegations from owner) */ function undelegatedVotePowerOfAt( address _owner, uint256 _balance, uint256 _blockNumber ) external view returns(uint256); /** * @notice Get the delegation mode for '_who'. This mode determines whether vote power is * allocated by percentage or by explicit value. * @param _who The address to get delegation mode. * @return Delegation mode (NOTSET=0, PERCENTAGE=1, AMOUNT=2)) */ function delegationModeOf(address _who) external view returns (uint256); /** * @notice Get the vote power delegation `_delegateAddresses` * and `pcts` of an `_owner`. Returned in two separate positional arrays. * @param _owner The address to get delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOf( address _owner ) external view returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ); /** * @notice Get the vote power delegation `delegationAddresses` * and `pcts` of an `_owner`. Returned in two separate positional arrays. * @param _owner The address to get delegations. * @param _blockNumber The block for which we want to know the delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOfAt( address _owner, uint256 _blockNumber ) external view returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ); /** * The VPToken (or some other contract) that owns this VPContract. * All state changing methods may be called only from this address. * This is because original msg.sender is sent in `_from` parameter * and we must be sure that it cannot be faked by directly calling VPContract. * Owner token is also used in case of replacement to recover vote powers from balances. */ function ownerToken() external view returns (IVPToken); /** * Return true if this IIVPContract is configured to be used as a replacement for other contract. * It means that vote powers are not necessarily correct at the initialization, therefore * every method that reads vote power must check whether it is initialized for that address and block. */ function isReplacement() external view returns (bool); } // File contracts/token/interface/IIGovernanceVotePower.sol interface IIGovernanceVotePower is IGovernanceVotePower { /** * Event triggered when an delegator's balance changes. * * Note: the event is always emitted from `GovernanceVotePower`. */ event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /** * Event triggered when an account delegates to another account. * * Note: the event is always emitted from `GovernanceVotePower`. */ event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /** * Update vote powers when tokens are transfered. **/ function updateAtTokenTransfer( address _from, address _to, uint256 _fromBalance, uint256 _toBalance, uint256 _amount ) external; /** * Set the cleanup block number. * Historic data for the blocks before `cleanupBlockNumber` can be erased, * history before that block should never be used since it can be inconsistent. * In particular, cleanup block number must be before current vote power block. * @param _blockNumber The new cleanup block number. */ function setCleanupBlockNumber(uint256 _blockNumber) external; /** * Set the contract that is allowed to call history cleaning methods. */ function setCleanerContract(address _cleanerContract) external; /** * @notice Get the token that this governance vote power contract belongs to. */ function ownerToken() external view returns (IVPToken); function getCleanupBlockNumber() external view returns(uint256); } // File contracts/token/interface/IIVPToken.sol interface IIVPToken is IVPToken, IICleanable { /** * Set the contract that is allowed to set cleanupBlockNumber. * Usually this will be an instance of CleanupBlockNumberManager. */ function setCleanupBlockNumberManager(address _cleanupBlockNumberManager) external; /** * Sets new governance vote power contract that allows token owners to participate in governance voting * and delegate governance vote power. */ function setGovernanceVotePower(IIGovernanceVotePower _governanceVotePower) external; /** * @notice Get the total vote power at block `_blockNumber` using cache. * It tries to read the cached value and if not found, reads the actual value and stores it in cache. * Can only be used if `_blockNumber` is in the past, otherwise reverts. * @param _blockNumber The block number at which to fetch. * @return The total vote power at the block (sum of all accounts' vote powers). */ function totalVotePowerAtCached(uint256 _blockNumber) external returns(uint256); /** * @notice Get the vote power of `_owner` at block `_blockNumber` using cache. * It tries to read the cached value and if not found, reads the actual value and stores it in cache. * Can only be used if _blockNumber is in the past, otherwise reverts. * @param _owner The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_owner` at `_blockNumber`. */ function votePowerOfAtCached(address _owner, uint256 _blockNumber) external returns(uint256); /** * Return vote powers for several addresses in a batch. * @param _owners The list of addresses to fetch vote power of. * @param _blockNumber The block number at which to fetch. * @return A list of vote powers. */ function batchVotePowerOfAt( address[] memory _owners, uint256 _blockNumber ) external view returns(uint256[] memory); } // File contracts/userInterfaces/IGovernanceSettings.sol /** * A special contract that holds Flare governance address. * This contract enables updating governance address and timelock only by hard forking the network, * meaning only by updating validator code. */ interface IGovernanceSettings { /** * Get the governance account address. * The governance address can only be changed by a hardfork. */ function getGovernanceAddress() external view returns (address); /** * Get the time in seconds that must pass between a governance call and execution. * The timelock value can only be changed by a hardfork. */ function getTimelock() external view returns (uint256); /** * Get the addresses of the accounts that are allowed to execute the timelocked governance calls * once the timelock period expires. * Executors can be changed without a hardfork, via a normal governance call. */ function getExecutors() external view returns (address[] memory); /** * Check whether an address is one of the executors. */ function isExecutor(address _address) external view returns (bool); } // File contracts/governance/implementation/GovernedBase.sol /** * @title Governed Base * @notice This abstract base class defines behaviors for a governed contract. * @dev This class is abstract so that specific behaviors can be defined for the constructor. * Contracts should not be left ungoverned, but not all contract will have a constructor * (for example those pre-defined in genesis). **/ abstract contract GovernedBase { struct TimelockedCall { uint256 allowedAfterTimestamp; bytes encodedCall; } // solhint-disable-next-line const-name-snakecase IGovernanceSettings public constant governanceSettings = IGovernanceSettings(0x1000000000000000000000000000000000000007); address private initialGovernance; bool private initialised; bool public productionMode; bool private executing; mapping(bytes4 => TimelockedCall) public timelockedCalls; event GovernanceCallTimelocked(bytes4 selector, uint256 allowedAfterTimestamp, bytes encodedCall); event TimelockedGovernanceCallExecuted(bytes4 selector, uint256 timestamp); event TimelockedGovernanceCallCanceled(bytes4 selector, uint256 timestamp); event GovernanceInitialised(address initialGovernance); event GovernedProductionModeEntered(address governanceSettings); modifier onlyGovernance { if (executing || !productionMode) { _beforeExecute(); _; } else { _recordTimelockedCall(msg.data); } } modifier onlyImmediateGovernance () { _checkOnlyGovernance(); _; } constructor(address _initialGovernance) { if (_initialGovernance != address(0)) { initialise(_initialGovernance); } } /** * @notice Execute the timelocked governance calls once the timelock period expires. * @dev Only executor can call this method. * @param _selector The method selector (only one timelocked call per method is stored). */ function executeGovernanceCall(bytes4 _selector) external { require(governanceSettings.isExecutor(msg.sender), "only executor"); TimelockedCall storage call = timelockedCalls[_selector]; require(call.allowedAfterTimestamp != 0, "timelock: invalid selector"); require(block.timestamp >= call.allowedAfterTimestamp, "timelock: not allowed yet"); bytes memory encodedCall = call.encodedCall; delete timelockedCalls[_selector]; executing = true; //solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call(encodedCall); executing = false; emit TimelockedGovernanceCallExecuted(_selector, block.timestamp); _passReturnOrRevert(success); } /** * Cancel a timelocked governance call before it has been executed. * @dev Only governance can call this method. * @param _selector The method selector. */ function cancelGovernanceCall(bytes4 _selector) external onlyImmediateGovernance { require(timelockedCalls[_selector].allowedAfterTimestamp != 0, "timelock: invalid selector"); emit TimelockedGovernanceCallCanceled(_selector, block.timestamp); delete timelockedCalls[_selector]; } /** * Enter the production mode after all the initial governance settings have been set. * This enables timelocks and the governance is afterwards obtained by calling * governanceSettings.getGovernanceAddress(). */ function switchToProductionMode() external { _checkOnlyGovernance(); require(!productionMode, "already in production mode"); initialGovernance = address(0); productionMode = true; emit GovernedProductionModeEntered(address(governanceSettings)); } /** * @notice Initialize the governance address if not first initialized. */ function initialise(address _initialGovernance) public virtual { require(initialised == false, "initialised != false"); initialised = true; initialGovernance = _initialGovernance; emit GovernanceInitialised(_initialGovernance); } /** * Returns the current effective governance address. */ function governance() public view returns (address) { return productionMode ? governanceSettings.getGovernanceAddress() : initialGovernance; } function _beforeExecute() private { if (executing) { // can only be run from executeGovernanceCall(), where we check that only executor can call // make sure nothing else gets executed, even in case of reentrancy assert(msg.sender == address(this)); executing = false; } else { // must be called with: productionMode=false // must check governance in this case _checkOnlyGovernance(); } } function _recordTimelockedCall(bytes calldata _data) private { _checkOnlyGovernance(); bytes4 selector; //solhint-disable-next-line no-inline-assembly assembly { selector := calldataload(_data.offset) } uint256 timelock = governanceSettings.getTimelock(); uint256 allowedAt = block.timestamp + timelock; timelockedCalls[selector] = TimelockedCall({ allowedAfterTimestamp: allowedAt, encodedCall: _data }); emit GovernanceCallTimelocked(selector, allowedAt, _data); } function _checkOnlyGovernance() private view { require(msg.sender == governance(), "only governance"); } function _passReturnOrRevert(bool _success) private pure { // pass exact return or revert data - needs to be done in assembly //solhint-disable-next-line no-inline-assembly assembly { let size := returndatasize() let ptr := mload(0x40) mstore(0x40, add(ptr, size)) returndatacopy(ptr, 0, size) if _success { return(ptr, size) } revert(ptr, size) } } } // File contracts/governance/implementation/Governed.sol /** * @title Governed * @dev For deployed, governed contracts, enforce a non-zero address at create time. **/ contract Governed is GovernedBase { constructor(address _governance) GovernedBase(_governance) { require(_governance != address(0), "_governance zero"); } } // File contracts/token/implementation/VPToken.sol /** * @title Vote Power Token * @dev An ERC20 token to enable the holder to delegate voting power * equal 1-1 to their balance, with history tracking by block. **/ contract VPToken is IIVPToken, ERC20, CheckPointable, Governed { using SafeMath for uint256; using SafePct for uint256; // the VPContract to use for reading vote powers and delegations IIVPContract private readVpContract; // the VPContract to use for writing vote powers and delegations // normally same as `readVpContract` except during switch // when reading happens from the old and writing goes to the new VPContract IIVPContract private writeVpContract; // the contract to use for governance vote power and delegation // here only to properly update governance vp during transfers - // all actual operations go directly to governance vp contract IIGovernanceVotePower private governanceVP; // the contract that is allowed to set cleanupBlockNumber // usually this will be an instance of CleanupBlockNumberManager address public cleanupBlockNumberManager; /** * When true, the argument to `setWriteVpContract` must be a vpContract * with `isReplacement` set to `true`. To be used for creating the correct VPContract. */ bool public vpContractInitialized = false; /** * Event used to track history of VPToken -> VPContract / GovernanceVotePower * associations (e.g. by external cleaners). * @param _contractType 0 = read VPContract, 1 = write VPContract, 2 = governance vote power * @param _oldContractAddress vote power contract address before change * @param _newContractAddress vote power contract address after change */ event VotePowerContractChanged(uint256 _contractType, address _oldContractAddress, address _newContractAddress); constructor( address _governance, //slither-disable-next-line shadowing-local string memory _name, //slither-disable-next-line shadowing-local string memory _symbol ) Governed(_governance) ERC20(_name, _symbol) { /* empty block */ } /** * @dev Should be compatible with ERC20 method */ function name() public view override(ERC20, IVPToken) returns (string memory) { return ERC20.name(); } /** * @dev Should be compatible with ERC20 method */ function symbol() public view override(ERC20, IVPToken) returns (string memory) { return ERC20.symbol(); } /** * @dev Should be compatible with ERC20 method */ function decimals() public view override(ERC20, IVPToken) returns (uint8) { return ERC20.decimals(); } /** * @notice Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the totalSupply is queried * @return The total amount of tokens at `_blockNumber` **/ function totalSupplyAt(uint256 _blockNumber) public view override(CheckPointable, IVPToken) returns(uint256) { return CheckPointable.totalSupplyAt(_blockNumber); } /** * @dev Queries the token balance of `_owner` at a specific `_blockNumber`. * @param _owner The address from which the balance will be retrieved. * @param _blockNumber The block number when the balance is queried. * @return The balance at `_blockNumber`. **/ function balanceOfAt( address _owner, uint256 _blockNumber ) public view override(CheckPointable, IVPToken) returns (uint256) { return CheckPointable.balanceOfAt(_owner, _blockNumber); } /** * @notice Delegate `_bips` of voting power to `_to` from `msg.sender` * @param _to The address of the recipient * @param _bips The percentage of voting power to be delegated expressed in basis points (1/100 of one percent). * Not cumulative - every call resets the delegation value (and value of 0 revokes delegation). **/ function delegate(address _to, uint256 _bips) external override { // Get the current balance of sender and delegate by percentage _to recipient _checkWriteVpContract().delegate(msg.sender, _to, balanceOf(msg.sender), _bips); } /** * @notice Undelegate all percentage delegations from the sender and then delegate corresponding * `_bips` percentage of voting power from the sender to each member of `_delegatees`. * @param _delegatees The addresses of the new recipients. * @param _bips The percentages of voting power to be delegated expressed in basis points (1/100 of one percent). * Total of all `_bips` values must be at most 10000. **/ function batchDelegate(address[] memory _delegatees, uint256[] memory _bips) external override { require(_delegatees.length == _bips.length, "Array length mismatch"); IIVPContract vpContract = _checkWriteVpContract(); uint256 balance = balanceOf(msg.sender); vpContract.undelegateAll(msg.sender, balance); for (uint256 i = 0; i < _delegatees.length; i++) { vpContract.delegate(msg.sender, _delegatees[i], balance, _bips[i]); } } /** * @notice Delegate `_amount` of voting power to `_to` from `msg.sender` * @param _to The address of the recipient * @param _amount An explicit vote power amount to be delegated. * Not cumulative - every call resets the delegation value (and value of 0 revokes delegation). **/ function delegateExplicit(address _to, uint256 _amount) external override { _checkWriteVpContract().delegateExplicit(msg.sender, _to, balanceOf(msg.sender), _amount); } /** * @notice Compute the current undelegated vote power of `_owner` * @param _owner The address to get undelegated voting power. * @return The unallocated vote power of `_owner` */ function undelegatedVotePowerOf(address _owner) external view override returns(uint256) { return _checkReadVpContract().undelegatedVotePowerOf(_owner, balanceOf(_owner)); } /** * @notice Get the undelegated vote power of `_owner` at given block. * @param _owner The address to get undelegated voting power. * @param _blockNumber The block number at which to fetch. * @return The unallocated vote power of `_owner` */ function undelegatedVotePowerOfAt(address _owner, uint256 _blockNumber) external view override returns (uint256) { return _checkReadVpContract() .undelegatedVotePowerOfAt(_owner, balanceOfAt(_owner, _blockNumber), _blockNumber); } /** * @notice Undelegate all voting power for delegates of `msg.sender` **/ function undelegateAll() external override { _checkWriteVpContract().undelegateAll(msg.sender, balanceOf(msg.sender)); } /** * @notice Undelegate all explicit vote power by amount delegates for `msg.sender`. * @param _delegateAddresses Explicit delegation does not store delegatees' addresses, * so the caller must supply them. * @return _remainingDelegation The amount still delegated (in case the list of delegates was incomplete). */ function undelegateAllExplicit( address[] memory _delegateAddresses ) external override returns (uint256 _remainingDelegation) { return _checkWriteVpContract().undelegateAllExplicit(msg.sender, _delegateAddresses); } /** * @notice Revoke all delegation from sender to `_who` at given block. * Only affects the reads via `votePowerOfAtCached()` in the block `_blockNumber`. * Block `_blockNumber` must be in the past. * This method should be used only to prevent rogue delegate voting in the current voting block. * To stop delegating use delegate/delegateExplicit with value of 0 or undelegateAll/undelegateAllExplicit. */ function revokeDelegationAt(address _who, uint256 _blockNumber) public override { IIVPContract writeVPC = writeVpContract; IIVPContract readVPC = readVpContract; if (address(writeVPC) != address(0)) { writeVPC.revokeDelegationAt(msg.sender, _who, balanceOfAt(msg.sender, _blockNumber), _blockNumber); } if (address(readVPC) != address(writeVPC) && address(readVPC) != address(0)) { try readVPC.revokeDelegationAt(msg.sender, _who, balanceOfAt(msg.sender, _blockNumber), _blockNumber) { } catch { // do nothing } } } /** * @notice Get current delegated vote power `_from` delegator delegated `_to` delegatee. * @param _from Address of delegator * @param _to Address of delegatee * @return votePower The delegated vote power. */ function votePowerFromTo( address _from, address _to ) external view override returns(uint256) { return _checkReadVpContract().votePowerFromTo(_from, _to, balanceOf(_from)); } /** * @notice Get delegated the vote power `_from` delegator delegated `_to` delegatee at `_blockNumber`. * @param _from Address of delegator * @param _to Address of delegatee * @param _blockNumber The block number at which to fetch. * @return The delegated vote power. */ function votePowerFromToAt( address _from, address _to, uint256 _blockNumber ) external view override returns(uint256) { return _checkReadVpContract().votePowerFromToAt(_from, _to, balanceOfAt(_from, _blockNumber), _blockNumber); } /** * @notice Get the current total vote power. * @return The current total vote power (sum of all accounts' vote powers). */ function totalVotePower() external view override returns(uint256) { return totalSupply(); } /** * @notice Get the total vote power at block `_blockNumber` * @param _blockNumber The block number at which to fetch. * @return The total vote power at the block (sum of all accounts' vote powers). */ function totalVotePowerAt(uint256 _blockNumber) external view override returns(uint256) { return totalSupplyAt(_blockNumber); } /** * @notice Get the total vote power at block `_blockNumber` using cache. * It tries to read the cached value and if not found, reads the actual value and stores it in cache. * Can only be used if `_blockNumber` is in the past, otherwise reverts. * @param _blockNumber The block number at which to fetch. * @return The total vote power at the block (sum of all accounts' vote powers). */ function totalVotePowerAtCached(uint256 _blockNumber) public override returns(uint256) { return _totalSupplyAtCached(_blockNumber); } /** * @notice Get the delegation mode for '_who'. This mode determines whether vote power is * allocated by percentage or by explicit value. Once the delegation mode is set, * it never changes, even if all delegations are removed. * @param _who The address to get delegation mode. * @return delegation mode: 0 = NOTSET, 1 = PERCENTAGE, 2 = AMOUNT (i.e. explicit) */ function delegationModeOf(address _who) external view override returns (uint256) { return _checkReadVpContract().delegationModeOf(_who); } /** * @notice Get the current vote power of `_owner`. * @param _owner The address to get voting power. * @return Current vote power of `_owner`. */ function votePowerOf(address _owner) external view override returns(uint256) { return _checkReadVpContract().votePowerOf(_owner); } /** * @notice Get the vote power of `_owner` at block `_blockNumber` * @param _owner The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_owner` at `_blockNumber`. */ function votePowerOfAt(address _owner, uint256 _blockNumber) external view override returns(uint256) { return _checkReadVpContract().votePowerOfAt(_owner, _blockNumber); } /** * @notice Get the vote power of `_owner` at block `_blockNumber`, ignoring revocation information (and cache). * @param _owner The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_owner` at `_blockNumber`. Result doesn't change if vote power is revoked. */ function votePowerOfAtIgnoringRevocation(address _owner, uint256 _blockNumber) external view override returns(uint256) { return _checkReadVpContract().votePowerOfAtIgnoringRevocation(_owner, _blockNumber); } /** * Return vote powers for several addresses in a batch. * @param _owners The list of addresses to fetch vote power of. * @param _blockNumber The block number at which to fetch. * @return A list of vote powers. */ function batchVotePowerOfAt( address[] memory _owners, uint256 _blockNumber ) external view override returns(uint256[] memory) { return _checkReadVpContract().batchVotePowerOfAt(_owners, _blockNumber); } /** * @notice Get the vote power of `_owner` at block `_blockNumber` using cache. * It tries to read the cached value and if not found, reads the actual value and stores it in cache. * Can only be used if _blockNumber is in the past, otherwise reverts. * @param _owner The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_owner` at `_blockNumber`. */ function votePowerOfAtCached(address _owner, uint256 _blockNumber) public override returns(uint256) { return _checkReadVpContract().votePowerOfAtCached(_owner, _blockNumber); } /** * @notice Get the vote power delegation `delegationAddresses` * and `_bips` of `_who`. Returned in two separate positional arrays. * @param _owner The address to get delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOf( address _owner ) external view override returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ) { return _checkReadVpContract().delegatesOf(_owner); } /** * @notice Get the vote power delegation `delegationAddresses` * and `pcts` of `_who`. Returned in two separate positional arrays. * @param _owner The address to get delegations. * @param _blockNumber The block for which we want to know the delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOfAt( address _owner, uint256 _blockNumber ) external view override returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ) { return _checkReadVpContract().delegatesOfAt(_owner, _blockNumber); } // Update vote power and balance checkpoints before balances are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer( address _from, address _to, uint256 _amount ) internal virtual override(ERC20) { require(_from != _to, "Cannot transfer to self"); uint256 fromBalance = _from != address(0) ? balanceOf(_from) : 0; uint256 toBalance = _to != address(0) ? balanceOf(_to) : 0; // update vote powers IIVPContract vpc = writeVpContract; if (address(vpc) != address(0)) { vpc.updateAtTokenTransfer(_from, _to, fromBalance, toBalance, _amount); } else if (!vpContractInitialized) { // transfers without vpcontract are allowed, but after they are made // any added vpcontract must have isReplacement set vpContractInitialized = true; } // update governance vote powers IIGovernanceVotePower gvp = governanceVP; if (address(gvp) != address(0)) { gvp.updateAtTokenTransfer(_from, _to, fromBalance, toBalance, _amount); } // update balance history _updateBalanceHistoryAtTransfer(_from, _to, _amount); } /** * Call from governance to set read VpContract on token, e.g. * `vpToken.setReadVpContract(new VPContract(vpToken))` * Read VPContract must be set before any of the VPToken delegation or vote power reading methods are called, * otherwise they will revert. * NOTE: If readVpContract differs from writeVpContract all reads will be "frozen" and will not reflect * changes (not even revokes; they may or may not reflect balance transfers). * @param _vpContract Read vote power contract to be used by this token. */ function setReadVpContract(IIVPContract _vpContract) external onlyGovernance { if (address(_vpContract) != address(0)) { require(address(_vpContract.ownerToken()) == address(this), "VPContract not owned by this token"); // set contract's cleanup block _vpContract.setCleanupBlockNumber(_cleanupBlockNumber()); } emit VotePowerContractChanged(0, address(readVpContract), address(_vpContract)); readVpContract = _vpContract; } /** * Call from governance to set write VpContract on token, e.g. * `vpToken.setWriteVpContract(new VPContract(vpToken))` * Write VPContract must be set before any of the VPToken delegation modifying methods are called, * otherwise they will revert. * @param _vpContract Write vote power contract to be used by this token. */ function setWriteVpContract(IIVPContract _vpContract) external onlyGovernance { if (address(_vpContract) != address(0)) { require(address(_vpContract.ownerToken()) == address(this), "VPContract not owned by this token"); require(!vpContractInitialized || _vpContract.isReplacement(), "VPContract not configured for replacement"); // set contract's cleanup block _vpContract.setCleanupBlockNumber(_cleanupBlockNumber()); // once a non-null vpcontract is set, every other has to have isReplacement flag set vpContractInitialized = true; } emit VotePowerContractChanged(1, address(writeVpContract), address(_vpContract)); writeVpContract = _vpContract; } /** * Return read vpContract, ensuring that it is not zero. */ function _checkReadVpContract() internal view returns (IIVPContract) { IIVPContract vpc = readVpContract; require(address(vpc) != address(0), "Token missing read VPContract"); return vpc; } /** * Return write vpContract, ensuring that it is not zero. */ function _checkWriteVpContract() internal view returns (IIVPContract) { IIVPContract vpc = writeVpContract; require(address(vpc) != address(0), "Token missing write VPContract"); return vpc; } /** * Return vpContract use for reading, may be zero. */ function _getReadVpContract() internal view returns (IIVPContract) { return readVpContract; } /** * Return vpContract use for writing, may be zero. */ function _getWriteVpContract() internal view returns (IIVPContract) { return writeVpContract; } /** * Returns VPContract event interface used for readonly operations (view methods). */ function readVotePowerContract() external view override returns (IVPContractEvents) { return readVpContract; } /** * Returns VPContract event interface used for state changing operations (non-view methods). */ function writeVotePowerContract() external view override returns (IVPContractEvents) { return writeVpContract; } /** * Set the cleanup block number. * Historic data for the blocks before `cleanupBlockNumber` can be erased, * history before that block should never be used since it can be inconsistent. * In particular, cleanup block number must be before current vote power block. * @param _blockNumber The new cleanup block number. */ function setCleanupBlockNumber(uint256 _blockNumber) external override { require(msg.sender == cleanupBlockNumberManager, "only cleanup block manager"); _setCleanupBlockNumber(_blockNumber); if (address(readVpContract) != address(0)) { readVpContract.setCleanupBlockNumber(_blockNumber); } if (address(writeVpContract) != address(0) && address(writeVpContract) != address(readVpContract)) { writeVpContract.setCleanupBlockNumber(_blockNumber); } if (address(governanceVP) != address(0)) { governanceVP.setCleanupBlockNumber(_blockNumber); } } /** * Get the current cleanup block number. */ function cleanupBlockNumber() external view override returns (uint256) { return _cleanupBlockNumber(); } /** * Set the contract that is allowed to set cleanupBlockNumber. * Usually this will be an instance of CleanupBlockNumberManager. */ function setCleanupBlockNumberManager(address _cleanupBlockNumberManager) external override onlyGovernance { cleanupBlockNumberManager = _cleanupBlockNumberManager; } /** * Set the contract that is allowed to call history cleaning methods. */ function setCleanerContract(address _cleanerContract) external override onlyGovernance { _setCleanerContract(_cleanerContract); if (address(readVpContract) != address(0)) { readVpContract.setCleanerContract(_cleanerContract); } if (address(writeVpContract) != address(0) && address(writeVpContract) != address(readVpContract)) { writeVpContract.setCleanerContract(_cleanerContract); } if (address(governanceVP) != address(0)) { governanceVP.setCleanerContract(_cleanerContract); } } /** * Sets new governance vote power contract that allows token owners to participate in governance voting * and delegate governance vote power. */ function setGovernanceVotePower(IIGovernanceVotePower _governanceVotePower) external override onlyGovernance { require(address(_governanceVotePower.ownerToken()) == address(this), "Governance vote power contract does not belong to this token."); emit VotePowerContractChanged(2, address(governanceVP), address(_governanceVotePower)); governanceVP = _governanceVotePower; } /** * When set, allows token owners to participate in governance voting * and delegate governance vote power. */ function governanceVotePower() external view override returns (IGovernanceVotePower) { return governanceVP; } } // File contracts/token/lib/DelegationHistory.sol /** * @title DelegationHistory library * @notice A contract to manage checkpoints as of a given block. * @dev Store value history by block number with detachable state. **/ library DelegationHistory { using SafeMath for uint256; using SafePct for uint256; using SafeCast for uint256; uint256 public constant MAX_DELEGATES_BY_PERCENT = 2; string private constant MAX_DELEGATES_MSG = "Max delegates exceeded"; struct Delegation { address delegate; uint16 value; // delegations[0] will also hold length and blockNumber to save 1 slot of storage per checkpoint // for all other indexes these fields will be 0 // also, when checkpoint is empty, `length` will automatically be 0, which is ok uint64 fromBlock; uint8 length; // length is limited to MAX_DELEGATES_BY_PERCENT which fits in 8 bits } /** * @dev `CheckPoint` is the structure that attaches a block number to a * given value; the block number attached is the one that last changed the * value **/ struct CheckPoint { // the list of delegations at the time mapping(uint256 => Delegation) delegations; } struct CheckPointHistoryState { // `checkpoints` is an array that tracks delegations at non-contiguous block numbers mapping(uint256 => CheckPoint) checkpoints; // `checkpoints` before `startIndex` have been deleted // INVARIANT: checkpoints.length == 0 || startIndex < checkpoints.length (strict!) uint64 startIndex; uint64 length; } /** * @notice Queries the value at a specific `_blockNumber` * @param _self A CheckPointHistoryState instance to manage. * @param _delegate The delegate for which we need value. * @param _blockNumber The block number of the value active at that time * @return _value The value of the `_delegate` at `_blockNumber` **/ function valueOfAt( CheckPointHistoryState storage _self, address _delegate, uint256 _blockNumber ) internal view returns (uint256 _value) { (bool found, uint256 index) = _findGreatestBlockLessThan(_self, _blockNumber); if (!found) return 0; return _getValueForDelegate(_self.checkpoints[index], _delegate); } /** * @notice Queries the value at `block.number` * @param _self A CheckPointHistoryState instance to manage. * @param _delegate The delegate for which we need value. * @return _value The value at `block.number` **/ function valueOfAtNow( CheckPointHistoryState storage _self, address _delegate ) internal view returns (uint256 _value) { uint256 length = _self.length; if (length == 0) return 0; return _getValueForDelegate(_self.checkpoints[length - 1], _delegate); } /** * @notice Writes the value at the current block. * @param _self A CheckPointHistoryState instance to manage. * @param _delegate The delegate tu update. * @param _value The new value to set for this delegate (value `0` deletes `_delegate` from the list). **/ function writeValue( CheckPointHistoryState storage _self, address _delegate, uint256 _value ) internal { uint256 historyCount = _self.length; if (historyCount == 0) { // checkpoints array empty, push new CheckPoint if (_value != 0) { CheckPoint storage cp = _self.checkpoints[historyCount]; _self.length = SafeCast.toUint64(historyCount + 1); cp.delegations[0] = Delegation({ delegate: _delegate, value: _value.toUint16(), fromBlock: block.number.toUint64(), length: 1 }); } } else { // historyCount - 1 is safe, since historyCount != 0 CheckPoint storage lastCheckpoint = _self.checkpoints[historyCount - 1]; uint256 lastBlock = lastCheckpoint.delegations[0].fromBlock; // slither-disable-next-line incorrect-equality if (block.number == lastBlock) { // If last check point is the current block, just update _updateDelegates(lastCheckpoint, _delegate, _value); } else { // we should never have future blocks in history assert(block.number > lastBlock); // last check point block is before CheckPoint storage cp = _self.checkpoints[historyCount]; _self.length = SafeCast.toUint64(historyCount + 1); _copyAndUpdateDelegates(cp, lastCheckpoint, _delegate, _value); cp.delegations[0].fromBlock = block.number.toUint64(); } } } /** * Get all percentage delegations active at a time. * @param _self A CheckPointHistoryState instance to manage. * @param _blockNumber The block number to query. * @return _delegates The active percentage delegates at the time. * @return _values The delegates' values at the time. **/ function delegationsAt( CheckPointHistoryState storage _self, uint256 _blockNumber ) internal view returns ( address[] memory _delegates, uint256[] memory _values ) { (bool found, uint256 index) = _findGreatestBlockLessThan(_self, _blockNumber); if (!found) { return (new address[](0), new uint256[](0)); } // copy delegates and values to memory arrays // (to prevent caller updating the stored value) CheckPoint storage cp = _self.checkpoints[index]; uint256 length = cp.delegations[0].length; _delegates = new address[](length); _values = new uint256[](length); for (uint256 i = 0; i < length; i++) { Delegation storage dlg = cp.delegations[i]; _delegates[i] = dlg.delegate; _values[i] = dlg.value; } } /** * Get all percentage delegations active now. * @param _self A CheckPointHistoryState instance to manage. * @return _delegates The active percentage delegates. * @return _values The delegates' values. **/ function delegationsAtNow( CheckPointHistoryState storage _self ) internal view returns (address[] memory _delegates, uint256[] memory _values) { return delegationsAt(_self, block.number); } /** * Get all percentage delegations active now. * @param _self A CheckPointHistoryState instance to manage. * @return _length The number of delegations. * @return _delegations . **/ function delegationsAtNowRaw( CheckPointHistoryState storage _self ) internal view returns ( uint256 _length, mapping(uint256 => Delegation) storage _delegations ) { uint256 length = _self.length; if (length == 0) { return (0, _self.checkpoints[0].delegations); } CheckPoint storage cp = _self.checkpoints[length - 1]; return (cp.delegations[0].length, cp.delegations); } /** * Get the number of delegations. * @param _self A CheckPointHistoryState instance to query. * @param _blockNumber The block number to query. * @return _count Count of delegations at the time. **/ function countAt( CheckPointHistoryState storage _self, uint256 _blockNumber ) internal view returns (uint256 _count) { (bool found, uint256 index) = _findGreatestBlockLessThan(_self, _blockNumber); if (!found) return 0; return _self.checkpoints[index].delegations[0].length; } /** * Get the sum of all delegation values. * @param _self A CheckPointHistoryState instance to query. * @param _blockNumber The block number to query. * @return _total Total delegation value at the time. **/ function totalValueAt( CheckPointHistoryState storage _self, uint256 _blockNumber ) internal view returns (uint256 _total) { (bool found, uint256 index) = _findGreatestBlockLessThan(_self, _blockNumber); if (!found) return 0; CheckPoint storage cp = _self.checkpoints[index]; uint256 length = cp.delegations[0].length; _total = 0; for (uint256 i = 0; i < length; i++) { _total = _total.add(cp.delegations[i].value); } } /** * Get the sum of all delegation values. * @param _self A CheckPointHistoryState instance to query. * @return _total Total delegation value at the time. **/ function totalValueAtNow( CheckPointHistoryState storage _self ) internal view returns (uint256 _total) { return totalValueAt(_self, block.number); } /** * Get the sum of all delegation values, every one scaled by `_mul/_div`. * @param _self A CheckPointHistoryState instance to query. * @param _mul The multiplier. * @param _div The divisor. * @param _blockNumber The block number to query. * @return _total Total scaled delegation value at the time. **/ function scaledTotalValueAt( CheckPointHistoryState storage _self, uint256 _mul, uint256 _div, uint256 _blockNumber ) internal view returns (uint256 _total) { (bool found, uint256 index) = _findGreatestBlockLessThan(_self, _blockNumber); if (!found) return 0; CheckPoint storage cp = _self.checkpoints[index]; uint256 length = cp.delegations[0].length; _total = 0; for (uint256 i = 0; i < length; i++) { _total = _total.add(uint256(cp.delegations[i].value).mulDiv(_mul, _div)); } } /** * Clear all delegations at this moment. * @param _self A CheckPointHistoryState instance to manage. */ function clear(CheckPointHistoryState storage _self) internal { uint256 historyCount = _self.length; if (historyCount > 0) { // add an empty checkpoint CheckPoint storage cp = _self.checkpoints[historyCount]; _self.length = SafeCast.toUint64(historyCount + 1); // create empty checkpoint = only set fromBlock cp.delegations[0] = Delegation({ delegate: address(0), value: 0, fromBlock: block.number.toUint64(), length: 0 }); } } /** * Delete at most `_count` of the oldest checkpoints. * At least one checkpoint at or before `_cleanupBlockNumber` will remain * (unless the history was empty to start with). */ function cleanupOldCheckpoints( CheckPointHistoryState storage _self, uint256 _count, uint256 _cleanupBlockNumber ) internal returns (uint256) { if (_cleanupBlockNumber == 0) return 0; // optimization for when cleaning is not enabled uint256 length = _self.length; if (length == 0) return 0; uint256 startIndex = _self.startIndex; // length - 1 is safe, since length != 0 (check above) uint256 endIndex = Math.min(startIndex.add(_count), length - 1); // last element can never be deleted uint256 index = startIndex; // we can delete `checkpoint[index]` while the next checkpoint is at `_cleanupBlockNumber` or before while (index < endIndex && _self.checkpoints[index + 1].delegations[0].fromBlock <= _cleanupBlockNumber) { CheckPoint storage cp = _self.checkpoints[index]; uint256 cplength = cp.delegations[0].length; for (uint256 i = 0; i < cplength; i++) { delete cp.delegations[i]; } index++; } if (index > startIndex) { // index is the first not deleted index _self.startIndex = SafeCast.toUint64(index); } return index - startIndex; // safe: index = startIndex at start and increases in loop } ///////////////////////////////////////////////////////////////////////////////// // helper functions for writeValueAt function _copyAndUpdateDelegates( CheckPoint storage _cp, CheckPoint storage _orig, address _delegate, uint256 _value ) private { uint256 length = _orig.delegations[0].length; bool updated = false; uint256 newlength = 0; for (uint256 i = 0; i < length; i++) { Delegation memory origDlg = _orig.delegations[i]; if (origDlg.delegate == _delegate) { // copy delegate, but with new value newlength = _appendDelegate(_cp, origDlg.delegate, _value, newlength); updated = true; } else { // just copy the delegate with original value newlength = _appendDelegate(_cp, origDlg.delegate, origDlg.value, newlength); } } if (!updated) { // delegate is not in the original list, so add it newlength = _appendDelegate(_cp, _delegate, _value, newlength); } // safe - newlength <= length + 1 <= MAX_DELEGATES_BY_PERCENT _cp.delegations[0].length = uint8(newlength); } function _updateDelegates(CheckPoint storage _cp, address _delegate, uint256 _value) private { uint256 length = _cp.delegations[0].length; uint256 i = 0; while (i < length && _cp.delegations[i].delegate != _delegate) ++i; if (i < length) { if (_value != 0) { _cp.delegations[i].value = _value.toUint16(); } else { _deleteDelegate(_cp, i, length - 1); // length - 1 is safe: 0 <= i < length _cp.delegations[0].length = uint8(length - 1); } } else { uint256 newlength = _appendDelegate(_cp, _delegate, _value, length); _cp.delegations[0].length = uint8(newlength); // safe - length <= MAX_DELEGATES_BY_PERCENT } } function _appendDelegate(CheckPoint storage _cp, address _delegate, uint256 _value, uint256 _length) private returns (uint256) { if (_value != 0) { require(_length < MAX_DELEGATES_BY_PERCENT, MAX_DELEGATES_MSG); Delegation storage dlg = _cp.delegations[_length]; dlg.delegate = _delegate; dlg.value = _value.toUint16(); // for delegations[0], fromBlock and length are assigned outside return _length + 1; } return _length; } function _deleteDelegate(CheckPoint storage _cp, uint256 _index, uint256 _last) private { Delegation storage dlg = _cp.delegations[_index]; Delegation storage lastDlg = _cp.delegations[_last]; if (_index < _last) { dlg.delegate = lastDlg.delegate; dlg.value = lastDlg.value; } lastDlg.delegate = address(0); lastDlg.value = 0; } ///////////////////////////////////////////////////////////////////////////////// // helper functions for querying /** * @notice Binary search of _checkpoints array. * @param _checkpoints An array of CheckPoint to search. * @param _startIndex Smallest possible index to be returned. * @param _blockNumber The block number to search for. */ function _binarySearchGreatestBlockLessThan( mapping(uint256 => CheckPoint) storage _checkpoints, uint256 _startIndex, uint256 _endIndex, uint256 _blockNumber ) private view returns (uint256 _index) { // Binary search of the value by given block number in the array uint256 min = _startIndex; uint256 max = _endIndex.sub(1); while (max > min) { uint256 mid = (max.add(min).add(1)).div(2); if (_checkpoints[mid].delegations[0].fromBlock <= _blockNumber) { min = mid; } else { max = mid.sub(1); } } return min; } /** * @notice Binary search of _checkpoints array. Extra optimized for the common case when we are * searching for the last block. * @param _self The state to query. * @param _blockNumber The block number to search for. * @return _found true if value was found (only `false` if `_blockNumber` is before first * checkpoint or the checkpoint array is empty) * @return _index index of the newest block with number less than or equal `_blockNumber` */ function _findGreatestBlockLessThan( CheckPointHistoryState storage _self, uint256 _blockNumber ) private view returns ( bool _found, uint256 _index ) { uint256 startIndex = _self.startIndex; uint256 historyCount = _self.length; if (historyCount == 0) { _found = false; } else if (_blockNumber >= _self.checkpoints[historyCount - 1].delegations[0].fromBlock) { _found = true; _index = historyCount - 1; // safe, historyCount != 0 in this branch } else if (_blockNumber < _self.checkpoints[startIndex].delegations[0].fromBlock) { // reading data before `_startIndex` is only safe before first cleanup require(startIndex == 0, "DelegationHistory: reading from cleaned-up block"); _found = false; } else { _found = true; _index = _binarySearchGreatestBlockLessThan(_self.checkpoints, startIndex, historyCount, _blockNumber); } } /** * Find delegate and return its value or 0 if not found. */ function _getValueForDelegate(CheckPoint storage _cp, address _delegate) internal view returns (uint256) { uint256 length = _cp.delegations[0].length; for (uint256 i = 0; i < length; i++) { Delegation storage dlg = _cp.delegations[i]; if (dlg.delegate == _delegate) { return dlg.value; } } return 0; // _delegate not found } } // File contracts/token/lib/PercentageDelegation.sol /** * @title PercentageDelegation library * @notice Only handles percentage delegation * @notice A library to manage a group of _delegates for allocating voting power by a delegator. **/ library PercentageDelegation { using CheckPointHistory for CheckPointHistory.CheckPointHistoryState; using DelegationHistory for DelegationHistory.CheckPointHistoryState; using SafeMath for uint256; using SafePct for uint256; uint256 public constant MAX_BIPS = 10000; string private constant MAX_BIPS_MSG = "Max delegation bips exceeded"; /** * @dev `DelegationState` is the state structure used by this library to contain/manage * a grouing of _delegates (a PercentageDelegation) for a delegator. */ struct DelegationState { // percentages by _delegates DelegationHistory.CheckPointHistoryState delegation; } /** * @notice Add or replace an existing _delegate with allocated vote power in basis points. * @param _self A DelegationState instance to manage. * @param _delegate The address of the _delegate to add/replace * @param _bips Allocation of the delegation specified in basis points (1/100 of 1 percent) * @dev If you send a `_bips` of zero, `_delegate` will be deleted if one * exists in the delegation; if zero and `_delegate` does not exist, it will not be added. */ function addReplaceDelegate( DelegationState storage _self, address _delegate, uint256 _bips ) internal { // Check for max delegation basis points assert(_bips <= MAX_BIPS); // Change the delegate's percentage _self.delegation.writeValue(_delegate, _bips); // check the total require(_self.delegation.totalValueAtNow() <= MAX_BIPS, MAX_BIPS_MSG); } /** * @notice Get the total of the explicit vote power delegation bips of all delegates at given block. * @param _self A DelegationState instance to manage. * @param _blockNumber The block to query. * @return _totalBips The total vote power bips delegated. */ function getDelegatedTotalAt( DelegationState storage _self, uint256 _blockNumber ) internal view returns (uint256 _totalBips) { return _self.delegation.totalValueAt(_blockNumber); } /** * @notice Get the total of the bips vote power delegation bips of all _delegates. * @param _self A DelegationState instance to manage. * @return _totalBips The total vote power bips delegated. */ function getDelegatedTotal( DelegationState storage _self ) internal view returns (uint256 _totalBips) { return _self.delegation.totalValueAtNow(); } /** * @notice Given a _delegate address, return the bips of the vote power delegation. * @param _self A DelegationState instance to manage. * @param _delegate The delegate address to find. * @param _blockNumber The block to query. * @return _bips The percent of vote power allocated to the delegate address. */ function getDelegatedValueAt( DelegationState storage _self, address _delegate, uint256 _blockNumber ) internal view returns (uint256 _bips) { return _self.delegation.valueOfAt(_delegate, _blockNumber); } /** * @notice Given a delegate address, return the bips of the vote power delegation. * @param _self A DelegationState instance to manage. * @param _delegate The delegate address to find. * @return _bips The percent of vote power allocated to the delegate address. */ function getDelegatedValue( DelegationState storage _self, address _delegate ) internal view returns (uint256 _bips) { return _self.delegation.valueOfAtNow(_delegate); } /** * @notice Returns lists of delegate addresses and corresponding values at given block. * @param _self A DelegationState instance to manage. * @param _blockNumber The block to query. * @return _delegates Positional array of delegation addresses. * @return _values Positional array of delegation percents specified in basis points (1/100 or 1 percent) */ function getDelegationsAt( DelegationState storage _self, uint256 _blockNumber ) internal view returns ( address[] memory _delegates, uint256[] memory _values ) { return _self.delegation.delegationsAt(_blockNumber); } /** * @notice Returns lists of delegate addresses and corresponding values. * @param _self A DelegationState instance to manage. * @return _delegates Positional array of delegation addresses. * @return _values Positional array of delegation percents specified in basis points (1/100 or 1 percent) */ function getDelegations( DelegationState storage _self ) internal view returns ( address[] memory _delegates, uint256[] memory _values ) { return _self.delegation.delegationsAtNow(); } /** * Get all percentage delegations active now. * @param _self A CheckPointHistoryState instance to manage. * @return _length The number of delegations. * @return _delegations . **/ function getDelegationsRaw( DelegationState storage _self ) internal view returns ( uint256 _length, mapping(uint256 => DelegationHistory.Delegation) storage _delegations ) { return _self.delegation.delegationsAtNowRaw(); } /** * Get the number of delegations. * @param _self A DelegationState instance to manage. * @param _blockNumber The block number to query. * @return _count Count of delegations at the time. **/ function getCountAt( DelegationState storage _self, uint256 _blockNumber ) internal view returns (uint256 _count) { return _self.delegation.countAt(_blockNumber); } /** * Get the number of delegations. * @param _self A DelegationState instance to manage. * @return _count Count of delegations at the time. **/ function getCount( DelegationState storage _self ) internal view returns (uint256 _count) { return _self.delegation.countAt(block.number); } /** * @notice Get the total amount (absolute) of the vote power delegation of all delegates. * @param _self A DelegationState instance to manage. * @param _balance Owner's balance. * @return _totalAmount The total vote power amount delegated. */ function getDelegatedTotalAmountAt( DelegationState storage _self, uint256 _balance, uint256 _blockNumber ) internal view returns (uint256 _totalAmount) { return _self.delegation.scaledTotalValueAt(_balance, MAX_BIPS, _blockNumber); } /** * @notice Clears all delegates. * @param _self A DelegationState instance to manage. * @dev Delegation mode remains PERCENTAGE, even though the delgation is now empty. */ function clear(DelegationState storage _self) internal { _self.delegation.clear(); } /** * Delete at most `_count` of the oldest checkpoints. * At least one checkpoint at or before `_cleanupBlockNumber` will remain * (unless the history was empty to start with). */ function cleanupOldCheckpoints( DelegationState storage _self, uint256 _count, uint256 _cleanupBlockNumber ) internal returns (uint256) { return _self.delegation.cleanupOldCheckpoints(_count, _cleanupBlockNumber); } } // File contracts/token/lib/ExplicitDelegation.sol /** * @title ExplicitDelegation library * @notice A library to manage a group of delegates for allocating voting power by a delegator. **/ library ExplicitDelegation { using CheckPointHistory for CheckPointHistory.CheckPointHistoryState; using CheckPointsByAddress for CheckPointsByAddress.CheckPointsByAddressState; using SafeMath for uint256; using SafePct for uint256; /** * @dev `DelegationState` is the state structure used by this library to contain/manage * a grouing of delegates (a ExplicitDelegation) for a delegator. */ struct DelegationState { CheckPointHistory.CheckPointHistoryState delegatedTotal; // `delegatedVotePower` is a map of delegators pointing to a map of delegates // containing a checkpoint history of delegated vote power balances. CheckPointsByAddress.CheckPointsByAddressState delegatedVotePower; } /** * @notice Add or replace an existing _delegate with new vote power (explicit). * @param _self A DelegationState instance to manage. * @param _delegate The address of the _delegate to add/replace * @param _amount Allocation of the delegation as explicit amount */ function addReplaceDelegate( DelegationState storage _self, address _delegate, uint256 _amount ) internal { uint256 prevAmount = _self.delegatedVotePower.valueOfAtNow(_delegate); uint256 newTotal = _self.delegatedTotal.valueAtNow().sub(prevAmount, "Total < 0").add(_amount); _self.delegatedVotePower.writeValue(_delegate, _amount); _self.delegatedTotal.writeValue(newTotal); } /** * Delete at most `_count` of the oldest checkpoints. * At least one checkpoint at or before `_cleanupBlockNumber` will remain * (unless the history was empty to start with). */ function cleanupOldCheckpoints( DelegationState storage _self, address _owner, uint256 _count, uint256 _cleanupBlockNumber ) internal returns(uint256 _deleted) { _deleted = _self.delegatedTotal.cleanupOldCheckpoints(_count, _cleanupBlockNumber); // safe: cleanupOldCheckpoints always returns the number of deleted elements which is small, so no owerflow _deleted += _self.delegatedVotePower.cleanupOldCheckpoints(_owner, _count, _cleanupBlockNumber); } /** * @notice Get the _total of the explicit vote power delegation amount. * @param _self A DelegationState instance to manage. * @param _blockNumber The block to query. * @return _total The _total vote power amount delegated. */ function getDelegatedTotalAt( DelegationState storage _self, uint256 _blockNumber ) internal view returns (uint256 _total) { return _self.delegatedTotal.valueAt(_blockNumber); } /** * @notice Get the _total of the explicit vote power delegation amount. * @param _self A DelegationState instance to manage. * @return _total The total vote power amount delegated. */ function getDelegatedTotal( DelegationState storage _self ) internal view returns (uint256 _total) { return _self.delegatedTotal.valueAtNow(); } /** * @notice Given a delegate address, return the explicit amount of the vote power delegation. * @param _self A DelegationState instance to manage. * @param _delegate The _delegate address to find. * @param _blockNumber The block to query. * @return _value The percent of vote power allocated to the _delegate address. */ function getDelegatedValueAt( DelegationState storage _self, address _delegate, uint256 _blockNumber ) internal view returns (uint256 _value) { return _self.delegatedVotePower.valueOfAt(_delegate, _blockNumber); } /** * @notice Given a delegate address, return the explicit amount of the vote power delegation. * @param _self A DelegationState instance to manage. * @param _delegate The _delegate address to find. * @return _value The percent of vote power allocated to the _delegate address. */ function getDelegatedValue( DelegationState storage _self, address _delegate ) internal view returns (uint256 _value) { return _self.delegatedVotePower.valueOfAtNow(_delegate); } } // File contracts/token/lib/VotePower.sol /** * @title Vote power library * @notice A library to record delegate vote power balances by delegator * and delegatee. **/ library VotePower { using CheckPointHistory for CheckPointHistory.CheckPointHistoryState; using CheckPointsByAddress for CheckPointsByAddress.CheckPointsByAddressState; using SafeMath for uint256; /** * @dev `VotePowerState` is state structure used by this library to manage vote * power amounts by delegator and it's delegates. */ struct VotePowerState { // `votePowerByAddress` is the map that tracks the voting power balance // of each address, by block. CheckPointsByAddress.CheckPointsByAddressState votePowerByAddress; } /** * @notice This modifier checks that both addresses are non-zero. * @param _delegator A delegator address. * @param _delegatee A delegatee address. */ modifier addressesNotZero(address _delegator, address _delegatee) { // Both addresses cannot be zero assert(!(_delegator == address(0) && _delegatee == address(0))); _; } /** * @notice Delegate vote power `_amount` to `_delegatee` address from `_delegator` address. * @param _delegator Delegator address * @param _delegatee Delegatee address * @param _amount The _amount of vote power to send from _delegator to _delegatee * @dev Amount recorded at the current block. **/ function delegate( VotePowerState storage _self, address _delegator, address _delegatee, uint256 _amount ) internal addressesNotZero(_delegator, _delegatee) { // Shortcut if (_amount == 0) { return; } // Transmit vote power _self.votePowerByAddress.transmit(_delegator, _delegatee, _amount); } /** * @notice Change the current vote power value. * @param _owner Address of vote power owner. * @param _add The amount to add to the vote power. * @param _sub The amount to subtract from the vote power. */ function changeValue( VotePowerState storage _self, address _owner, uint256 _add, uint256 _sub ) internal { assert(_owner != address(0)); if (_add == _sub) return; uint256 value = _self.votePowerByAddress.valueOfAtNow(_owner); value = value.add(_add).sub(_sub); _self.votePowerByAddress.writeValue(_owner, value); } /** * @notice Undelegate vote power `_amount` from `_delegatee` address * to `_delegator` address * @param _delegator Delegator address * @param _delegatee Delegatee address * @param _amount The amount of vote power recovered by delegator from delegatee **/ function undelegate( VotePowerState storage _self, address _delegator, address _delegatee, uint256 _amount ) internal addressesNotZero(_delegator, _delegatee) { // Shortcut if (_amount == 0) { return; } // Recover vote power _self.votePowerByAddress.transmit(_delegatee, _delegator, _amount); } /** * Delete at most `_count` of the oldest checkpoints. * At least one checkpoint at or before `_cleanupBlockNumber` will remain * (unless the history was empty to start with). */ function cleanupOldCheckpoints( VotePowerState storage _self, address _owner, uint256 _count, uint256 _cleanupBlockNumber ) internal returns (uint256) { return _self.votePowerByAddress.cleanupOldCheckpoints(_owner, _count, _cleanupBlockNumber); } /** * @notice Get the vote power of `_who` at `_blockNumber`. * @param _self A VotePowerState instance to manage. * @param _who Address to get vote power. * @param _blockNumber Block number of the block to fetch vote power. * @return _votePower The fetched vote power. */ function votePowerOfAt( VotePowerState storage _self, address _who, uint256 _blockNumber ) internal view returns(uint256 _votePower) { return _self.votePowerByAddress.valueOfAt(_who, _blockNumber); } /** * @notice Get the current vote power of `_who`. * @param _self A VotePowerState instance to manage. * @param _who Address to get vote power. * @return _votePower The fetched vote power. */ function votePowerOfAtNow( VotePowerState storage _self, address _who ) internal view returns(uint256 _votePower) { return _self.votePowerByAddress.valueOfAtNow(_who); } } // File contracts/token/lib/VotePowerCache.sol /** * @title Vote power library * @notice A library to record delegate vote power balances by delegator * and delegatee. **/ library VotePowerCache { using SafeMath for uint256; using VotePower for VotePower.VotePowerState; struct RevocationCacheRecord { // revoking delegation only affects cached value therefore we have to track // the revocation in order not to revoke twice // mapping delegatee => revokedValue mapping(address => uint256) revocations; } /** * @dev `CacheState` is state structure used by this library to manage vote * power amounts by delegator and it's delegates. */ struct CacheState { // map keccak256([address, _blockNumber]) -> (value + 1) mapping(bytes32 => uint256) valueCache; // map keccak256([address, _blockNumber]) -> RevocationCacheRecord mapping(bytes32 => RevocationCacheRecord) revocationCache; } /** * @notice Get the cached value at given block. If there is no cached value, original * value is returned and stored to cache. Cache never gets stale, because original * value can never change in a past block. * @param _self A VotePowerCache instance to manage. * @param _votePower A VotePower instance to read from if cache is empty. * @param _who Address to get vote power. * @param _blockNumber Block number of the block to fetch vote power. * precondition: _blockNumber < block.number */ function valueOfAt( CacheState storage _self, VotePower.VotePowerState storage _votePower, address _who, uint256 _blockNumber ) internal returns (uint256 _value, bool _createdCache) { bytes32 key = keccak256(abi.encode(_who, _blockNumber)); // is it in cache? uint256 cachedValue = _self.valueCache[key]; if (cachedValue != 0) { return (cachedValue - 1, false); // safe, cachedValue != 0 } // read from _votePower uint256 votePowerValue = _votePower.votePowerOfAt(_who, _blockNumber); _writeCacheValue(_self, key, votePowerValue); return (votePowerValue, true); } /** * @notice Get the cached value at given block. If there is no cached value, original * value is returned. Cache is never modified. * @param _self A VotePowerCache instance to manage. * @param _votePower A VotePower instance to read from if cache is empty. * @param _who Address to get vote power. * @param _blockNumber Block number of the block to fetch vote power. * precondition: _blockNumber < block.number */ function valueOfAtReadonly( CacheState storage _self, VotePower.VotePowerState storage _votePower, address _who, uint256 _blockNumber ) internal view returns (uint256 _value) { bytes32 key = keccak256(abi.encode(_who, _blockNumber)); // is it in cache? uint256 cachedValue = _self.valueCache[key]; if (cachedValue != 0) { return cachedValue - 1; // safe, cachedValue != 0 } // read from _votePower return _votePower.votePowerOfAt(_who, _blockNumber); } /** * @notice Delete cached value for `_who` at given block. * Only used for history cleanup. * @param _self A VotePowerCache instance to manage. * @param _who Address to get vote power. * @param _blockNumber Block number of the block to fetch vote power. * @return _deleted The number of cache items deleted (always 0 or 1). * precondition: _blockNumber < cleanupBlockNumber */ function deleteValueAt( CacheState storage _self, address _who, uint256 _blockNumber ) internal returns (uint256 _deleted) { bytes32 key = keccak256(abi.encode(_who, _blockNumber)); if (_self.valueCache[key] != 0) { delete _self.valueCache[key]; return 1; } return 0; } /** * @notice Revoke vote power delegation from `from` to `to` at given block. * Updates cached values for the block, so they are the only vote power values respecting revocation. * @dev Only delegatees cached value is changed, delegator doesn't get the vote power back; so * the revoked vote power is forfeit for as long as this vote power block is in use. This is needed to * prevent double voting. * @param _self A VotePowerCache instance to manage. * @param _votePower A VotePower instance to read from if cache is empty. * @param _from The delegator. * @param _to The delegatee. * @param _revokedValue Value of delegation is not stored here, so it must be supplied by caller. * @param _blockNumber Block number of the block to modify. * precondition: _blockNumber < block.number */ function revokeAt( CacheState storage _self, VotePower.VotePowerState storage _votePower, address _from, address _to, uint256 _revokedValue, uint256 _blockNumber ) internal { if (_revokedValue == 0) return; bytes32 keyFrom = keccak256(abi.encode(_from, _blockNumber)); if (_self.revocationCache[keyFrom].revocations[_to] != 0) { revert("Already revoked"); } // read values and prime cacheOf (uint256 valueTo,) = valueOfAt(_self, _votePower, _to, _blockNumber); // write new values bytes32 keyTo = keccak256(abi.encode(_to, _blockNumber)); _writeCacheValue(_self, keyTo, valueTo.sub(_revokedValue, "Revoked value too large")); // mark as revoked _self.revocationCache[keyFrom].revocations[_to] = _revokedValue; } /** * @notice Delete revocation from `_from` to `_to` at block `_blockNumber`. * Only used for history cleanup. * @param _self A VotePowerCache instance to manage. * @param _from The delegator. * @param _to The delegatee. * @param _blockNumber Block number of the block to modify. * precondition: _blockNumber < cleanupBlockNumber */ function deleteRevocationAt( CacheState storage _self, address _from, address _to, uint256 _blockNumber ) internal returns (uint256 _deleted) { bytes32 keyFrom = keccak256(abi.encode(_from, _blockNumber)); RevocationCacheRecord storage revocationRec = _self.revocationCache[keyFrom]; uint256 value = revocationRec.revocations[_to]; if (value != 0) { delete revocationRec.revocations[_to]; return 1; } return 0; } /** * @notice Returns true if `from` has revoked vote pover delgation of `to` in block `_blockNumber`. * @param _self A VotePowerCache instance to manage. * @param _from The delegator. * @param _to The delegatee. * @param _blockNumber Block number of the block to fetch result. * precondition: _blockNumber < block.number */ function revokedFromToAt( CacheState storage _self, address _from, address _to, uint256 _blockNumber ) internal view returns (bool revoked) { bytes32 keyFrom = keccak256(abi.encode(_from, _blockNumber)); return _self.revocationCache[keyFrom].revocations[_to] != 0; } function _writeCacheValue(CacheState storage _self, bytes32 _key, uint256 _value) private { // store to cacheOf (add 1 to differentiate from empty) _self.valueCache[_key] = _value.add(1); } } // File contracts/token/implementation/Delegatable.sol /** * @title Delegateable ERC20 behavior * @notice An ERC20 Delegateable behavior to delegate voting power * of a token to delegates. This contract orchestrates interaction between * managing a delegation and the vote power allocations that result. **/ contract Delegatable is IVPContractEvents { using PercentageDelegation for PercentageDelegation.DelegationState; using ExplicitDelegation for ExplicitDelegation.DelegationState; using SafeMath for uint256; using SafePct for uint256; using VotePower for VotePower.VotePowerState; using VotePowerCache for VotePowerCache.CacheState; enum DelegationMode { NOTSET, PERCENTAGE, AMOUNT } // The number of history cleanup steps executed for every write operation. // It is more than 1 to make as certain as possible that all history gets cleaned eventually. uint256 private constant CLEANUP_COUNT = 2; string constant private UNDELEGATED_VP_TOO_SMALL_MSG = "Undelegated vote power too small"; // Map that tracks delegation mode of each address. mapping(address => DelegationMode) private delegationModes; // `percentageDelegations` is the map that tracks the percentage voting power delegation of each address. // Explicit delegations are tracked directly through votePower. mapping(address => PercentageDelegation.DelegationState) private percentageDelegations; mapping(address => ExplicitDelegation.DelegationState) private explicitDelegations; // `votePower` tracks all voting power balances VotePower.VotePowerState private votePower; // `votePower` tracks all voting power balances VotePowerCache.CacheState private votePowerCache; // Historic data for the blocks before `cleanupBlockNumber` can be erased, // history before that block should never be used since it can be inconsistent. uint256 private cleanupBlockNumber; // Address of the contract that is allowed to call methods for history cleaning. address public cleanerContract; /** * Emitted when a vote power cache entry is created. * Allows history cleaners to track vote power cache cleanup opportunities off-chain. */ event CreatedVotePowerCache(address _owner, uint256 _blockNumber); // Most history cleanup opportunities can be deduced from standard events: // Transfer(from, to, amount): // - vote power checkpoints for `from` (if nonzero) and `to` (if nonzero) // - vote power checkpoints for percentage delegatees of `from` and `to` are also created, // but they don't have to be checked since Delegate events are also emitted in case of // percentage delegation vote power change due to delegators balance change // - Note: Transfer event is emitted from VPToken but vote power checkpoint delegationModes // must be called on its writeVotePowerContract // Delegate(from, to, priorVP, newVP): // - vote power checkpoints for `from` and `to` // - percentage delegation checkpoint for `from` (if `from` uses percentage delegation mode) // - explicit delegation checkpoint from `from` to `to` (if `from` uses explicit delegation mode) // Revoke(from, to, vp, block): // - vote power cache for `from` and `to` at `block` // - revocation cache block from `from` to `to` at `block` /** * Reading from history is not allowed before `cleanupBlockNumber`, since data before that * might have been deleted and is thus unreliable. */ modifier notBeforeCleanupBlock(uint256 _blockNumber) { require(_blockNumber >= cleanupBlockNumber, "Delegatable: reading from cleaned-up block"); _; } /** * History cleaning methods can be called only from the cleaner address. */ modifier onlyCleaner { require(msg.sender == cleanerContract, "Only cleaner contract"); _; } /** * @notice (Un)Allocate `_owner` vote power of `_amount` across owner delegate * vote power percentages. * @param _owner The address of the vote power owner. * @param _priorBalance The owner's balance before change. * @param _newBalance The owner's balance after change. * @dev precondition: delegationModes[_owner] == DelegationMode.PERCENTAGE */ function _allocateVotePower(address _owner, uint256 _priorBalance, uint256 _newBalance) private { // Get the voting delegation for the _owner PercentageDelegation.DelegationState storage delegation = percentageDelegations[_owner]; // Track total owner vp change uint256 ownerVpAdd = _newBalance; uint256 ownerVpSub = _priorBalance; // Iterate over the delegates (uint256 length, mapping(uint256 => DelegationHistory.Delegation) storage delegations) = delegation.getDelegationsRaw(); for (uint256 i = 0; i < length; i++) { DelegationHistory.Delegation storage dlg = delegations[i]; address delegatee = dlg.delegate; uint256 value = dlg.value; // Compute the delegated vote power for the delegatee uint256 priorValue = _priorBalance.mulDiv(value, PercentageDelegation.MAX_BIPS); uint256 newValue = _newBalance.mulDiv(value, PercentageDelegation.MAX_BIPS); ownerVpAdd = ownerVpAdd.add(priorValue); ownerVpSub = ownerVpSub.add(newValue); // could optimize next lines by checking that priorValue != newValue, but that can only happen // for the transfer of 0 amount, which is prevented by the calling function votePower.changeValue(delegatee, newValue, priorValue); votePower.cleanupOldCheckpoints(delegatee, CLEANUP_COUNT, cleanupBlockNumber); emit Delegate(_owner, delegatee, priorValue, newValue); } // (ownerVpAdd - ownerVpSub) is how much the owner vp changes - will be 0 if delegation is 100% if (ownerVpAdd != ownerVpSub) { votePower.changeValue(_owner, ownerVpAdd, ownerVpSub); votePower.cleanupOldCheckpoints(_owner, CLEANUP_COUNT, cleanupBlockNumber); } } /** * @notice Burn `_amount` of vote power for `_owner`. * @param _owner The address of the _owner vote power to burn. * @param _ownerCurrentBalance The current token balance of the owner (which is their allocatable vote power). * @param _amount The amount of vote power to burn. */ function _burnVotePower(address _owner, uint256 _ownerCurrentBalance, uint256 _amount) internal { // revert with the same error as ERC20 in case transfer exceeds balance uint256 newOwnerBalance = _ownerCurrentBalance.sub(_amount, "ERC20: transfer amount exceeds balance"); if (delegationModes[_owner] == DelegationMode.PERCENTAGE) { // for PERCENTAGE delegation: reduce owner vote power allocations _allocateVotePower(_owner, _ownerCurrentBalance, newOwnerBalance); } else { // for AMOUNT delegation: is there enough unallocated VP _to burn if explicitly delegated? require(_isTransmittable(_owner, _ownerCurrentBalance, _amount), UNDELEGATED_VP_TOO_SMALL_MSG); // burn vote power votePower.changeValue(_owner, 0, _amount); votePower.cleanupOldCheckpoints(_owner, CLEANUP_COUNT, cleanupBlockNumber); } } /** * @notice Get whether `_owner` current delegation can be delegated by percentage. * @param _owner Address of delegation to check. * @return True if delegation can be delegated by percentage. */ function _canDelegateByPct(address _owner) internal view returns(bool) { // Get the delegation mode. DelegationMode delegationMode = delegationModes[_owner]; // Return true if delegation is safe _to store percents, which can also // apply if there is not delegation mode set. return delegationMode == DelegationMode.NOTSET || delegationMode == DelegationMode.PERCENTAGE; } /** * @notice Get whether `_owner` current delegation can be delegated by amount. * @param _owner Address of delegation to check. * @return True if delegation can be delegated by amount. */ function _canDelegateByAmount(address _owner) internal view returns(bool) { // Get the delegation mode. DelegationMode delegationMode = delegationModes[_owner]; // Return true if delegation is safe to store explicit amounts, which can also // apply if there is not delegation mode set. return delegationMode == DelegationMode.NOTSET || delegationMode == DelegationMode.AMOUNT; } /** * @notice Delegate `_amount` of voting power to `_to` from `_from` * @param _from The address of the delegator * @param _to The address of the recipient * @param _senderCurrentBalance The senders current balance (not their voting power) * @param _amount The amount of voting power to be delegated **/ function _delegateByAmount( address _from, address _to, uint256 _senderCurrentBalance, uint256 _amount ) internal virtual { require (_to != address(0), "Cannot delegate to zero"); require (_to != _from, "Cannot delegate to self"); require (_canDelegateByAmount(_from), "Cannot delegate by amount"); // Get the vote power delegation for the sender ExplicitDelegation.DelegationState storage delegation = explicitDelegations[_from]; // the prior value uint256 priorAmount = delegation.getDelegatedValue(_to); // Delegate new power if (_amount < priorAmount) { // Prior amount is greater, just reduce the delegated amount. // subtraction is safe since _amount < priorAmount votePower.undelegate(_from, _to, priorAmount - _amount); } else { // Is there enough undelegated vote power? uint256 availableAmount = _undelegatedVotePowerOf(_from, _senderCurrentBalance).add(priorAmount); require(availableAmount >= _amount, UNDELEGATED_VP_TOO_SMALL_MSG); // Increase the delegated amount of vote power. // subtraction is safe since _amount >= priorAmount votePower.delegate(_from, _to, _amount - priorAmount); } votePower.cleanupOldCheckpoints(_from, CLEANUP_COUNT, cleanupBlockNumber); votePower.cleanupOldCheckpoints(_to, CLEANUP_COUNT, cleanupBlockNumber); // Add/replace delegate delegation.addReplaceDelegate(_to, _amount); delegation.cleanupOldCheckpoints(_to, CLEANUP_COUNT, cleanupBlockNumber); // update mode if needed if (delegationModes[_from] != DelegationMode.AMOUNT) { delegationModes[_from] = DelegationMode.AMOUNT; } // emit event for delegation change emit Delegate(_from, _to, priorAmount, _amount); } /** * @notice Delegate `_bips` of voting power to `_to` from `_from` * @param _from The address of the delegator * @param _to The address of the recipient * @param _senderCurrentBalance The senders current balance (not their voting power) * @param _bips The percentage of voting power in basis points (1/100 of 1 percent) to be delegated **/ function _delegateByPercentage( address _from, address _to, uint256 _senderCurrentBalance, uint256 _bips ) internal virtual { require (_to != address(0), "Cannot delegate to zero"); require (_to != _from, "Cannot delegate to self"); require (_canDelegateByPct(_from), "Cannot delegate by percentage"); // Get the vote power delegation for the sender PercentageDelegation.DelegationState storage delegation = percentageDelegations[_from]; // Get prior percent for delegate if exists uint256 priorBips = delegation.getDelegatedValue(_to); uint256 reverseVotePower = 0; uint256 newVotePower = 0; // Add/replace delegate delegation.addReplaceDelegate(_to, _bips); delegation.cleanupOldCheckpoints(CLEANUP_COUNT, cleanupBlockNumber); // First, back out old voting power percentage, if not zero if (priorBips != 0) { reverseVotePower = _senderCurrentBalance.mulDiv(priorBips, PercentageDelegation.MAX_BIPS); } // Calculate the new vote power if (_bips != 0) { newVotePower = _senderCurrentBalance.mulDiv(_bips, PercentageDelegation.MAX_BIPS); } // Delegate new power if (newVotePower < reverseVotePower) { // subtraction is safe since newVotePower < reverseVotePower votePower.undelegate(_from, _to, reverseVotePower - newVotePower); } else { // subtraction is safe since newVotePower >= reverseVotePower votePower.delegate(_from, _to, newVotePower - reverseVotePower); } votePower.cleanupOldCheckpoints(_from, CLEANUP_COUNT, cleanupBlockNumber); votePower.cleanupOldCheckpoints(_to, CLEANUP_COUNT, cleanupBlockNumber); // update mode if needed if (delegationModes[_from] != DelegationMode.PERCENTAGE) { delegationModes[_from] = DelegationMode.PERCENTAGE; } // emit event for delegation change emit Delegate(_from, _to, reverseVotePower, newVotePower); } /** * @notice Get the delegation mode for '_who'. This mode determines whether vote power is * allocated by percentage or by explicit value. * @param _who The address to get delegation mode. * @return Delegation mode */ function _delegationModeOf(address _who) internal view returns (DelegationMode) { return delegationModes[_who]; } /** * @notice Get the vote power delegation `delegationAddresses` * and `_bips` of an `_owner`. Returned in two separate positional arrays. * @param _owner The address to get delegations. * @param _blockNumber The block for which we want to know the delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) */ function _percentageDelegatesOfAt( address _owner, uint256 _blockNumber ) internal view notBeforeCleanupBlock(_blockNumber) returns ( address[] memory _delegateAddresses, uint256[] memory _bips ) { PercentageDelegation.DelegationState storage delegation = percentageDelegations[_owner]; address[] memory allDelegateAddresses; uint256[] memory allBips; (allDelegateAddresses, allBips) = delegation.getDelegationsAt(_blockNumber); // delete revoked addresses for (uint256 i = 0; i < allDelegateAddresses.length; i++) { if (votePowerCache.revokedFromToAt(_owner, allDelegateAddresses[i], _blockNumber)) { allBips[i] = 0; } } uint256 length = 0; for (uint256 i = 0; i < allDelegateAddresses.length; i++) { if (allBips[i] != 0) length++; } _delegateAddresses = new address[](length); _bips = new uint256[](length); uint256 destIndex = 0; for (uint256 i = 0; i < allDelegateAddresses.length; i++) { if (allBips[i] != 0) { _delegateAddresses[destIndex] = allDelegateAddresses[i]; _bips[destIndex] = allBips[i]; destIndex++; } } } /** * @notice Checks if enough undelegated vote power exists to allow a token * transfer to occur if vote power is explicitly delegated. * @param _owner The address of transmittable vote power to check. * @param _ownerCurrentBalance The current balance of `_owner`. * @param _amount The amount to check. * @return True is `_amount` is transmittable. */ function _isTransmittable( address _owner, uint256 _ownerCurrentBalance, uint256 _amount ) private view returns(bool) { // Only proceed if we have a delegation by _amount if (delegationModes[_owner] == DelegationMode.AMOUNT) { // Return true if there is enough vote power _to cover the transfer return _undelegatedVotePowerOf(_owner, _ownerCurrentBalance) >= _amount; } else { // Not delegated by _amount, so transfer always allowed return true; } } /** * @notice Mint `_amount` of vote power for `_owner`. * @param _owner The address of the owner to receive new vote power. * @param _amount The amount of vote power to mint. */ function _mintVotePower(address _owner, uint256 _ownerCurrentBalance, uint256 _amount) internal { if (delegationModes[_owner] == DelegationMode.PERCENTAGE) { // Allocate newly minted vote power over delegates _allocateVotePower(_owner, _ownerCurrentBalance, _ownerCurrentBalance.add(_amount)); } else { votePower.changeValue(_owner, _amount, 0); votePower.cleanupOldCheckpoints(_owner, CLEANUP_COUNT, cleanupBlockNumber); } } /** * @notice Revoke the vote power of `_to` at block `_blockNumber` * @param _from The address of the delegator * @param _to The delegatee address of vote power to revoke. * @param _senderBalanceAt The sender's balance at the block to be revoked. * @param _blockNumber The block number at which to revoke. */ function _revokeDelegationAt( address _from, address _to, uint256 _senderBalanceAt, uint256 _blockNumber ) internal notBeforeCleanupBlock(_blockNumber) { require(_blockNumber < block.number, "Revoke is only for the past, use undelegate for the present"); // Get amount revoked uint256 votePowerRevoked = _votePowerFromToAtNoRevokeCheck(_from, _to, _senderBalanceAt, _blockNumber); // Revoke vote power votePowerCache.revokeAt(votePower, _from, _to, votePowerRevoked, _blockNumber); // Emit revoke event emit Revoke(_from, _to, votePowerRevoked, _blockNumber); } /** * @notice Transmit `_amount` of vote power `_from` address `_to` address. * @param _from The address of the sender. * @param _to The address of the receiver. * @param _fromCurrentBalance The current token balance of the transmitter. * @param _toCurrentBalance The current token balance of the receiver. * @param _amount The amount of vote power to transmit. */ function _transmitVotePower( address _from, address _to, uint256 _fromCurrentBalance, uint256 _toCurrentBalance, uint256 _amount ) internal { _burnVotePower(_from, _fromCurrentBalance, _amount); _mintVotePower(_to, _toCurrentBalance, _amount); } /** * @notice Undelegate all vote power by percentage for `delegation` of `_who`. * @param _from The address of the delegator * @param _senderCurrentBalance The current balance of message sender. * precondition: delegationModes[_who] == DelegationMode.PERCENTAGE */ function _undelegateAllByPercentage(address _from, uint256 _senderCurrentBalance) internal { DelegationMode delegationMode = delegationModes[_from]; if (delegationMode == DelegationMode.NOTSET) return; require(delegationMode == DelegationMode.PERCENTAGE, "undelegateAll can only be used in percentage delegation mode"); PercentageDelegation.DelegationState storage delegation = percentageDelegations[_from]; // Iterate over the delegates (address[] memory delegates, uint256[] memory _bips) = delegation.getDelegations(); for (uint256 i = 0; i < delegates.length; i++) { address to = delegates[i]; // Compute vote power to be reversed for the delegate uint256 reverseVotePower = _senderCurrentBalance.mulDiv(_bips[i], PercentageDelegation.MAX_BIPS); // Transmit vote power back to _owner votePower.undelegate(_from, to, reverseVotePower); votePower.cleanupOldCheckpoints(_from, CLEANUP_COUNT, cleanupBlockNumber); votePower.cleanupOldCheckpoints(to, CLEANUP_COUNT, cleanupBlockNumber); // Emit vote power reversal event emit Delegate(_from, to, reverseVotePower, 0); } // Clear delegates delegation.clear(); delegation.cleanupOldCheckpoints(CLEANUP_COUNT, cleanupBlockNumber); } /** * @notice Undelegate all vote power by amount delegates for `_from`. * @param _from The address of the delegator * @param _delegateAddresses Explicit delegation does not store delegatees' addresses, * so the caller must supply them. */ function _undelegateAllByAmount( address _from, address[] memory _delegateAddresses ) internal returns (uint256 _remainingDelegation) { DelegationMode delegationMode = delegationModes[_from]; if (delegationMode == DelegationMode.NOTSET) return 0; require(delegationMode == DelegationMode.AMOUNT, "undelegateAllExplicit can only be used in explicit delegation mode"); ExplicitDelegation.DelegationState storage delegation = explicitDelegations[_from]; // Iterate over the delegates for (uint256 i = 0; i < _delegateAddresses.length; i++) { address to = _delegateAddresses[i]; // Compute vote power _to be reversed for the delegate uint256 reverseVotePower = delegation.getDelegatedValue(to); if (reverseVotePower == 0) continue; // Transmit vote power back _to _owner votePower.undelegate(_from, to, reverseVotePower); votePower.cleanupOldCheckpoints(_from, CLEANUP_COUNT, cleanupBlockNumber); votePower.cleanupOldCheckpoints(to, CLEANUP_COUNT, cleanupBlockNumber); // change delagation delegation.addReplaceDelegate(to, 0); delegation.cleanupOldCheckpoints(to, CLEANUP_COUNT, cleanupBlockNumber); // Emit vote power reversal event emit Delegate(_from, to, reverseVotePower, 0); } return delegation.getDelegatedTotal(); } /** * @notice Check if the `_owner` has made any delegations. * @param _owner The address of owner to get delegated vote power. * @return The total delegated vote power at block. */ function _hasAnyDelegations(address _owner) internal view returns(bool) { DelegationMode delegationMode = delegationModes[_owner]; if (delegationMode == DelegationMode.NOTSET) { return false; } else if (delegationMode == DelegationMode.AMOUNT) { return explicitDelegations[_owner].getDelegatedTotal() > 0; } else { // delegationMode == DelegationMode.PERCENTAGE return percentageDelegations[_owner].getCount() > 0; } } /** * @notice Get the total delegated vote power of `_owner` at some block. * @param _owner The address of owner to get delegated vote power. * @param _ownerBalanceAt The balance of the owner at that block (not their vote power). * @param _blockNumber The block number at which to fetch. * @return _votePower The total delegated vote power at block. */ function _delegatedVotePowerOfAt( address _owner, uint256 _ownerBalanceAt, uint256 _blockNumber ) internal view notBeforeCleanupBlock(_blockNumber) returns(uint256 _votePower) { // Get the vote power delegation for the _owner DelegationMode delegationMode = delegationModes[_owner]; if (delegationMode == DelegationMode.NOTSET) { return 0; } else if (delegationMode == DelegationMode.AMOUNT) { return explicitDelegations[_owner].getDelegatedTotalAt(_blockNumber); } else { // delegationMode == DelegationMode.PERCENTAGE return percentageDelegations[_owner].getDelegatedTotalAmountAt(_ownerBalanceAt, _blockNumber); } } /** * @notice Get the undelegated vote power of `_owner` at some block. * @param _owner The address of owner to get undelegated vote power. * @param _ownerBalanceAt The balance of the owner at that block (not their vote power). * @param _blockNumber The block number at which to fetch. * @return _votePower The undelegated vote power at block. */ function _undelegatedVotePowerOfAt( address _owner, uint256 _ownerBalanceAt, uint256 _blockNumber ) internal view notBeforeCleanupBlock(_blockNumber) returns(uint256 _votePower) { // Return the current balance less delegations or zero if negative uint256 delegated = _delegatedVotePowerOfAt(_owner, _ownerBalanceAt, _blockNumber); bool overflow; uint256 result; (overflow, result) = _ownerBalanceAt.trySub(delegated); return result; } /** * @notice Get the undelegated vote power of `_owner`. * @param _owner The address of owner to get undelegated vote power. * @param _ownerCurrentBalance The current balance of the owner (not their vote power). * @return _votePower The undelegated vote power. */ function _undelegatedVotePowerOf( address _owner, uint256 _ownerCurrentBalance ) internal view returns(uint256 _votePower) { return _undelegatedVotePowerOfAt(_owner, _ownerCurrentBalance, block.number); } /** * @notice Get current delegated vote power `_from` delegator delegated `_to` delegatee. * @param _from Address of delegator * @param _to Address of delegatee * @return _votePower The delegated vote power. */ function _votePowerFromTo( address _from, address _to, uint256 _currentFromBalance ) internal view returns(uint256 _votePower) { DelegationMode delegationMode = delegationModes[_from]; if (delegationMode == DelegationMode.NOTSET) { return 0; } else if (delegationMode == DelegationMode.PERCENTAGE) { uint256 _bips = percentageDelegations[_from].getDelegatedValue(_to); return _currentFromBalance.mulDiv(_bips, PercentageDelegation.MAX_BIPS); } else { // delegationMode == DelegationMode.AMOUNT return explicitDelegations[_from].getDelegatedValue(_to); } } /** * @notice Get delegated the vote power `_from` delegator delegated `_to` delegatee at `_blockNumber`. * @param _from Address of delegator * @param _to Address of delegatee * @param _fromBalanceAt From's balance at the block `_blockNumber`. * @param _blockNumber The block number at which to fetch. * @return _votePower The delegated vote power. */ function _votePowerFromToAt( address _from, address _to, uint256 _fromBalanceAt, uint256 _blockNumber ) internal view notBeforeCleanupBlock(_blockNumber) returns(uint256 _votePower) { // if revoked, return 0 if (votePowerCache.revokedFromToAt(_from, _to, _blockNumber)) return 0; return _votePowerFromToAtNoRevokeCheck(_from, _to, _fromBalanceAt, _blockNumber); } /** * @notice Get delegated the vote power `_from` delegator delegated `_to` delegatee at `_blockNumber`. * Private use only - ignores revocations. * @param _from Address of delegator * @param _to Address of delegatee * @param _fromBalanceAt From's balance at the block `_blockNumber`. * @param _blockNumber The block number at which to fetch. * @return _votePower The delegated vote power. */ function _votePowerFromToAtNoRevokeCheck( address _from, address _to, uint256 _fromBalanceAt, uint256 _blockNumber ) private view returns(uint256 _votePower) { // assumed: notBeforeCleanupBlock(_blockNumber) DelegationMode delegationMode = delegationModes[_from]; if (delegationMode == DelegationMode.NOTSET) { return 0; } else if (delegationMode == DelegationMode.PERCENTAGE) { uint256 _bips = percentageDelegations[_from].getDelegatedValueAt(_to, _blockNumber); return _fromBalanceAt.mulDiv(_bips, PercentageDelegation.MAX_BIPS); } else { // delegationMode == DelegationMode.AMOUNT return explicitDelegations[_from].getDelegatedValueAt(_to, _blockNumber); } } /** * @notice Get the current vote power of `_who`. * @param _who The address to get voting power. * @return Current vote power of `_who`. */ function _votePowerOf(address _who) internal view returns(uint256) { return votePower.votePowerOfAtNow(_who); } /** * @notice Get the vote power of `_who` at block `_blockNumber` * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. */ function _votePowerOfAt( address _who, uint256 _blockNumber ) internal view notBeforeCleanupBlock(_blockNumber) returns(uint256) { // read cached value for past blocks to respect revocations (and possibly get a cache speedup) if (_blockNumber < block.number) { return votePowerCache.valueOfAtReadonly(votePower, _who, _blockNumber); } else { return votePower.votePowerOfAtNow(_who); } } /** * @notice Get the vote power of `_who` at block `_blockNumber`, ignoring revocation information (and cache). * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. Result doesn't change if vote power is revoked. */ function _votePowerOfAtIgnoringRevocation( address _who, uint256 _blockNumber ) internal view notBeforeCleanupBlock(_blockNumber) returns(uint256) { return votePower.votePowerOfAt(_who, _blockNumber); } /** * Return vote powers for several addresses in a batch. * Only works for past blocks. * @param _owners The list of addresses to fetch vote power of. * @param _blockNumber The block number at which to fetch. * @return _votePowers A list of vote powers corresponding to _owners. */ function _batchVotePowerOfAt( address[] memory _owners, uint256 _blockNumber ) internal view notBeforeCleanupBlock(_blockNumber) returns(uint256[] memory _votePowers) { require(_blockNumber < block.number, "Can only be used for past blocks"); _votePowers = new uint256[](_owners.length); for (uint256 i = 0; i < _owners.length; i++) { // read through cache, much faster if it has been set _votePowers[i] = votePowerCache.valueOfAtReadonly(votePower, _owners[i], _blockNumber); } } /** * @notice Get the vote power of `_who` at block `_blockNumber` * Reads/updates cache and upholds revocations. * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. */ function _votePowerOfAtCached( address _who, uint256 _blockNumber ) internal notBeforeCleanupBlock(_blockNumber) returns(uint256) { require(_blockNumber < block.number, "Can only be used for past blocks"); (uint256 vp, bool createdCache) = votePowerCache.valueOfAt(votePower, _who, _blockNumber); if (createdCache) emit CreatedVotePowerCache(_who, _blockNumber); return vp; } /** * Set the cleanup block number. */ function _setCleanupBlockNumber(uint256 _blockNumber) internal { require(_blockNumber >= cleanupBlockNumber, "Cleanup block number must never decrease"); require(_blockNumber < block.number, "Cleanup block must be in the past"); cleanupBlockNumber = _blockNumber; } /** * Get the cleanup block number. */ function _cleanupBlockNumber() internal view returns (uint256) { return cleanupBlockNumber; } /** * Set the contract that is allowed to call history cleaning methods. */ function _setCleanerContract(address _cleanerContract) internal { cleanerContract = _cleanerContract; } // history cleanup methods /** * Delete vote power checkpoints that expired (i.e. are before `cleanupBlockNumber`). * Method can only be called from the `cleanerContract` (which may be a proxy to external cleaners). * @param _owner vote power owner account address * @param _count maximum number of checkpoints to delete * @return the number of checkpoints deleted */ function votePowerHistoryCleanup(address _owner, uint256 _count) external onlyCleaner returns (uint256) { return votePower.cleanupOldCheckpoints(_owner, _count, cleanupBlockNumber); } /** * Delete vote power cache entry that expired (i.e. is before `cleanupBlockNumber`). * Method can only be called from the `cleanerContract` (which may be a proxy to external cleaners). * @param _owner vote power owner account address * @param _blockNumber the block number for which total supply value was cached * @return the number of cache entries deleted (always 0 or 1) */ function votePowerCacheCleanup(address _owner, uint256 _blockNumber) external onlyCleaner returns (uint256) { require(_blockNumber < cleanupBlockNumber, "No cleanup after cleanup block"); return votePowerCache.deleteValueAt(_owner, _blockNumber); } /** * Delete revocation entry that expired (i.e. is before `cleanupBlockNumber`). * Method can only be called from the `cleanerContract` (which may be a proxy to external cleaners). * @param _from the delegator address * @param _to the delegatee address * @param _blockNumber the block number for which total supply value was cached * @return the number of revocation entries deleted (always 0 or 1) */ function revocationCleanup( address _from, address _to, uint256 _blockNumber ) external onlyCleaner returns (uint256) { require(_blockNumber < cleanupBlockNumber, "No cleanup after cleanup block"); return votePowerCache.deleteRevocationAt(_from, _to, _blockNumber); } /** * Delete percentage delegation checkpoints that expired (i.e. are before `cleanupBlockNumber`). * Method can only be called from the `cleanerContract` (which may be a proxy to external cleaners). * @param _owner balance owner account address * @param _count maximum number of checkpoints to delete * @return the number of checkpoints deleted */ function percentageDelegationHistoryCleanup(address _owner, uint256 _count) external onlyCleaner returns (uint256) { return percentageDelegations[_owner].cleanupOldCheckpoints(_count, cleanupBlockNumber); } /** * Delete explicit delegation checkpoints that expired (i.e. are before `cleanupBlockNumber`). * Method can only be called from the `cleanerContract` (which may be a proxy to external cleaners). * @param _from the delegator address * @param _to the delegatee address * @param _count maximum number of checkpoints to delete * @return the number of checkpoints deleted */ function explicitDelegationHistoryCleanup(address _from, address _to, uint256 _count) external onlyCleaner returns (uint256) { return explicitDelegations[_from].cleanupOldCheckpoints(_to, _count, cleanupBlockNumber); } } // File contracts/token/implementation/VPContract.sol contract VPContract is IIVPContract, Delegatable { using SafeMath for uint256; /** * The VPToken (or some other contract) that owns this VPContract. * All state changing methods may be called only from this address. * This is because original msg.sender is sent in `_from` parameter * and we must be sure that it cannot be faked by directly calling VPContract. * Owner token is also used in case of replacement to recover vote powers from balances. */ IVPToken public immutable override ownerToken; /** * Return true if this IIVPContract is configured to be used as a replacement for other contract. * It means that vote powers are not necessarily correct at the initialization, therefore * every method that reads vote power must check whether it is initialized for that address and block. */ bool public immutable override isReplacement; // The block number when vote power for an address was first set. // Reading vote power before this block would return incorrect result and must revert. mapping (address => uint256) private votePowerInitializationBlock; // Vote power cache for past blocks when vote power was not initialized. // Reading vote power at that block would return incorrect result, so cache must be set by some other means. // No need for revocation info, since there can be no delegations at such block. mapping (bytes32 => uint256) private uninitializedVotePowerCache; string constant private ALREADY_EXPLICIT_MSG = "Already delegated explicitly"; string constant private ALREADY_PERCENT_MSG = "Already delegated by percentage"; string constant internal VOTE_POWER_NOT_INITIALIZED = "Vote power not initialized"; /** * All external methods in VPContract can only be executed by the owner token. */ modifier onlyOwnerToken { require(msg.sender == address(ownerToken), "only owner token"); _; } modifier onlyPercent(address sender) { // If a delegate cannot be added by percentage, revert. require(_canDelegateByPct(sender), ALREADY_EXPLICIT_MSG); _; } modifier onlyExplicit(address sender) { // If a delegate cannot be added by explicit amount, revert. require(_canDelegateByAmount(sender), ALREADY_PERCENT_MSG); _; } /** * Construct VPContract for given VPToken. */ constructor(IVPToken _ownerToken, bool _isReplacement) { require(address(_ownerToken) != address(0), "VPContract must belong to a VPToken"); ownerToken = _ownerToken; isReplacement = _isReplacement; } /** * Set the cleanup block number. * Historic data for the blocks before `cleanupBlockNumber` can be erased, * history before that block should never be used since it can be inconsistent. * In particular, cleanup block number must be before current vote power block. * The method can be called only by the owner token. * @param _blockNumber The new cleanup block number. */ function setCleanupBlockNumber(uint256 _blockNumber) external override onlyOwnerToken { _setCleanupBlockNumber(_blockNumber); } /** * Set the contract that is allowed to call history cleaning methods. * The method can be called only by the owner token. */ function setCleanerContract(address _cleanerContract) external override onlyOwnerToken { _setCleanerContract(_cleanerContract); } /** * Update vote powers when tokens are transfered. * Also update delegated vote powers for percentage delegation * and check for enough funds for explicit delegations. **/ function updateAtTokenTransfer( address _from, address _to, uint256 _fromBalance, uint256 _toBalance, uint256 _amount ) external override onlyOwnerToken { if (_from == address(0)) { // mint new vote power _initializeVotePower(_to, _toBalance); _mintVotePower(_to, _toBalance, _amount); } else if (_to == address(0)) { // burn vote power _initializeVotePower(_from, _fromBalance); _burnVotePower(_from, _fromBalance, _amount); } else { // transmit vote power _to receiver _initializeVotePower(_from, _fromBalance); _initializeVotePower(_to, _toBalance); _transmitVotePower(_from, _to, _fromBalance, _toBalance, _amount); } } /** * @notice Delegate `_bips` percentage of voting power to `_to` from `_from` * @param _from The address of the delegator * @param _to The address of the recipient * @param _balance The delegator's current balance * @param _bips The percentage of voting power to be delegated expressed in basis points (1/100 of one percent). * Not cumulative - every call resets the delegation value (and value of 0 revokes delegation). **/ function delegate( address _from, address _to, uint256 _balance, uint256 _bips ) external override onlyOwnerToken onlyPercent(_from) { _initializeVotePower(_from, _balance); if (!_votePowerInitialized(_to)) { _initializeVotePower(_to, ownerToken.balanceOf(_to)); } _delegateByPercentage(_from, _to, _balance, _bips); } /** * @notice Explicitly delegate `_amount` of voting power to `_to` from `_from`. * @param _from The address of the delegator * @param _to The address of the recipient * @param _balance The delegator's current balance * @param _amount An explicit vote power amount to be delegated. * Not cumulative - every call resets the delegation value (and value of 0 undelegates `to`). **/ function delegateExplicit( address _from, address _to, uint256 _balance, uint _amount ) external override onlyOwnerToken onlyExplicit(_from) { _initializeVotePower(_from, _balance); if (!_votePowerInitialized(_to)) { _initializeVotePower(_to, ownerToken.balanceOf(_to)); } _delegateByAmount(_from, _to, _balance, _amount); } /** * @notice Revoke all delegation from `_from` to `_to` at given block. * Only affects the reads via `votePowerOfAtCached()` in the block `_blockNumber`. * Block `_blockNumber` must be in the past. * This method should be used only to prevent rogue delegate voting in the current voting block. * To stop delegating use delegate/delegateExplicit with value of 0 or undelegateAll/undelegateAllExplicit. * @param _from The address of the delegator * @param _to Address of the delegatee * @param _balance The delegator's current balance * @param _blockNumber The block number at which to revoke delegation. **/ function revokeDelegationAt( address _from, address _to, uint256 _balance, uint _blockNumber ) external override onlyOwnerToken { // ASSERT: if there was a delegation, _from and _to must be initialized if (!isReplacement || (_votePowerInitializedAt(_from, _blockNumber) && _votePowerInitializedAt(_to, _blockNumber))) { _revokeDelegationAt(_from, _to, _balance, _blockNumber); } } /** * @notice Undelegate all voting power for delegates of `_from` * Can only be used with percentage delegation. * Does not reset delegation mode back to NOTSET. * @param _from The address of the delegator **/ function undelegateAll( address _from, uint256 _balance ) external override onlyOwnerToken onlyPercent(_from) { if (_hasAnyDelegations(_from)) { // ASSERT: since there were delegations, _from and its targets must be initialized _undelegateAllByPercentage(_from, _balance); } } /** * @notice Undelegate all explicit vote power by amount delegates for `_from`. * Can only be used with explicit delegation. * Does not reset delegation mode back to NOTSET. * @param _from The address of the delegator * @param _delegateAddresses Explicit delegation does not store delegatees' addresses, * so the caller must supply them. * @return The amount still delegated (in case the list of delegates was incomplete). */ function undelegateAllExplicit( address _from, address[] memory _delegateAddresses ) external override onlyOwnerToken onlyExplicit(_from) returns (uint256) { if (_hasAnyDelegations(_from)) { // ASSERT: since there were delegations, _from and its targets must be initialized return _undelegateAllByAmount(_from, _delegateAddresses); } return 0; } /** * @notice Get the vote power of `_who` at block `_blockNumber` * Reads/updates cache and upholds revocations. * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. */ function votePowerOfAtCached(address _who, uint256 _blockNumber) external override returns(uint256) { if (!isReplacement || _votePowerInitializedAt(_who, _blockNumber)) { // use standard method return _votePowerOfAtCached(_who, _blockNumber); } else { // use uninitialized vote power cache bytes32 key = keccak256(abi.encode(_who, _blockNumber)); uint256 cached = uninitializedVotePowerCache[key]; if (cached != 0) { return cached - 1; // safe, cached != 0 } uint256 balance = ownerToken.balanceOfAt(_who, _blockNumber); uninitializedVotePowerCache[key] = balance.add(1); return balance; } } /** * Get the current cleanup block number. */ function cleanupBlockNumber() external view override returns (uint256) { return _cleanupBlockNumber(); } /** * @notice Get the current vote power of `_who`. * @param _who The address to get voting power. * @return Current vote power of `_who`. */ function votePowerOf(address _who) external view override returns(uint256) { if (_votePowerInitialized(_who)) { return _votePowerOf(_who); } else { return ownerToken.balanceOf(_who); } } /** * @notice Get the vote power of `_who` at block `_blockNumber` * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. */ function votePowerOfAt(address _who, uint256 _blockNumber) public view override returns(uint256) { if (!isReplacement || _votePowerInitializedAt(_who, _blockNumber)) { return _votePowerOfAt(_who, _blockNumber); } else { return ownerToken.balanceOfAt(_who, _blockNumber); } } /** * @notice Get the vote power of `_who` at block `_blockNumber`, ignoring revocation information (and cache). * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. Result doesn't change if vote power is revoked. */ function votePowerOfAtIgnoringRevocation(address _who, uint256 _blockNumber) external view override returns(uint256) { if (!isReplacement || _votePowerInitializedAt(_who, _blockNumber)) { return _votePowerOfAtIgnoringRevocation(_who, _blockNumber); } else { return ownerToken.balanceOfAt(_who, _blockNumber); } } /** * Return vote powers for several addresses in a batch. * @param _owners The list of addresses to fetch vote power of. * @param _blockNumber The block number at which to fetch. * @return _votePowers A list of vote powers corresponding to _owners. */ function batchVotePowerOfAt( address[] memory _owners, uint256 _blockNumber ) external view override returns(uint256[] memory _votePowers) { _votePowers = _batchVotePowerOfAt(_owners, _blockNumber); // zero results might not have been initialized if (isReplacement) { for (uint256 i = 0; i < _votePowers.length; i++) { if (_votePowers[i] == 0 && !_votePowerInitializedAt(_owners[i], _blockNumber)) { _votePowers[i] = ownerToken.balanceOfAt(_owners[i], _blockNumber); } } } } /** * @notice Get current delegated vote power `_from` delegator delegated `_to` delegatee. * @param _from Address of delegator * @param _to Address of delegatee * @param _balance The delegator's current balance * @return The delegated vote power. */ function votePowerFromTo( address _from, address _to, uint256 _balance ) external view override returns (uint256) { // ASSERT: if the result is nonzero, _from and _to are initialized return _votePowerFromTo(_from, _to, _balance); } /** * @notice Get delegated the vote power `_from` delegator delegated `_to` delegatee at `_blockNumber`. * @param _from Address of delegator * @param _to Address of delegatee * @param _balance The delegator's current balance * @param _blockNumber The block number at which to fetch. * @return The delegated vote power. */ function votePowerFromToAt( address _from, address _to, uint256 _balance, uint _blockNumber ) external view override returns (uint256) { // ASSERT: if the result is nonzero, _from and _to were initialized at _blockNumber return _votePowerFromToAt(_from, _to, _balance, _blockNumber); } /** * @notice Get the delegation mode for '_who'. This mode determines whether vote power is * allocated by percentage or by explicit value. * @param _who The address to get delegation mode. * @return Delegation mode (NOTSET=0, PERCENTAGE=1, AMOUNT=2)) */ function delegationModeOf(address _who) external view override returns (uint256) { return uint256(_delegationModeOf(_who)); } /** * @notice Compute the current undelegated vote power of `_owner` * @param _owner The address to get undelegated voting power. * @param _balance Owner's current balance * @return The unallocated vote power of `_owner` */ function undelegatedVotePowerOf( address _owner, uint256 _balance ) external view override returns (uint256) { if (_votePowerInitialized(_owner)) { return _undelegatedVotePowerOf(_owner, _balance); } else { // ASSERT: there are no delegations return _balance; } } /** * @notice Get the undelegated vote power of `_owner` at given block. * @param _owner The address to get undelegated voting power. * @param _blockNumber The block number at which to fetch. * @return The undelegated vote power of `_owner` (= owner's own balance minus all delegations from owner) */ function undelegatedVotePowerOfAt( address _owner, uint256 _balance, uint256 _blockNumber ) external view override returns (uint256) { if (_votePowerInitialized(_owner)) { return _undelegatedVotePowerOfAt(_owner, _balance, _blockNumber); } else { // ASSERT: there were no delegations at _blockNumber return _balance; } } /** * @notice Get the vote power delegation `_delegateAddresses` * and `pcts` of an `_owner`. Returned in two separate positional arrays. * Also returns the count of delegates and delegation mode. * @param _owner The address to get delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOf(address _owner) external view override returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ) { // ASSERT: either _owner is initialized or there are no delegations return delegatesOfAt(_owner, block.number); } /** * @notice Get the vote power delegation `delegationAddresses` * and `_bips` of an `_owner`. Returned in two separate positional arrays. * Also returns the count of delegates and delegation mode. * @param _owner The address to get delegations. * @param _blockNumber The block for which we want to know the delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOfAt( address _owner, uint256 _blockNumber ) public view override returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ) { // ASSERT: either _owner was initialized or there were no delegations DelegationMode mode = _delegationModeOf(_owner); if (mode == DelegationMode.PERCENTAGE) { // Get the vote power delegation for the _owner (_delegateAddresses, _bips) = _percentageDelegatesOfAt(_owner, _blockNumber); } else if (mode == DelegationMode.NOTSET) { _delegateAddresses = new address[](0); _bips = new uint256[](0); } else { revert ("delegatesOf does not work in AMOUNT delegation mode"); } _count = _delegateAddresses.length; _delegationMode = uint256(mode); } /** * Initialize vote power to current balance if not initialized already. * @param _owner The address to initialize voting power. * @param _balance The owner's current balance. */ function _initializeVotePower(address _owner, uint256 _balance) internal { if (!isReplacement) return; if (_owner == address(0)) return; // 0 address is special (usually marks no source/dest - no init needed) if (votePowerInitializationBlock[_owner] == 0) { // consistency check - no delegations should be made from or to owner before vote power is initialized // (that would be dangerous, because vote power would have been delegated incorrectly) assert(_votePowerOf(_owner) == 0 && !_hasAnyDelegations(_owner)); _mintVotePower(_owner, 0, _balance); votePowerInitializationBlock[_owner] = block.number.add(1); } } /** * Has the vote power of `_owner` been initialized? * @param _owner The address to check. * @return true if vote power of _owner is initialized */ function _votePowerInitialized(address _owner) internal view returns (bool) { if (!isReplacement) return true; return votePowerInitializationBlock[_owner] != 0; } /** * Was vote power of `_owner` initialized at some block? * @param _owner The address to check. * @param _blockNumber The block for which we want to check. * @return true if vote power of _owner was initialized at _blockNumber */ function _votePowerInitializedAt(address _owner, uint256 _blockNumber) internal view returns (bool) { if (!isReplacement) return true; uint256 initblock = votePowerInitializationBlock[_owner]; return initblock != 0 && initblock - 1 <= _blockNumber; } } // File contracts/userInterfaces/IWNat.sol interface IWNat { /** * @notice Deposit native token and mint WNAT ERC20. */ function deposit() external payable; /** * @notice Withdraw native token and burn WNAT ERC20. * @param _amount The amount to withdraw. */ function withdraw(uint256 _amount) external; /** * @notice Deposit native token from msg.sender and mint WNAT ERC20. * @param _recipient An address to receive minted WNAT. */ function depositTo(address _recipient) external payable; /** * @notice Withdraw WNAT from an owner and send NAT to msg.sender given an allowance. * @param _owner An address spending the native tokens. * @param _amount The amount to spend. * * Requirements: * * - `_owner` must have a balance of at least `_amount`. * - the caller must have allowance for `_owners`'s tokens of at least * `_amount`. */ function withdrawFrom(address _owner, uint256 _amount) external; } // File contracts/token/implementation/WNat.sol /** * @title Wrapped Native token * @notice Accept native token deposits and mint ERC20 WNAT (wrapped native) tokens 1-1. * @dev Attribution: https://rinkeby.etherscan.io/address/0xc778417e063141139fce010982780140aa0cd5ab#code */ contract WNat is VPToken, IWNat { using SafeMath for uint256; event Deposit(address indexed dst, uint amount); event Withdrawal(address indexed src, uint amount); /** * Construct an ERC20 token. */ constructor(address _governance, string memory _name, string memory _symbol) VPToken(_governance, _name, _symbol) { } receive() external payable { deposit(); } /** * @notice Withdraw WNAT from an owner and send native tokens to msg.sender given an allowance. * @param owner An address spending the Native tokens. * @param amount The amount to spend. * * Requirements: * * - `owner` must have a balance of at least `amount`. * - the caller must have allowance for `owners`'s tokens of at least * `amount`. */ function withdrawFrom(address owner, uint256 amount) external override { // Reduce senders allowance _approve(owner, msg.sender, allowance(owner, msg.sender).sub(amount, "allowance below zero")); // Burn the owners balance _burn(owner, amount); // Emit withdraw event emit Withdrawal(owner, amount); // Move value to sender (last statement, to prevent reentrancy) msg.sender.transfer(amount); } /** * @notice Deposit Native from msg.sender and mints WNAT ERC20 to recipient address. * @param recipient An address to receive minted WNAT. */ function depositTo(address recipient) external payable override { require(recipient != address(0), "Cannot deposit to zero address"); // Mint WNAT _mint(recipient, msg.value); // Emit deposit event emit Deposit(recipient, msg.value); } /** * @notice Deposit Native and mint wNat ERC20. */ function deposit() public payable override { // Mint WNAT _mint(msg.sender, msg.value); // Emit deposit event emit Deposit(msg.sender, msg.value); } /** * @notice Withdraw Native and burn WNAT ERC20. * @param amount The amount to withdraw. */ function withdraw(uint256 amount) external override { // Burn WNAT tokens _burn(msg.sender, amount); // Emit withdrawal event emit Withdrawal(msg.sender, amount); // Send Native to sender (last statement, to prevent reentrancy) msg.sender.transfer(amount); } } // File contracts/addressUpdater/interface/IIAddressUpdatable.sol interface IIAddressUpdatable { /** * @notice Updates contract addresses - should be called only from AddressUpdater contract * @param _contractNameHashes list of keccak256(abi.encode(...)) contract names * @param _contractAddresses list of contract addresses corresponding to the contract names */ function updateContractAddresses( bytes32[] memory _contractNameHashes, address[] memory _contractAddresses ) external; } // File contracts/addressUpdater/interface/IIAddressUpdater.sol interface IIAddressUpdater { /** * @notice Returns all contract names and corresponding addresses */ function getContractNamesAndAddresses() external view returns( string[] memory _contractNames, address[] memory _contractAddresses ); /** * @notice Returns contract address for the given name - might be address(0) * @param _name name of the contract */ function getContractAddress(string calldata _name) external view returns(address); /** * @notice Returns contract address for the given name hash - might be address(0) * @param _nameHash hash of the contract name (keccak256(abi.encode(name)) */ function getContractAddressByHash(bytes32 _nameHash) external view returns(address); /** * @notice Returns contract addresses for the given names - might be address(0) * @param _names names of the contracts */ function getContractAddresses(string[] calldata _names) external view returns(address[] memory); /** * @notice Returns contract addresses for the given name hashes - might be address(0) * @param _nameHashes hashes of the contract names (keccak256(abi.encode(name)) */ function getContractAddressesByHash(bytes32[] calldata _nameHashes) external view returns(address[] memory); } // File contracts/addressUpdater/implementation/AddressUpdater.sol contract AddressUpdater is IIAddressUpdater, Governed { string internal constant ERR_ARRAY_LENGTHS = "array lengths do not match"; string internal constant ERR_ADDRESS_ZERO = "address zero"; string[] internal contractNames; mapping(bytes32 => address) internal contractAddresses; constructor(address _governance) Governed(_governance) {} /** * @notice set/update contract names/addresses and then apply changes to other contracts * @param _contractNames contracts names * @param _contractAddresses addresses of corresponding contracts names * @param _contractsToUpdate contracts to be updated */ function update( string[] memory _contractNames, address[] memory _contractAddresses, IIAddressUpdatable[] memory _contractsToUpdate ) external onlyGovernance { _addOrUpdateContractNamesAndAddresses(_contractNames, _contractAddresses); _updateContractAddresses(_contractsToUpdate); } /** * @notice Updates contract addresses on all contracts implementing IIAddressUpdatable interface * @param _contractsToUpdate contracts to be updated */ function updateContractAddresses(IIAddressUpdatable[] memory _contractsToUpdate) external onlyImmediateGovernance { _updateContractAddresses(_contractsToUpdate); } /** * @notice Add or update contract names and addreses that are later used in updateContractAddresses calls * @param _contractNames contracts names * @param _contractAddresses addresses of corresponding contracts names */ function addOrUpdateContractNamesAndAddresses( string[] memory _contractNames, address[] memory _contractAddresses ) external onlyGovernance { _addOrUpdateContractNamesAndAddresses(_contractNames, _contractAddresses); } /** * @notice Remove contracts with given names * @param _contractNames contracts names */ function removeContracts(string[] memory _contractNames) external onlyGovernance { for (uint256 i = 0; i < _contractNames.length; i++) { string memory contractName = _contractNames[i]; bytes32 nameHash = _keccak256AbiEncode(contractName); require(contractAddresses[nameHash] != address(0), ERR_ADDRESS_ZERO); delete contractAddresses[nameHash]; uint256 index = contractNames.length; while (index > 0) { index--; if (nameHash == _keccak256AbiEncode(contractNames[index])) { break; } } contractNames[index] = contractNames[contractNames.length - 1]; contractNames.pop(); } } /** * @notice Returns all contract names and corresponding addresses */ function getContractNamesAndAddresses() external view override returns( string[] memory _contractNames, address[] memory _contractAddresses ) { _contractNames = contractNames; uint256 len = _contractNames.length; _contractAddresses = new address[](len); while (len > 0) { len--; _contractAddresses[len] = contractAddresses[_keccak256AbiEncode(_contractNames[len])]; } } /** * @notice Returns contract address for the given name - might be address(0) * @param _name name of the contract */ function getContractAddress(string calldata _name) external view override returns(address) { return contractAddresses[_keccak256AbiEncode(_name)]; } /** * @notice Returns contract address for the given name hash - might be address(0) * @param _nameHash hash of the contract name (keccak256(abi.encode(name)) */ function getContractAddressByHash(bytes32 _nameHash) external view override returns(address) { return contractAddresses[_nameHash]; } /** * @notice Returns contract addresses for the given names - might be address(0) * @param _names names of the contracts */ function getContractAddresses(string[] calldata _names) external view override returns(address[] memory) { address[] memory addresses = new address[](_names.length); for (uint256 i = 0; i < _names.length; i++) { addresses[i] = contractAddresses[_keccak256AbiEncode(_names[i])]; } return addresses; } /** * @notice Returns contract addresses for the given name hashes - might be address(0) * @param _nameHashes hashes of the contract names (keccak256(abi.encode(name)) */ function getContractAddressesByHash( bytes32[] calldata _nameHashes ) external view override returns(address[] memory) { address[] memory addresses = new address[](_nameHashes.length); for (uint256 i = 0; i < _nameHashes.length; i++) { addresses[i] = contractAddresses[_nameHashes[i]]; } return addresses; } /** * @notice Add or update contract names and addreses that are later used in updateContractAddresses calls * @param _contractNames contracts names * @param _contractAddresses addresses of corresponding contracts names */ function _addOrUpdateContractNamesAndAddresses( string[] memory _contractNames, address[] memory _contractAddresses ) internal { uint256 len = _contractNames.length; require(len == _contractAddresses.length, ERR_ARRAY_LENGTHS); for (uint256 i = 0; i < len; i++) { require(_contractAddresses[i] != address(0), ERR_ADDRESS_ZERO); bytes32 nameHash = _keccak256AbiEncode(_contractNames[i]); // add new contract name if address is not known yet if (contractAddresses[nameHash] == address(0)) { contractNames.push(_contractNames[i]); } // set or update contract address contractAddresses[nameHash] = _contractAddresses[i]; } } /** * @notice Updates contract addresses on all contracts implementing IIAddressUpdatable interface * @param _contractsToUpdate contracts to be updated */ function _updateContractAddresses(IIAddressUpdatable[] memory _contractsToUpdate) internal { uint256 len = contractNames.length; bytes32[] memory nameHashes = new bytes32[](len); address[] memory addresses = new address[](len); while (len > 0) { len--; nameHashes[len] = _keccak256AbiEncode(contractNames[len]); addresses[len] = contractAddresses[nameHashes[len]]; } for (uint256 i = 0; i < _contractsToUpdate.length; i++) { _contractsToUpdate[i].updateContractAddresses(nameHashes, addresses); } } /** * @notice Returns hash from string value */ function _keccak256AbiEncode(string memory _value) internal pure returns(bytes32) { return keccak256(abi.encode(_value)); } } // File contracts/genesis/implementation/GovernanceSettings.sol // (c) 2021, Flare Networks Limited. All rights reserved. // Please see the file LICENSE for licensing terms. /** * A special contract that holds Flare governance address. * This contract enables updating governance address and timelock only by hard forking the network, * meaning only by updating validator code. */ contract GovernanceSettings is IGovernanceSettings { address public constant SIGNAL_COINBASE = address(0x00000000000000000000000000000000000dEAD0); uint256 internal constant MAX_TIMELOCK = 365 days; address internal constant GENESIS_GOVERNANCE = 0xfffEc6C83c8BF5c3F4AE0cCF8c45CE20E4560BD7; // governance address set by the validator (set in initialise call, can be changed by fork) address private governanceAddress; // global timelock setting (in seconds), also set by validator (set in initialise call, can be changed by fork) uint64 private timelock; // prevent double initialisation bool private initialised; // executor addresses, changeable anytime by the governance address[] private executors; mapping (address => bool) private executorMap; event GovernanceAddressUpdated( uint256 timestamp, address oldGovernanceAddress, address newGovernanceAddress ); event GovernanceTimelockUpdated( uint256 timestamp, uint256 oldTimelock, uint256 newTimelock ); event GovernanceExecutorsUpdated( uint256 timestamp, address[] oldExecutors, address[] newExecutors ); /** * Perform initialisation, which cannot be done in constructor, since this is a genesis contract. * Can only be called once. */ function initialise(address _governanceAddress, uint256 _timelock, address[] memory _executors) external { require(msg.sender == GENESIS_GOVERNANCE, "only genesis governance"); require(!initialised, "already initialised"); require(_timelock < MAX_TIMELOCK, "timelock too large"); // set the field values initialised = true; governanceAddress = _governanceAddress; timelock = uint64(_timelock); _setExecutors(_executors); } /** * Change the governance address. * Can only be called by validators via fork. */ function setGovernanceAddress(address _newGovernance) external { require(governanceAddress != _newGovernance, "governanceAddress == _newGovernance"); if (msg.sender == block.coinbase && block.coinbase == SIGNAL_COINBASE) { emit GovernanceAddressUpdated(block.timestamp, governanceAddress, _newGovernance); governanceAddress = _newGovernance; } } /** * Change the timelock. * Can only be called by validators via fork. */ function setTimelock(uint256 _newTimelock) external { require(timelock != _newTimelock, "timelock == _newTimelock"); require(_newTimelock < MAX_TIMELOCK, "timelock too large"); if (msg.sender == block.coinbase && block.coinbase == SIGNAL_COINBASE) { emit GovernanceTimelockUpdated(block.timestamp, timelock, _newTimelock); timelock = uint64(_newTimelock); } } /** * Set the addresses of the accounts that are allowed to execute the timelocked governance calls * once the timelock period expires. * It isn't very dangerous to allow for anyone to execute timelocked calls, but we reserve the right to * make sure the timing of the execution is under control. * Can only be called by the governance. */ function setExecutors(address[] memory _newExecutors) external { require(msg.sender == governanceAddress, "only governance"); _setExecutors(_newExecutors); } /** * Get the governance account address. */ function getGovernanceAddress() external view override returns (address) { return governanceAddress; } /** * Get the time that must pass between a governance call and execution. */ function getTimelock() external view override returns (uint256) { return timelock; } /** * Get the addresses of the accounts that are allowed to execute the timelocked governance calls * once the timelock period expires. */ function getExecutors() external view override returns (address[] memory) { return executors; } /** * Check whether an address is allowed to execute an governance call after timelock expires. */ function isExecutor(address _address) external view override returns (bool) { return executorMap[_address]; } function _setExecutors(address[] memory _newExecutors) private { emit GovernanceExecutorsUpdated(block.timestamp, executors, _newExecutors); // clear old while (executors.length > 0) { executorMap[executors[executors.length - 1]] = false; executors.pop(); } // set new for (uint256 i = 0; i < _newExecutors.length; i++) { executors.push(_newExecutors[i]); executorMap[_newExecutors[i]] = true; } } } // File contracts/genesis/interface/IFtsoGenesis.sol interface IFtsoGenesis { /** * @notice Reveals submitted price during epoch reveal period - only price submitter * @param _voter Voter address * @param _epochId Id of the epoch in which the price hash was submitted * @param _price Submitted price in USD * @notice The hash of _price and _random must be equal to the submitted hash * @notice Emits PriceRevealed event */ function revealPriceSubmitter( address _voter, uint256 _epochId, uint256 _price, uint256 _wNatVP ) external; /** * @notice Get (and cache) wNat vote power for specified voter and given epoch id * @param _voter Voter address * @param _epochId Id of the epoch in which the price hash was submitted * @return wNat vote power */ function wNatVotePowerCached(address _voter, uint256 _epochId) external returns (uint256); } // File contracts/userInterfaces/IFtso.sol interface IFtso { enum PriceFinalizationType { // initial state NOT_FINALIZED, // median calculation used to find price WEIGHTED_MEDIAN, // low turnout - price calculated from median of trusted addresses TRUSTED_ADDRESSES, // low turnout + no votes from trusted addresses - price copied from previous epoch PREVIOUS_PRICE_COPIED, // price calculated from median of trusted addresses - triggered due to an exception TRUSTED_ADDRESSES_EXCEPTION, // previous price copied - triggered due to an exception PREVIOUS_PRICE_COPIED_EXCEPTION } event PriceRevealed( address indexed voter, uint256 indexed epochId, uint256 price, uint256 timestamp, uint256 votePowerNat, uint256 votePowerAsset ); event PriceFinalized( uint256 indexed epochId, uint256 price, bool rewardedFtso, uint256 lowRewardPrice, uint256 highRewardPrice, PriceFinalizationType finalizationType, uint256 timestamp ); event PriceEpochInitializedOnFtso( uint256 indexed epochId, uint256 endTime, uint256 timestamp ); event LowTurnout( uint256 indexed epochId, uint256 natTurnout, uint256 lowNatTurnoutThresholdBIPS, uint256 timestamp ); /** * @notice Returns if FTSO is active */ function active() external view returns (bool); /** * @notice Returns the FTSO symbol */ function symbol() external view returns (string memory); /** * @notice Returns current epoch id */ function getCurrentEpochId() external view returns (uint256); /** * @notice Returns id of the epoch which was opened for price submission at the specified timestamp * @param _timestamp Timestamp as seconds from unix epoch */ function getEpochId(uint256 _timestamp) external view returns (uint256); /** * @notice Returns random number of the specified epoch * @param _epochId Id of the epoch */ function getRandom(uint256 _epochId) external view returns (uint256); /** * @notice Returns asset price consented in specific epoch * @param _epochId Id of the epoch * @return Price in USD multiplied by ASSET_PRICE_USD_DECIMALS */ function getEpochPrice(uint256 _epochId) external view returns (uint256); /** * @notice Returns current epoch data * @return _epochId Current epoch id * @return _epochSubmitEndTime End time of the current epoch price submission as seconds from unix epoch * @return _epochRevealEndTime End time of the current epoch price reveal as seconds from unix epoch * @return _votePowerBlock Vote power block for the current epoch * @return _fallbackMode Current epoch in fallback mode - only votes from trusted addresses will be used * @dev half-closed intervals - end time not included */ function getPriceEpochData() external view returns ( uint256 _epochId, uint256 _epochSubmitEndTime, uint256 _epochRevealEndTime, uint256 _votePowerBlock, bool _fallbackMode ); /** * @notice Returns current epoch data * @return _firstEpochStartTs First epoch start timestamp * @return _submitPeriodSeconds Submit period in seconds * @return _revealPeriodSeconds Reveal period in seconds */ function getPriceEpochConfiguration() external view returns ( uint256 _firstEpochStartTs, uint256 _submitPeriodSeconds, uint256 _revealPeriodSeconds ); /** * @notice Returns asset price submitted by voter in specific epoch * @param _epochId Id of the epoch * @param _voter Address of the voter * @return Price in USD multiplied by ASSET_PRICE_USD_DECIMALS */ function getEpochPriceForVoter(uint256 _epochId, address _voter) external view returns (uint256); /** * @notice Returns current asset price * @return _price Price in USD multiplied by ASSET_PRICE_USD_DECIMALS * @return _timestamp Time when price was updated for the last time */ function getCurrentPrice() external view returns (uint256 _price, uint256 _timestamp); /** * @notice Returns current asset price and number of decimals * @return _price Price in USD multiplied by ASSET_PRICE_USD_DECIMALS * @return _timestamp Time when price was updated for the last time * @return _assetPriceUsdDecimals Number of decimals used for USD price */ function getCurrentPriceWithDecimals() external view returns ( uint256 _price, uint256 _timestamp, uint256 _assetPriceUsdDecimals ); /** * @notice Returns current asset price calculated from trusted providers * @return _price Price in USD multiplied by ASSET_PRICE_USD_DECIMALS * @return _timestamp Time when price was updated for the last time */ function getCurrentPriceFromTrustedProviders() external view returns (uint256 _price, uint256 _timestamp); /** * @notice Returns current asset price calculated from trusted providers and number of decimals * @return _price Price in USD multiplied by ASSET_PRICE_USD_DECIMALS * @return _timestamp Time when price was updated for the last time * @return _assetPriceUsdDecimals Number of decimals used for USD price */ function getCurrentPriceWithDecimalsFromTrustedProviders() external view returns ( uint256 _price, uint256 _timestamp, uint256 _assetPriceUsdDecimals ); /** * @notice Returns current asset price details * @return _price Price in USD multiplied by ASSET_PRICE_USD_DECIMALS * @return _priceTimestamp Time when price was updated for the last time * @return _priceFinalizationType Finalization type when price was updated for the last time * @return _lastPriceEpochFinalizationTimestamp Time when last price epoch was finalized * @return _lastPriceEpochFinalizationType Finalization type of last finalized price epoch */ function getCurrentPriceDetails() external view returns ( uint256 _price, uint256 _priceTimestamp, PriceFinalizationType _priceFinalizationType, uint256 _lastPriceEpochFinalizationTimestamp, PriceFinalizationType _lastPriceEpochFinalizationType ); /** * @notice Returns current random number */ function getCurrentRandom() external view returns (uint256); } // File contracts/ftso/interface/IIFtso.sol interface IIFtso is IFtso, IFtsoGenesis { /// function finalizePriceReveal /// called by reward manager only on correct timing. /// if price reveal period for epoch x ended. finalize. /// iterate list of price submissions /// find weighted median /// find adjucant 50% of price submissions. /// Allocate reward for any price submission which is same as a "winning" submission function finalizePriceEpoch(uint256 _epochId, bool _returnRewardData) external returns( address[] memory _eligibleAddresses, uint256[] memory _natWeights, uint256 _totalNatWeight ); function fallbackFinalizePriceEpoch(uint256 _epochId) external; function forceFinalizePriceEpoch(uint256 _epochId) external; // activateFtso will be called by ftso manager once ftso is added // before this is done, FTSO can't run function activateFtso( uint256 _firstEpochStartTs, uint256 _submitPeriodSeconds, uint256 _revealPeriodSeconds ) external; function deactivateFtso() external; // update initial price and timestamp - only if not active function updateInitialPrice(uint256 _initialPriceUSD, uint256 _initialPriceTimestamp) external; function configureEpochs( uint256 _maxVotePowerNatThresholdFraction, uint256 _maxVotePowerAssetThresholdFraction, uint256 _lowAssetUSDThreshold, uint256 _highAssetUSDThreshold, uint256 _highAssetTurnoutThresholdBIPS, uint256 _lowNatTurnoutThresholdBIPS, address[] memory _trustedAddresses ) external; function setAsset(IIVPToken _asset) external; function setAssetFtsos(IIFtso[] memory _assetFtsos) external; // current vote power block will update per reward epoch. // the FTSO doesn't have notion of reward epochs. // reward manager only can set this data. function setVotePowerBlock(uint256 _blockNumber) external; function initializeCurrentEpochStateForReveal(uint256 _circulatingSupplyNat, bool _fallbackMode) external; /** * @notice Returns ftso manager address */ function ftsoManager() external view returns (address); /** * @notice Returns the FTSO asset * @dev Asset is null in case of multi-asset FTSO */ function getAsset() external view returns (IIVPToken); /** * @notice Returns the Asset FTSOs * @dev AssetFtsos is not null only in case of multi-asset FTSO */ function getAssetFtsos() external view returns (IIFtso[] memory); /** * @notice Returns current configuration of epoch state * @return _maxVotePowerNatThresholdFraction High threshold for native token vote power per voter * @return _maxVotePowerAssetThresholdFraction High threshold for asset vote power per voter * @return _lowAssetUSDThreshold Threshold for low asset vote power * @return _highAssetUSDThreshold Threshold for high asset vote power * @return _highAssetTurnoutThresholdBIPS Threshold for high asset turnout * @return _lowNatTurnoutThresholdBIPS Threshold for low nat turnout * @return _trustedAddresses Trusted addresses - use their prices if low nat turnout is not achieved */ function epochsConfiguration() external view returns ( uint256 _maxVotePowerNatThresholdFraction, uint256 _maxVotePowerAssetThresholdFraction, uint256 _lowAssetUSDThreshold, uint256 _highAssetUSDThreshold, uint256 _highAssetTurnoutThresholdBIPS, uint256 _lowNatTurnoutThresholdBIPS, address[] memory _trustedAddresses ); /** * @notice Returns parameters necessary for approximately replicating vote weighting. * @return _assets the list of Assets that are accounted in vote * @return _assetMultipliers weight of each asset in (multiasset) ftso, mutiplied by TERA * @return _totalVotePowerNat total native token vote power at block * @return _totalVotePowerAsset total combined asset vote power at block * @return _assetWeightRatio ratio of combined asset vp vs. native token vp (in BIPS) * @return _votePowerBlock vote powewr block for given epoch */ function getVoteWeightingParameters() external view returns ( IIVPToken[] memory _assets, uint256[] memory _assetMultipliers, uint256 _totalVotePowerNat, uint256 _totalVotePowerAsset, uint256 _assetWeightRatio, uint256 _votePowerBlock ); function wNat() external view returns (IIVPToken); } // File contracts/genesis/interface/IFtsoRegistryGenesis.sol interface IFtsoRegistryGenesis { function getFtsos(uint256[] memory _indices) external view returns(IFtsoGenesis[] memory _ftsos); } // File contracts/userInterfaces/IFtsoRegistry.sol interface IFtsoRegistry is IFtsoRegistryGenesis { struct PriceInfo { uint256 ftsoIndex; uint256 price; uint256 decimals; uint256 timestamp; } function getFtso(uint256 _ftsoIndex) external view returns(IIFtso _activeFtsoAddress); function getFtsoBySymbol(string memory _symbol) external view returns(IIFtso _activeFtsoAddress); function getSupportedIndices() external view returns(uint256[] memory _supportedIndices); function getSupportedSymbols() external view returns(string[] memory _supportedSymbols); function getSupportedFtsos() external view returns(IIFtso[] memory _ftsos); function getFtsoIndex(string memory _symbol) external view returns (uint256 _assetIndex); function getFtsoSymbol(uint256 _ftsoIndex) external view returns (string memory _symbol); function getCurrentPrice(uint256 _ftsoIndex) external view returns(uint256 _price, uint256 _timestamp); function getCurrentPrice(string memory _symbol) external view returns(uint256 _price, uint256 _timestamp); function getCurrentPriceWithDecimals(uint256 _assetIndex) external view returns(uint256 _price, uint256 _timestamp, uint256 _assetPriceUsdDecimals); function getCurrentPriceWithDecimals(string memory _symbol) external view returns(uint256 _price, uint256 _timestamp, uint256 _assetPriceUsdDecimals); function getAllCurrentPrices() external view returns (PriceInfo[] memory); function getCurrentPricesByIndices(uint256[] memory _indices) external view returns (PriceInfo[] memory); function getCurrentPricesBySymbols(string[] memory _symbols) external view returns (PriceInfo[] memory); function getSupportedIndicesAndFtsos() external view returns(uint256[] memory _supportedIndices, IIFtso[] memory _ftsos); function getSupportedSymbolsAndFtsos() external view returns(string[] memory _supportedSymbols, IIFtso[] memory _ftsos); function getSupportedIndicesAndSymbols() external view returns(uint256[] memory _supportedIndices, string[] memory _supportedSymbols); function getSupportedIndicesSymbolsAndFtsos() external view returns(uint256[] memory _supportedIndices, string[] memory _supportedSymbols, IIFtso[] memory _ftsos); } // File contracts/utils/interface/IIFtsoRegistry.sol interface IIFtsoRegistry is IFtsoRegistry { // returns ftso index function addFtso(IIFtso _ftsoContract) external returns(uint256); function removeFtso(IIFtso _ftso) external; } // File contracts/genesis/interface/IFtsoManagerGenesis.sol interface IFtsoManagerGenesis { function getCurrentPriceEpochId() external view returns (uint256 _priceEpochId); } // File contracts/userInterfaces/IFtsoManager.sol interface IFtsoManager is IFtsoManagerGenesis { event FtsoAdded(IIFtso ftso, bool add); event FallbackMode(bool fallbackMode); event FtsoFallbackMode(IIFtso ftso, bool fallbackMode); event RewardEpochFinalized(uint256 votepowerBlock, uint256 startBlock); event PriceEpochFinalized(address chosenFtso, uint256 rewardEpochId); event InitializingCurrentEpochStateForRevealFailed(IIFtso ftso, uint256 epochId); event FinalizingPriceEpochFailed(IIFtso ftso, uint256 epochId, IFtso.PriceFinalizationType failingType); event DistributingRewardsFailed(address ftso, uint256 epochId); event AccruingUnearnedRewardsFailed(uint256 epochId); function active() external view returns (bool); function getCurrentRewardEpoch() external view returns (uint256); function getRewardEpochVotePowerBlock(uint256 _rewardEpoch) external view returns (uint256); function getRewardEpochToExpireNext() external view returns (uint256); function getCurrentPriceEpochData() external view returns ( uint256 _priceEpochId, uint256 _priceEpochStartTimestamp, uint256 _priceEpochEndTimestamp, uint256 _priceEpochRevealEndTimestamp, uint256 _currentTimestamp ); function getFtsos() external view returns (IIFtso[] memory _ftsos); function getPriceEpochConfiguration() external view returns ( uint256 _firstPriceEpochStartTs, uint256 _priceEpochDurationSeconds, uint256 _revealEpochDurationSeconds ); function getRewardEpochConfiguration() external view returns ( uint256 _firstRewardEpochStartTs, uint256 _rewardEpochDurationSeconds ); function getFallbackMode() external view returns ( bool _fallbackMode, IIFtso[] memory _ftsos, bool[] memory _ftsoInFallbackMode ); } // File contracts/genesis/interface/IFlareDaemonize.sol /// Any contracts that want to recieve a trigger from Flare daemon should /// implement IFlareDaemonize interface IFlareDaemonize { /// Implement this function for recieving a trigger from FlareDaemon. function daemonize() external returns (bool); /// This function will be called after an error is caught in daemonize(). /// It will switch the contract to a simpler fallback mode, which hopefully works when full mode doesn't. /// Not every contract needs to support fallback mode (FtsoManager does), so this method may be empty. /// Switching back to normal mode is left to the contract (typically a governed method call). /// This function may be called due to low-gas error, so it shouldn't use more than ~30.000 gas. /// @return true if switched to fallback mode, false if already in fallback mode or if falback not supported function switchToFallbackMode() external returns (bool); /// Implement this function for updating daemonized contracts through AddressUpdater. function getContractName() external view returns (string memory); } // File contracts/ftso/interface/IIFtsoManager.sol interface IIFtsoManager is IFtsoManager, IFlareDaemonize { struct RewardEpochData { uint256 votepowerBlock; uint256 startBlock; uint256 startTimestamp; } event ClosingExpiredRewardEpochFailed(uint256 rewardEpoch); event CleanupBlockNumberManagerFailedForBlock(uint256 blockNumber); event UpdatingActiveValidatorsTriggerFailed(uint256 rewardEpoch); event FtsoDeactivationFailed(IIFtso ftso); function activate() external; function setInitialRewardData( uint256 _nextRewardEpochToExpire, uint256 _rewardEpochsLength, uint256 _currentRewardEpochEnds ) external; function setGovernanceParameters( uint256 _maxVotePowerNatThresholdFraction, uint256 _maxVotePowerAssetThresholdFraction, uint256 _lowAssetUSDThreshold, uint256 _highAssetUSDThreshold, uint256 _highAssetTurnoutThresholdBIPS, uint256 _lowNatTurnoutThresholdBIPS, uint256 _rewardExpiryOffsetSeconds, address[] memory _trustedAddresses ) external; function addFtso(IIFtso _ftso) external; function addFtsosBulk(IIFtso[] memory _ftsos) external; function removeFtso(IIFtso _ftso) external; function replaceFtso( IIFtso _ftsoToAdd, bool copyCurrentPrice, bool copyAssetOrAssetFtsos ) external; function replaceFtsosBulk( IIFtso[] memory _ftsosToAdd, bool copyCurrentPrice, bool copyAssetOrAssetFtsos ) external; function setFtsoAsset(IIFtso _ftso, IIVPToken _asset) external; function setFtsoAssetFtsos(IIFtso _ftso, IIFtso[] memory _assetFtsos) external; function setFallbackMode(bool _fallbackMode) external; function setFtsoFallbackMode(IIFtso _ftso, bool _fallbackMode) external; function notInitializedFtsos(IIFtso) external view returns (bool); function getRewardEpochData(uint256 _rewardEpochId) external view returns (RewardEpochData memory); function currentRewardEpochEnds() external view returns (uint256); function getLastUnprocessedPriceEpochData() external view returns( uint256 _lastUnprocessedPriceEpoch, uint256 _lastUnprocessedPriceEpochRevealEnds, bool _lastUnprocessedPriceEpochInitialized ); function rewardEpochsStartTs() external view returns(uint256); function rewardEpochDurationSeconds() external view returns(uint256); function rewardEpochs(uint256 _rewardEpochId) external view returns ( uint256 _votepowerBlock, uint256 _startBlock, uint256 _startTimestamp ); function getRewardExpiryOffsetSeconds() external view returns (uint256); }
Compiler Settings
{"outputSelection":{"*":{"*":["*"],"":["*"]}},"optimizer":{"runs":200,"enabled":true},"libraries":{}}
Contract ABI
[{"type":"constructor","stateMutability":"nonpayable","inputs":[{"type":"address","name":"_governance","internalType":"address"},{"type":"string","name":"_name","internalType":"string"},{"type":"string","name":"_symbol","internalType":"string"},{"type":"string","name":"_assetName","internalType":"string"},{"type":"string","name":"_assetSymbol","internalType":"string"},{"type":"uint8","name":"_decimals","internalType":"uint8"}]},{"type":"event","name":"Approval","inputs":[{"type":"address","name":"owner","internalType":"address","indexed":true},{"type":"address","name":"spender","internalType":"address","indexed":true},{"type":"uint256","name":"value","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"CreatedTotalSupplyCache","inputs":[{"type":"uint256","name":"_blockNumber","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"GovernanceCallTimelocked","inputs":[{"type":"bytes4","name":"selector","internalType":"bytes4","indexed":false},{"type":"uint256","name":"allowedAfterTimestamp","internalType":"uint256","indexed":false},{"type":"bytes","name":"encodedCall","internalType":"bytes","indexed":false}],"anonymous":false},{"type":"event","name":"GovernanceInitialised","inputs":[{"type":"address","name":"initialGovernance","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"GovernedProductionModeEntered","inputs":[{"type":"address","name":"governanceSettings","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"TimelockedGovernanceCallCanceled","inputs":[{"type":"bytes4","name":"selector","internalType":"bytes4","indexed":false},{"type":"uint256","name":"timestamp","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"TimelockedGovernanceCallExecuted","inputs":[{"type":"bytes4","name":"selector","internalType":"bytes4","indexed":false},{"type":"uint256","name":"timestamp","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Transfer","inputs":[{"type":"address","name":"from","internalType":"address","indexed":true},{"type":"address","name":"to","internalType":"address","indexed":true},{"type":"uint256","name":"value","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"VotePowerContractChanged","inputs":[{"type":"uint256","name":"_contractType","internalType":"uint256","indexed":false},{"type":"address","name":"_oldContractAddress","internalType":"address","indexed":false},{"type":"address","name":"_newContractAddress","internalType":"address","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"allowance","inputs":[{"type":"address","name":"owner","internalType":"address"},{"type":"address","name":"spender","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"approve","inputs":[{"type":"address","name":"spender","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"assetManager","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"assetName","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"assetSymbol","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"balanceHistoryCleanup","inputs":[{"type":"address","name":"_owner","internalType":"address"},{"type":"uint256","name":"_count","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"balanceOf","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"balanceOfAt","inputs":[{"type":"address","name":"_owner","internalType":"address"},{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"batchDelegate","inputs":[{"type":"address[]","name":"_delegatees","internalType":"address[]"},{"type":"uint256[]","name":"_bips","internalType":"uint256[]"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256[]","name":"","internalType":"uint256[]"}],"name":"batchVotePowerOfAt","inputs":[{"type":"address[]","name":"_owners","internalType":"address[]"},{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"burn","inputs":[{"type":"address","name":"_owner","internalType":"address"},{"type":"uint256","name":"_amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"cancelGovernanceCall","inputs":[{"type":"bytes4","name":"_selector","internalType":"bytes4"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"cleanerContract","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"cleanupBlockNumber","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"cleanupBlockNumberManager","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint8","name":"","internalType":"uint8"}],"name":"decimals","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"decreaseAllowance","inputs":[{"type":"address","name":"spender","internalType":"address"},{"type":"uint256","name":"subtractedValue","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"delegate","inputs":[{"type":"address","name":"_to","internalType":"address"},{"type":"uint256","name":"_bips","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"delegateExplicit","inputs":[{"type":"address","name":"_to","internalType":"address"},{"type":"uint256","name":"_amount","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address[]","name":"_delegateAddresses","internalType":"address[]"},{"type":"uint256[]","name":"_bips","internalType":"uint256[]"},{"type":"uint256","name":"_count","internalType":"uint256"},{"type":"uint256","name":"_delegationMode","internalType":"uint256"}],"name":"delegatesOf","inputs":[{"type":"address","name":"_owner","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address[]","name":"_delegateAddresses","internalType":"address[]"},{"type":"uint256[]","name":"_bips","internalType":"uint256[]"},{"type":"uint256","name":"_count","internalType":"uint256"},{"type":"uint256","name":"_delegationMode","internalType":"uint256"}],"name":"delegatesOfAt","inputs":[{"type":"address","name":"_owner","internalType":"address"},{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"delegationModeOf","inputs":[{"type":"address","name":"_who","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"executeGovernanceCall","inputs":[{"type":"bytes4","name":"_selector","internalType":"bytes4"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"governance","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IGovernanceSettings"}],"name":"governanceSettings","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IGovernanceVotePower"}],"name":"governanceVotePower","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"increaseAllowance","inputs":[{"type":"address","name":"spender","internalType":"address"},{"type":"uint256","name":"addedValue","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initialise","inputs":[{"type":"address","name":"_initialGovernance","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"mint","inputs":[{"type":"address","name":"_owner","internalType":"address"},{"type":"uint256","name":"_amount","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"name","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"productionMode","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IVPContractEvents"}],"name":"readVotePowerContract","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"revokeDelegationAt","inputs":[{"type":"address","name":"_who","internalType":"address"},{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setAssetManager","inputs":[{"type":"address","name":"_assetManager","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setCleanerContract","inputs":[{"type":"address","name":"_cleanerContract","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setCleanupBlockNumber","inputs":[{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setCleanupBlockNumberManager","inputs":[{"type":"address","name":"_cleanupBlockNumberManager","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setGovernanceVotePower","inputs":[{"type":"address","name":"_governanceVotePower","internalType":"contract IIGovernanceVotePower"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setReadVpContract","inputs":[{"type":"address","name":"_vpContract","internalType":"contract IIVPContract"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setWriteVpContract","inputs":[{"type":"address","name":"_vpContract","internalType":"contract IIVPContract"}]},{"type":"function","stateMutability":"pure","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"supportsInterface","inputs":[{"type":"bytes4","name":"_interfaceId","internalType":"bytes4"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"switchToProductionMode","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"symbol","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"terminate","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"terminated","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint64","name":"","internalType":"uint64"}],"name":"terminatedAt","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"allowedAfterTimestamp","internalType":"uint256"},{"type":"bytes","name":"encodedCall","internalType":"bytes"}],"name":"timelockedCalls","inputs":[{"type":"bytes4","name":"","internalType":"bytes4"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalSupply","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalSupplyAt","inputs":[{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalSupplyCacheCleanup","inputs":[{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalSupplyHistoryCleanup","inputs":[{"type":"uint256","name":"_count","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalVotePower","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalVotePowerAt","inputs":[{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalVotePowerAtCached","inputs":[{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"transfer","inputs":[{"type":"address","name":"recipient","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"transferFrom","inputs":[{"type":"address","name":"sender","internalType":"address"},{"type":"address","name":"recipient","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"undelegateAll","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"_remainingDelegation","internalType":"uint256"}],"name":"undelegateAllExplicit","inputs":[{"type":"address[]","name":"_delegateAddresses","internalType":"address[]"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"undelegatedVotePowerOf","inputs":[{"type":"address","name":"_owner","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"undelegatedVotePowerOfAt","inputs":[{"type":"address","name":"_owner","internalType":"address"},{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"votePowerFromTo","inputs":[{"type":"address","name":"_from","internalType":"address"},{"type":"address","name":"_to","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"votePowerFromToAt","inputs":[{"type":"address","name":"_from","internalType":"address"},{"type":"address","name":"_to","internalType":"address"},{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"votePowerOf","inputs":[{"type":"address","name":"_owner","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"votePowerOfAt","inputs":[{"type":"address","name":"_owner","internalType":"address"},{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"votePowerOfAtCached","inputs":[{"type":"address","name":"_owner","internalType":"address"},{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"votePowerOfAtIgnoringRevocation","inputs":[{"type":"address","name":"_owner","internalType":"address"},{"type":"uint256","name":"_blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"vpContractInitialized","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IVPContractEvents"}],"name":"writeVotePowerContract","inputs":[]}]
Contract Creation Code
0x60806040526011805460ff60a01b1916905560128054600160a01b600160e01b03191690553480156200003157600080fd5b506040516200561738038062005617833981810160405260c08110156200005757600080fd5b8151602083018051604051929492938301929190846401000000008211156200007f57600080fd5b9083019060208201858111156200009557600080fd5b8251640100000000811182820188101715620000b057600080fd5b82525081516020918201929091019080838360005b83811015620000df578181015183820152602001620000c5565b50505050905090810190601f1680156200010d5780820380516001836020036101000a031916815260200191505b50604052602001805160405193929190846401000000008211156200013157600080fd5b9083019060208201858111156200014757600080fd5b82516401000000008111828201881017156200016257600080fd5b82525081516020918201929091019080838360005b838110156200019157818101518382015260200162000177565b50505050905090810190601f168015620001bf5780820380516001836020036101000a031916815260200191505b5060405260200180516040519392919084640100000000821115620001e357600080fd5b908301906020820185811115620001f957600080fd5b82516401000000008111828201881017156200021457600080fd5b82525081516020918201929091019080838360005b838110156200024357818101518382015260200162000229565b50505050905090810190601f168015620002715780820380516001836020036101000a031916815260200191505b50604052602001805160405193929190846401000000008211156200029557600080fd5b908301906020820185811115620002ab57600080fd5b8251640100000000811182820188101715620002c657600080fd5b82525081516020918201929091019080838360005b83811015620002f5578181015183820152602001620002db565b50505050905090810190601f168015620003235780820380516001836020036101000a031916815260200191505b506040526020908101518751909350889250879187918491829185918591620003539160039190850190620004be565b50805162000369906004906020840190620004be565b50506005805460ff19166012179055506001600160a01b038116156200039457620003948162000414565b506001600160a01b038116620003c75760405162461bcd60e51b8152600401620003be906200057e565b60405180910390fd5b50505050620003dc81620004a860201b60201c565b8251620003f1906013906020860190620004be565b50815162000407906014906020850190620004be565b50505050505050620005df565b600c54600160a01b900460ff1615620004415760405162461bcd60e51b8152600401620003be90620005a8565b600c8054600160a01b60ff60a01b19909116176001600160a01b0319166001600160a01b0383161790556040517f9789733827840833afc031fb2ef9ab6894271f77bad2085687cf4ae5c7bee4db906200049d9083906200056a565b60405180910390a150565b6005805460ff191660ff92909216919091179055565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282620004f6576000855562000541565b82601f106200051157805160ff191683800117855562000541565b8280016001018555821562000541579182015b828111156200054157825182559160200191906001019062000524565b506200054f92915062000553565b5090565b5b808211156200054f576000815560010162000554565b6001600160a01b0391909116815260200190565b60208082526010908201526f5f676f7665726e616e6365207a65726f60801b604082015260600190565b60208082526014908201527f696e697469616c6973656420213d2066616c7365000000000000000000000000604082015260600190565b61502880620005ef6000396000f3fe608060405234801561001057600080fd5b50600436106103fc5760003560e01c80638c2b8ae111610215578063c9230c5d11610125578063e587497e116100b8578063f5a9838311610087578063f5a9838314610fa2578063f5f3d4f714610faa578063f62f8f3a14610fb2578063f683776714610fcf578063f6a494af14610ff5576103fc565b8063e587497e14610ee8578063e64767aa14610f14578063ed475a7914610f4a578063f0e292c914610f76576103fc565b8063dc4fcda7116100f4578063dc4fcda714610d87578063dd62ed3e14610eaa578063deea13e714610ed8578063e17f212e14610ee0576103fc565b8063c9230c5d14610d10578063caeb942b14610d18578063d06dc3ad14610d35578063d6aa0b7714610d61576103fc565b80639d6a890f116101a8578063a9059cbb11610177578063a9059cbb14610c7a578063b302f39314610ca6578063bbd6fbf814610cae578063be0ca74714610cda578063c787a8fc14610d08576103fc565b80639d6a890f14610bd85780639dc29fac14610bfe5780639e3bc20814610c2a578063a457c2d714610c4e576103fc565b8063981b24d0116101e4578063981b24d014610b855780639b3baa0e14610ba25780639ca20e4e14610baa5780639ca2231a14610bb2576103fc565b80638c2b8ae114610b4157806392bfe6d814610b4957806394217ad114610b7557806395d89b4114610b7d576103fc565b806340c10f19116103105780635ff27079116102a357806374e6310e1161027257806374e6310e14610956578063755d10a4146109fc5780637de5b8ed14610a225780637f4fcaa914610aef57806383035a8214610b15576103fc565b80635ff27079146108da57806362354e031461090157806367fc40291461090957806370a0823114610930576103fc565b80634eac870f116102df5780634eac870f146107fd5780634ee2cd7e146108055780635aa6e675146108315780635d6d11eb14610839576103fc565b806340c10f191461069b57806343060237146106c757806343ea370b146106ed57806349e3c7e51461070a576103fc565b8063176de7a81161039357806323b872dd1161036257806323b872dd146105d8578063313ce5671461060e57806331d12a161461062c57806339509351146106525780633e5aa26a1461067e576103fc565b8063176de7a81461059c57806318160ddd146105a4578063194307bf146105ac5780631fec092a146105b4576103fc565b8063095ea7b3116103cf578063095ea7b3146105255780630c08bf881461055157806313de97f514610559578063142d101814610576576103fc565b806301ffc9a714610401578063026e402b1461043c57806304bb4e431461046a57806306fdde03146104a8575b600080fd5b6104286004803603602081101561041757600080fd5b50356001600160e01b03191661101b565b604080519115158252519081900360200190f35b6104686004803603604081101561045257600080fd5b506001600160a01b0381351690602001356110c0565b005b6104966004803603604081101561048057600080fd5b506001600160a01b038135169060200135611137565b60408051918252519081900360200190f35b6104b06111c7565b6040805160208082528351818301528351919283929083019185019080838360005b838110156104ea5781810151838201526020016104d2565b50505050905090810190601f1680156105175780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6104286004803603604081101561053b57600080fd5b506001600160a01b0381351690602001356111d6565b6104686111f3565b6104686004803603602081101561056f57600080fd5b5035611286565b6104966004803603602081101561058c57600080fd5b50356001600160a01b0316611440565b6104b06114c5565b610496611553565b610428611559565b6105bc611571565b604080516001600160a01b039092168252519081900360200190f35b610428600480360360608110156105ee57600080fd5b506001600160a01b03813581169160208101359091169060400135611580565b610616611608565b6040805160ff9092168252519081900360200190f35b6104686004803603602081101561064257600080fd5b50356001600160a01b0316611612565b6104286004803603604081101561066857600080fd5b506001600160a01b0381351690602001356117ca565b6104966004803603602081101561069457600080fd5b5035611818565b610468600480360360408110156106b157600080fd5b506001600160a01b038135169060200135611823565b610468600480360360208110156106dd57600080fd5b50356001600160a01b0316611885565b6104966004803603602081101561070357600080fd5b5035611982565b6107ad6004803603604081101561072057600080fd5b810190602081018135600160201b81111561073a57600080fd5b82018360208201111561074c57600080fd5b803590602001918460208302840111600160201b8311171561076d57600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955050913592506119db915050565b60408051602080825283518183015283519192839290830191858101910280838360005b838110156107e95781810151838201526020016107d1565b505050509050019250505060405180910390f35b6105bc611a66565b6104966004803603604081101561081b57600080fd5b506001600160a01b038135169060200135611a75565b6105bc611a81565b6104966004803603602081101561084f57600080fd5b810190602081018135600160201b81111561086957600080fd5b82018360208201111561087b57600080fd5b803590602001918460208302840111600160201b8311171561089c57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550611b1e945050505050565b610468600480360360208110156108f057600080fd5b50356001600160e01b031916611b83565b6105bc611e02565b6104686004803603602081101561091f57600080fd5b50356001600160e01b031916611e0d565b6104966004803603602081101561094657600080fd5b50356001600160a01b0316611eb3565b61097d6004803603602081101561096c57600080fd5b50356001600160e01b031916611ece565b6040518083815260200180602001828103825283818151815260200191508051906020019080838360005b838110156109c05781810151838201526020016109a8565b50505050905090810190601f1680156109ed5780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b61046860048036036020811015610a1257600080fd5b50356001600160a01b0316611f75565b610a4860048036036020811015610a3857600080fd5b50356001600160a01b03166121d6565b604051808060200180602001858152602001848152602001838103835287818151815260200191508051906020019060200280838360005b83811015610a98578181015183820152602001610a80565b50505050905001838103825286818151815260200191508051906020019060200280838360005b83811015610ad7578181015183820152602001610abf565b50505050905001965050505050505060405180910390f35b61046860048036036020811015610b0557600080fd5b50356001600160a01b0316612272565b61049660048036036040811015610b2b57600080fd5b506001600160a01b0381351690602001356122c1565b6105bc612303565b61049660048036036040811015610b5f57600080fd5b506001600160a01b038135169060200135612312565b6105bc612349565b6104b0612358565b61049660048036036020811015610b9b57600080fd5b5035612362565b6105bc61236d565b6105bc61237c565b61046860048036036020811015610bc857600080fd5b50356001600160a01b031661238b565b61046860048036036020811015610bee57600080fd5b50356001600160a01b03166124c3565b61046860048036036040811015610c1457600080fd5b506001600160a01b038135169060200135612552565b610c326125b0565b604080516001600160401b039092168252519081900360200190f35b61042860048036036040811015610c6457600080fd5b506001600160a01b0381351690602001356125c6565b61042860048036036040811015610c9057600080fd5b506001600160a01b03813516906020013561262e565b610468612642565b61046860048036036040811015610cc457600080fd5b506001600160a01b0381351690602001356126ad565b61049660048036036040811015610cf057600080fd5b506001600160a01b03813581169160200135166127d2565b610428612813565b6104b0612823565b61049660048036036020811015610d2e57600080fd5b503561287e565b61046860048036036040811015610d4b57600080fd5b506001600160a01b038135169060200135612889565b61049660048036036020811015610d7757600080fd5b50356001600160a01b03166128aa565b61046860048036036040811015610d9d57600080fd5b810190602081018135600160201b811115610db757600080fd5b820183602082011115610dc957600080fd5b803590602001918460208302840111600160201b83111715610dea57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b811115610e3957600080fd5b820183602082011115610e4b57600080fd5b803590602001918460208302840111600160201b83111715610e6c57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295506128e9945050505050565b61049660048036036040811015610ec057600080fd5b506001600160a01b0381358116916020013516612a26565b610496612a51565b610428612a5b565b61049660048036036040811015610efe57600080fd5b506001600160a01b038135169060200135612a6b565b61049660048036036060811015610f2a57600080fd5b506001600160a01b03813581169160208101359091169060400135612ad0565b610a4860048036036040811015610f6057600080fd5b506001600160a01b038135169060200135612b6c565b61049660048036036040811015610f8c57600080fd5b506001600160a01b038135169060200135612c0b565b610468612c4b565b610496612cd5565b61049660048036036020811015610fc857600080fd5b5035612cdf565b61049660048036036020811015610fe557600080fd5b50356001600160a01b0316612d1d565b6104686004803603602081101561100b57600080fd5b50356001600160a01b0316612d52565b60006001600160e01b031982166301ffc9a760e01b148061104c57506001600160e01b031982166336372b0760e01b145b8061106757506001600160e01b031982166302d57e8d60e11b145b8061108257506001600160e01b03198216634113dcd360e11b145b8061109d57506001600160e01b03198216638562f30360e01b145b806110b857506001600160e01b03198216633b9010bd60e01b145b90505b919050565b6110c8612f0a565b6001600160a01b0316636230001a33846110e133611eb3565b856040518563ffffffff1660e01b815260040161110194939291906145a4565b600060405180830381600087803b15801561111b57600080fd5b505af115801561112f573d6000803e3d6000fd5b505050505050565b6000611141612f36565b6001600160a01b03166304bb4e4384846040518363ffffffff1660e01b815260040161116e9291906145f1565b60206040518083038186803b15801561118657600080fd5b505afa15801561119a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111be9190614519565b90505b92915050565b60606111d1612f62565b905090565b60006111ea6111e3612ff8565b8484612ffc565b50600192915050565b6012546001600160a01b03163314611247576040805162461bcd60e51b815260206004820152601260248201527137b7363c9030b9b9b2ba1036b0b730b3b2b960711b604482015290519081900360640190fd5b601254600160a01b90046001600160401b0316611284576012805467ffffffffffffffff60a01b1916600160a01b426001600160401b0316021790555b565b6011546001600160a01b031633146112b95760405162461bcd60e51b81526004016112b090614d8e565b60405180910390fd5b6112c2816130b0565b600e546001600160a01b03161561133657600e546040516313de97f560e01b81526001600160a01b03909116906313de97f590611303908490600401614ed3565b600060405180830381600087803b15801561131d57600080fd5b505af1158015611331573d6000803e3d6000fd5b505050505b600f546001600160a01b0316158015906113615750600e54600f546001600160a01b03908116911614155b156113c957600f546040516313de97f560e01b81526001600160a01b03909116906313de97f590611396908490600401614ed3565b600060405180830381600087803b1580156113b057600080fd5b505af11580156113c4573d6000803e3d6000fd5b505050505b6010546001600160a01b03161561143d576010546040516313de97f560e01b81526001600160a01b03909116906313de97f59061140a908490600401614ed3565b600060405180830381600087803b15801561142457600080fd5b505af1158015611438573d6000803e3d6000fd5b505050505b50565b600061144a612f36565b6001600160a01b031663142d1018836040518263ffffffff1660e01b81526004016114759190614590565b60206040518083038186803b15801561148d57600080fd5b505afa1580156114a1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b89190614519565b6014805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561154b5780601f106115205761010080835404028352916020019161154b565b820191906000526020600020905b81548152906001019060200180831161152e57829003601f168201915b505050505081565b60025490565b601254600160a01b90046001600160401b0316151590565b600f546001600160a01b031690565b600061158d8484846130f6565b6115fd84611599612ff8565b6115f885604051806060016040528060288152602001614fa6602891396001600160a01b038a166000908152600160205260408120906115d7612ff8565b6001600160a01b03168152602081019190915260400160002054919061320b565b612ffc565b5060015b9392505050565b60006111d1613237565b600c54600160b01b900460ff16806116345750600c54600160a81b900460ff16155b156117bf57611641613240565b6001600160a01b0381161561175757306001600160a01b0316816001600160a01b031663653718836040518163ffffffff1660e01b815260040160206040518083038186803b15801561169357600080fd5b505afa1580156116a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116cb91906143d9565b6001600160a01b0316146116f15760405162461bcd60e51b81526004016112b090614e91565b806001600160a01b03166313de97f5611708613275565b6040518263ffffffff1660e01b81526004016117249190614ed3565b600060405180830381600087803b15801561173e57600080fd5b505af1158015611752573d6000803e3d6000fd5b505050505b600e546040517fbec98a6c0f609cda6b9f23b95824ba6ac733cb57edd17d344f2f27968440073991611797916000916001600160a01b0316908590614702565b60405180910390a1600e80546001600160a01b0319166001600160a01b03831617905561143d565b61143d60003661327b565b60006111ea6117d7612ff8565b846115f885600160006117e8612ff8565b6001600160a01b03908116825260208083019390935260409182016000908120918c1681529252902054906133d4565b60006110b882612362565b6012546001600160a01b03163314611877576040805162461bcd60e51b815260206004820152601260248201527137b7363c9030b9b9b2ba1036b0b730b3b2b960711b604482015290519081900360640190fd5b61188182826133f9565b5050565b600c54600160b01b900460ff16806118a75750600c54600160a81b900460ff16155b156117bf576118b4613240565b6001600160a01b038116611904576040805162461bcd60e51b81526020600482015260126024820152713d32b9379030b9b9b2ba1036b0b730b3b2b960711b604482015290519081900360640190fd5b6012546001600160a01b031615611962576040805162461bcd60e51b815260206004820152601c60248201527f63616e6e6f74207265706c616365206173736574206d616e6167657200000000604482015290519081900360640190fd5b601280546001600160a01b0319166001600160a01b03831617905561143d565b600b546000906001600160a01b031633146119af5760405162461bcd60e51b81526004016112b090614a98565b600a5482106119d05760405162461bcd60e51b81526004016112b090614ca2565b6110b86009836134b9565b60606119e5612f36565b6001600160a01b03166349e3c7e584846040518363ffffffff1660e01b8152600401611a12929190614680565b60006040518083038186803b158015611a2a57600080fd5b505afa158015611a3e573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526111be91908101906144c7565b6011546001600160a01b031681565b60006111be83836134ed565b600c54600090600160a81b900460ff16611aa657600c546001600160a01b03166111d1565b60076001609c1b016001600160a01b031663732524946040518163ffffffff1660e01b815260040160206040518083038186803b158015611ae657600080fd5b505afa158015611afa573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111d191906143d9565b6000611b28612f0a565b6001600160a01b0316630f8b8af733846040518363ffffffff1660e01b8152600401611b559291906145cd565b602060405180830381600087803b158015611b6f57600080fd5b505af11580156114a1573d6000803e3d6000fd5b604051630debfda360e41b815260076001609c1b019063debfda3090611bad903390600401614590565b60206040518083038186803b158015611bc557600080fd5b505afa158015611bd9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bfd91906144f9565b611c195760405162461bcd60e51b81526004016112b090614dc5565b6001600160e01b031981166000908152600d602052604090208054611c505760405162461bcd60e51b81526004016112b090614dec565b8054421015611c715760405162461bcd60e51b81526004016112b090614b44565b6000816001018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015611d0b5780601f10611ce057610100808354040283529160200191611d0b565b820191906000526020600020905b815481529060010190602001808311611cee57829003601f168201915b505050506001600160e01b031985166000908152600d602052604081208181559293509050611d3d6001830182614290565b5050600c805460ff60b01b1916600160b01b1790556040516000903090611d65908490614574565b6000604051808303816000865af19150503d8060008114611da2576040519150601f19603f3d011682016040523d82523d6000602084013e611da7565b606091505b5050600c805460ff60b01b191690556040519091507fa7326b57fc9cfe267aaea5e7f0b01757154d265620a0585819416ee9ddd2c43890611deb90869042906146a2565b60405180910390a1611dfc8161351e565b50505050565b60076001609c1b0181565b611e1561353b565b6001600160e01b031981166000908152600d6020526040902054611e4b5760405162461bcd60e51b81526004016112b090614dec565b7f7735b2391c38a81419c513e30ca578db7158eadd7101511b23e221c654d19cf88142604051611e7c9291906146a2565b60405180910390a16001600160e01b031981166000908152600d6020526040812081815590611eae6001830182614290565b505050565b6001600160a01b031660009081526020819052604090205490565b600d602090815260009182526040918290208054600180830180548651600293821615610100026000190190911692909204601f810186900486028301860190965285825291949293909290830182828015611f6b5780601f10611f4057610100808354040283529160200191611f6b565b820191906000526020600020905b815481529060010190602001808311611f4e57829003601f168201915b5050505050905082565b600c54600160b01b900460ff1680611f975750600c54600160a81b900460ff16155b156117bf57611fa4613240565b6001600160a01b0381161561216e57306001600160a01b0316816001600160a01b031663653718836040518163ffffffff1660e01b815260040160206040518083038186803b158015611ff657600080fd5b505afa15801561200a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061202e91906143d9565b6001600160a01b0316146120545760405162461bcd60e51b81526004016112b090614e91565b601154600160a01b900460ff1615806120d95750806001600160a01b031663aa94d3f26040518163ffffffff1660e01b815260040160206040518083038186803b1580156120a157600080fd5b505afa1580156120b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120d991906144f9565b6120f55760405162461bcd60e51b81526004016112b090614a18565b806001600160a01b03166313de97f561210c613275565b6040518263ffffffff1660e01b81526004016121289190614ed3565b600060405180830381600087803b15801561214257600080fd5b505af1158015612156573d6000803e3d6000fd5b50506011805460ff60a01b1916600160a01b17905550505b600f546040517fbec98a6c0f609cda6b9f23b95824ba6ac733cb57edd17d344f2f279684400739916121ae916001916001600160a01b0316908590614702565b60405180910390a1600f80546001600160a01b0319166001600160a01b03831617905561143d565b6060806000806121e4612f36565b6001600160a01b0316637de5b8ed866040518263ffffffff1660e01b815260040161220f9190614590565b60006040518083038186803b15801561222757600080fd5b505afa15801561223b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261226391908101906143f5565b93509350935093509193509193565b600c54600160b01b900460ff16806122945750600c54600160a81b900460ff16155b156117bf576122a1613240565b601180546001600160a01b0319166001600160a01b03831617905561143d565b60006122cb612f36565b6001600160a01b03166331503927846122e48686611a75565b856040518463ffffffff1660e01b815260040161116e9392919061465f565b6010546001600160a01b031690565b600061231c612f36565b6001600160a01b03166392bfe6d884846040518363ffffffff1660e01b815260040161116e9291906145f1565b6012546001600160a01b031681565b60606111d1613573565b60006110b8826135d4565b600e546001600160a01b031690565b600b546001600160a01b031681565b600c54600160b01b900460ff16806123ad5750600c54600160a81b900460ff16155b156117bf576123ba613240565b306001600160a01b0316816001600160a01b031663653718836040518163ffffffff1660e01b815260040160206040518083038186803b1580156123fd57600080fd5b505afa158015612411573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061243591906143d9565b6001600160a01b03161461245b5760405162461bcd60e51b81526004016112b090614b7b565b6010546040517fbec98a6c0f609cda6b9f23b95824ba6ac733cb57edd17d344f2f2796844007399161249b916002916001600160a01b0316908590614702565b60405180910390a1601080546001600160a01b0319166001600160a01b03831617905561143d565b600c54600160a01b900460ff16156124ed5760405162461bcd60e51b81526004016112b090614d29565b600c8054600160a01b60ff60a01b19909116176001600160a01b0319166001600160a01b0383161790556040517f9789733827840833afc031fb2ef9ab6894271f77bad2085687cf4ae5c7bee4db90612547908390614590565b60405180910390a150565b6012546001600160a01b031633146125a6576040805162461bcd60e51b815260206004820152601260248201527137b7363c9030b9b9b2ba1036b0b730b3b2b960711b604482015290519081900360640190fd5b6118818282613604565b601254600160a01b90046001600160401b031681565b60006111ea6125d3612ff8565b846115f885604051806060016040528060258152602001614fce60259139600160006125fd612ff8565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919061320b565b60006111ea61263b612ff8565b84846130f6565b61264a612f0a565b6001600160a01b03166305109ecf3361266233611eb3565b6040518363ffffffff1660e01b815260040161267f9291906145f1565b600060405180830381600087803b15801561269957600080fd5b505af1158015611dfc573d6000803e3d6000fd5b600f54600e546001600160a01b039182169116811561273457816001600160a01b031663c7c62fab33866126e13388611a75565b876040518563ffffffff1660e01b815260040161270194939291906145a4565b600060405180830381600087803b15801561271b57600080fd5b505af115801561272f573d6000803e3d6000fd5b505050505b816001600160a01b0316816001600160a01b03161415801561275e57506001600160a01b03811615155b15611dfc57806001600160a01b031663c7c62fab338661277e3388611a75565b876040518563ffffffff1660e01b815260040161279e94939291906145a4565b600060405180830381600087803b1580156127b857600080fd5b505af19250505080156127c9575060015b611dfc57611dfc565b60006127dc612f36565b6001600160a01b0316639dc6b9f284846127f587611eb3565b6040518463ffffffff1660e01b815260040161116e9392919061460a565b601154600160a01b900460ff1681565b6013805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561154b5780601f106115205761010080835404028352916020019161154b565b60006110b8826136da565b612891612f0a565b6001600160a01b031663404d9e8233846110e133611eb3565b60006128b4612f36565b6001600160a01b0316634a03d556836128cc85611eb3565b6040518363ffffffff1660e01b81526004016114759291906145f1565b805182511461290a5760405162461bcd60e51b81526004016112b0906147d8565b6000612914612f0a565b9050600061292133611eb3565b6040516305109ecf60e01b81529091506001600160a01b038316906305109ecf9061295290339085906004016145f1565b600060405180830381600087803b15801561296c57600080fd5b505af1158015612980573d6000803e3d6000fd5b5050505060005b845181101561143857826001600160a01b0316636230001a338784815181106129ac57fe5b6020026020010151858886815181106129c157fe5b60200260200101516040518563ffffffff1660e01b81526004016129e894939291906145a4565b600060405180830381600087803b158015612a0257600080fd5b505af1158015612a16573d6000803e3d6000fd5b5050600190920191506129879050565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b60006111d1613275565b600c54600160a81b900460ff1681565b6000612a75612f36565b6001600160a01b031663e587497e84846040518363ffffffff1660e01b8152600401612aa29291906145f1565b602060405180830381600087803b158015612abc57600080fd5b505af115801561119a573d6000803e3d6000fd5b6000612ada612f36565b6001600160a01b031663833aca928585612af48887611a75565b866040518563ffffffff1660e01b8152600401612b1494939291906145a4565b60206040518083038186803b158015612b2c57600080fd5b505afa158015612b40573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b649190614519565b949350505050565b606080600080612b7a612f36565b6001600160a01b031663ed475a7987876040518363ffffffff1660e01b8152600401612ba79291906145f1565b60006040518083038186803b158015612bbf57600080fd5b505afa158015612bd3573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052612bfb91908101906143f5565b9299919850965090945092505050565b600b546000906001600160a01b03163314612c385760405162461bcd60e51b81526004016112b090614a98565b600a546111be9060069085908590613778565b612c5361353b565b600c54600160a81b900460ff1615612c7d5760405162461bcd60e51b81526004016112b090614934565b600c8054600161ff0160a01b031916600160a81b1790556040517f83af113638b5422f9e977cebc0aaf0eaf2188eb9a8baae7f9d46c42b33a1560c90612ccb9060076001609c1b0190614590565b60405180910390a1565b60006111d1611553565b600b546000906001600160a01b03163314612d0c5760405162461bcd60e51b81526004016112b090614a98565b600a546110b89060079084906137be565b6000612d27612f36565b6001600160a01b031663f6837767836040518263ffffffff1660e01b81526004016114759190614590565b600c54600160b01b900460ff1680612d745750600c54600160a81b900460ff16155b156117bf57612d81613240565b612d8a816138ab565b600e546001600160a01b031615612dfe57600e5460405163f6a494af60e01b81526001600160a01b039091169063f6a494af90612dcb908490600401614590565b600060405180830381600087803b158015612de557600080fd5b505af1158015612df9573d6000803e3d6000fd5b505050505b600f546001600160a01b031615801590612e295750600e54600f546001600160a01b03908116911614155b15612e9157600f5460405163f6a494af60e01b81526001600160a01b039091169063f6a494af90612e5e908490600401614590565b600060405180830381600087803b158015612e7857600080fd5b505af1158015612e8c573d6000803e3d6000fd5b505050505b6010546001600160a01b031615612f055760105460405163f6a494af60e01b81526001600160a01b039091169063f6a494af90612ed2908490600401614590565b600060405180830381600087803b158015612eec57600080fd5b505af1158015612f00573d6000803e3d6000fd5b505050505b61143d565b600f546000906001600160a01b0316806111d15760405162461bcd60e51b81526004016112b090614ac7565b600e546000906001600160a01b0316806111d15760405162461bcd60e51b81526004016112b090614e23565b60038054604080516020601f6002600019610100600188161502019095169490940493840181900481028201810190925282815260609390929091830182828015612fee5780601f10612fc357610100808354040283529160200191612fee565b820191906000526020600020905b815481529060010190602001808311612fd157829003601f168201915b5050505050905090565b3390565b6001600160a01b0383166130225760405162461bcd60e51b81526004016112b090614c5e565b6001600160a01b0382166130485760405162461bcd60e51b81526004016112b090614807565b6001600160a01b0380841660008181526001602090815260408083209487168084529490915290819020849055517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906130a3908590614ed3565b60405180910390a3505050565b600a548110156130d25760405162461bcd60e51b81526004016112b090614880565b4381106130f15760405162461bcd60e51b81526004016112b090614797565b600a55565b6001600160a01b03831661311c5760405162461bcd60e51b81526004016112b090614c19565b6001600160a01b0382166131425760405162461bcd60e51b81526004016112b090614754565b61314d8383836138cd565b61318a81604051806060016040528060268152602001614f80602691396001600160a01b038616600090815260208190526040902054919061320b565b6001600160a01b0380851660009081526020819052604080822093909355908416815220546131b990826133d4565b6001600160a01b0380841660008181526020819052604090819020939093559151908516907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906130a3908590614ed3565b6000818484111561322f5760405162461bcd60e51b81526004016112b09190614721565b505050900390565b60055460ff1690565b600c54600160b01b900460ff161561326d5733301461325b57fe5b600c805460ff60b01b19169055611284565b61128461353b565b600a5490565b61328361353b565b600082359050600060076001609c1b016001600160a01b0316636221a54b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156132cb57600080fd5b505afa1580156132df573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133039190614519565b905060008142019050604051806040016040528082815260200186868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250506001600160e01b031986168152600d602090815260409091208351815583820151805191935061338c9260018501929101906142d4565b509050507fed948300a3694aa01d4a6b258bfd664350193d770c0b51f8387277f6d83ea3b6838287876040516133c594939291906146bc565b60405180910390a15050505050565b6000828201838110156111be5760405162461bcd60e51b81526004016112b090614849565b6001600160a01b03821661341f5760405162461bcd60e51b81526004016112b090614e5a565b61342b600083836138cd565b60025461343890826133d4565b6002556001600160a01b03821660009081526020819052604090205461345e90826133d4565b6001600160a01b0383166000818152602081905260408082209390935591519091907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906134ad908590614ed3565b60405180910390a35050565b600081815260208390526040812054156134e4575060008181526020839052604081205560016111c1565b50600092915050565b600081600a548110156135125760405162461bcd60e51b81526004016112b0906149cb565b612b64600685856139a1565b3d604051818101604052816000823e8215613537578181f35b8181fd5b613543611a81565b6001600160a01b0316336001600160a01b0316146112845760405162461bcd60e51b81526004016112b09061496b565b60048054604080516020601f6002600019610100600188161502019095169490940493840181900481028201810190925282815260609390929091830182828015612fee5780601f10612fc357610100808354040283529160200191612fee565b600081600a548110156135f95760405162461bcd60e51b81526004016112b0906149cb565b6116016007846139cc565b6001600160a01b03821661362a5760405162461bcd60e51b81526004016112b090614bd8565b613636826000836138cd565b61367381604051806060016040528060228152602001614f5e602291396001600160a01b038516600090815260208190526040902054919061320b565b6001600160a01b0383166000908152602081905260409020556002546136999082613af0565b6002556040516000906001600160a01b038416907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906134ad908590614ed3565b600081600a548110156136ff5760405162461bcd60e51b81526004016112b0906149cb565b43831061371e5760405162461bcd60e51b81526004016112b0906148c8565b60008061372e6009600787613b18565b915091508015613770577ffec477a10b4fcdfdf1114eb32b3caf6118b2d76d20e1fcb70007274bb4b616be856040516137679190614ed3565b60405180910390a15b509392505050565b60006001600160a01b038416156137b3576001600160a01b03841660009081526020869052604090206137ac9084846137be565b9050612b64565b506000949350505050565b6000816137cd57506000611601565b6001840154600160401b90046001600160401b0316806137f1576000915050611601565b60018501546001600160401b0316600061381761380e83886133d4565b60018503613b76565b9050815b818110801561384c575060018101600090815260208990526040902054600160c01b90046001600160401b03168610155b156138685760008181526020899052604081205560010161381b565b8281111561389d5761387981613b8c565b60018901805467ffffffffffffffff19166001600160401b03929092169190911790555b919091039695505050505050565b600b80546001600160a01b0319166001600160a01b0392909216919091179055565b601254600160a01b90046001600160401b031615613927576040805162461bcd60e51b8152602060048201526012602482015271198b585cdcd95d081d195c9b5a5b985d195960721b604482015290519081900360640190fd5b6001600160a01b038316158061394557508061394284611eb3565b10155b613996576040805162461bcd60e51b815260206004820152601760248201527f662d61737365742062616c616e636520746f6f206c6f77000000000000000000604482015290519081900360640190fd5b611eae838383613bb5565b6001600160a01b03821660009081526020849052604081206139c381846139cc565b95945050505050565b6001820154600090600160401b90046001600160401b0316806139f35760009150506111c1565b4383101580613a2557506000198101600090815260208590526040902054600160c01b90046001600160401b03168310155b15613a4d57600019016000908152602084905260409020546001600160c01b031690506111c1565b60018401546001600160401b039081166000818152602087905260409020549091600160c01b90910416841015613aa7578015613a9c5760405162461bcd60e51b81526004016112b090614cd9565b6000925050506111c1565b6001850154600090613acd9087908490600160401b90046001600160401b031688613d5b565b6000908152602087905260409020546001600160c01b0316935050505092915050565b600082821115613b125760405162461bcd60e51b81526004016112b0906148fd565b50900390565b60008181526020849052604081205481908015613b3e5760001901915060009050613b6e565b6000613b4a86866139cc565b9050613b578160016133d4565b600086815260208990526040902055925060019150505b935093915050565b6000818310613b8557816111be565b5090919050565b6000600160401b8210613bb15760405162461bcd60e51b81526004016112b090614afe565b5090565b816001600160a01b0316836001600160a01b03161415613be75760405162461bcd60e51b81526004016112b090614d57565b60006001600160a01b038416613bfe576000613c07565b613c0784611eb3565b905060006001600160a01b038416613c20576000613c29565b613c2984611eb3565b600f549091506001600160a01b03168015613ca95760405163756da1b160e11b81526001600160a01b0382169063eadb436290613c729089908990889088908b9060040161462e565b600060405180830381600087803b158015613c8c57600080fd5b505af1158015613ca0573d6000803e3d6000fd5b50505050613cce565b601154600160a01b900460ff16613cce576011805460ff60a01b1916600160a01b1790555b6010546001600160a01b03168015613d475760405163756da1b160e11b81526001600160a01b0382169063eadb436290613d14908a908a90899089908c9060040161462e565b600060405180830381600087803b158015613d2e57600080fd5b505af1158015613d42573d6000803e3d6000fd5b505050505b613d52878787613de5565b50505050505050565b60008381613d6a856001613af0565b90505b81811115613ddb576000613d976002613d916001613d8b86886133d4565b906133d4565b90613e25565b600081815260208a90526040902054909150600160c01b90046001600160401b03168510613dc757809250613dd5565b613dd2816001613af0565b91505b50613d6d565b5095945050505050565b6001600160a01b038316613e0257613dfd8282613e57565b611eae565b6001600160a01b038216613e1a57613dfd8382613eb4565b611eae838383613f63565b6000808211613e465760405162461bcd60e51b81526004016112b090614994565b818381613e4f57fe5b049392505050565b6000613e6782613d8b8543611a75565b9050613e7560068483613f99565b600a54613e89906006908590600290613778565b50613ea2613e9a83613d8b43612362565b600790613fb7565b600a54611dfc906007906002906137be565b6000613efa8260405180604001604052806016815260200175213ab937103a37b7903134b3903337b91037bbb732b960511b815250613ef38643611a75565b919061320b565b9050613f0860068483613f99565b600a54613f1c906006908590600290613778565b50613ea2613e9a836040518060400160405280601d81526020017f4275726e20746f6f2062696720666f7220746f74616c20737570706c79000000815250613ef343612362565b613f706006848484614178565b600a54613f84906006908590600290613778565b50600a54611dfc906006908490600290613778565b6001600160a01b0382166000908152602084905260409020611dfc81835b6001820154600160401b90046001600160401b03168061406e576040518060400160405280613fe584614207565b6001600160c01b03168152602001613ffc43613b8c565b6001600160401b03908116909152600080805260208681526040909120835181549490920151909216600160c01b026001600160c01b039182166001600160c01b0319909416939093171691909117905560018301805467ffffffffffffffff60401b1916600160401b179055611eae565b600019810160009081526020849052604090208054600160c01b90046001600160401b0316438114156140c4576140a484614207565b82546001600160c01b0319166001600160c01b0391909116178255611438565b8043116140cd57fe5b60405180604001604052806140e186614207565b6001600160c01b031681526020016140f843613b8c565b6001600160401b039081169091526000858152602088815260409091208351815494909201518316600160c01b026001600160c01b039283166001600160c01b0319909516949094179091169290921790915560018087018054918601909216600160401b0267ffffffffffffffff60401b199091161790555050505050565b8061418257611dfc565b6001600160a01b0383161580156141a057506001600160a01b038216155b156141a757fe5b6001600160a01b038316156141db5760006141cc826141c6878761422c565b90613af0565b90506141d9858583613f99565b505b6001600160a01b03821615611dfc5760006141fa82613d8b878661422c565b9050611438858483613f99565b6000600160c01b8210613bb15760405162461bcd60e51b81526004016112b090614a61565b6001600160a01b0381166000908152602083905260408120612b64816001810154600090600160401b90046001600160401b03168061426f5760009150506110bb565b6000190160009081526020929092525060409020546001600160c01b031690565b50805460018160011615610100020316600290046000825580601f106142b6575061143d565b601f01602090049060005260206000209081019061143d9190614358565b828054600181600116156101000203166002900490600052602060002090601f01602090048101928261430a5760008555614350565b82601f1061432357805160ff1916838001178555614350565b82800160010185558215614350579182015b82811115614350578251825591602001919060010190614335565b50613bb19291505b5b80821115613bb15760008155600101614359565b600082601f83011261437d578081fd5b8151602061439261438d83614eff565b614edc565b82815281810190858301838502870184018810156143ae578586fd5b855b858110156143cc578151845292840192908401906001016143b0565b5090979650505050505050565b6000602082840312156143ea578081fd5b81516111be81614f48565b6000806000806080858703121561440a578283fd5b84516001600160401b0380821115614420578485fd5b818701915087601f830112614433578485fd5b8151602061444361438d83614eff565b82815281810190858301838502870184018d101561445f57898afd5b8996505b8487101561448a57805161447681614f48565b835260019690960195918301918301614463565b50918a01519198509093505050808211156144a3578485fd5b506144b08782880161436d565b604087015160609097015195989097509350505050565b6000602082840312156144d8578081fd5b81516001600160401b038111156144ed578182fd5b612b648482850161436d565b60006020828403121561450a578081fd5b815180151581146111be578182fd5b60006020828403121561452a578081fd5b5051919050565b6000815180845260208085019450808401835b838110156145695781516001600160a01b031687529582019590820190600101614544565b509495945050505050565b60008251614586818460208701614f1c565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0394851681529290931660208301526040820152606081019190915260800190565b6001600160a01b0383168152604060208201819052600090612b6490830184614531565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03958616815293909416602084015260408301919091526060820152608081019190915260a00190565b6001600160a01b039390931683526020830191909152604082015260600190565b6000604082526146936040830185614531565b90508260208301529392505050565b6001600160e01b0319929092168252602082015260400190565b600063ffffffff60e01b861682528460208301526060604083015282606083015282846080840137818301608090810191909152601f909201601f191601019392505050565b9283526001600160a01b03918216602084015216604082015260600190565b6000602082528251806020840152614740816040850160208701614f1c565b601f01601f19169190910160400192915050565b60208082526023908201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260408201526265737360e81b606082015260800190565b60208082526021908201527f436c65616e757020626c6f636b206d75737420626520696e20746865207061736040820152601d60fa1b606082015260800190565b602080825260159082015274082e4e4c2f240d8cadccee8d040dad2e6dac2e8c6d605b1b604082015260600190565b60208082526022908201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604082015261737360f01b606082015260800190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b60208082526028908201527f436c65616e757020626c6f636b206e756d626572206d757374206e6576657220604082015267646563726561736560c01b606082015260800190565b6020808252818101527f43616e206f6e6c79206265207573656420666f72207061737420626c6f636b73604082015260600190565b6020808252601e908201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604082015260600190565b6020808252601a908201527f616c726561647920696e2070726f64756374696f6e206d6f6465000000000000604082015260600190565b6020808252600f908201526e6f6e6c7920676f7665726e616e636560881b604082015260600190565b6020808252601a908201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604082015260600190565b6020808252602d908201527f436865636b506f696e7461626c653a2072656164696e672066726f6d20636c6560408201526c616e65642d757020626c6f636b60981b606082015260800190565b60208082526029908201527f5650436f6e7472616374206e6f7420636f6e6669677572656420666f722072656040820152681c1b1858d95b595b9d60ba1b606082015260800190565b6020808252601d908201527f76616c756520646f65736e27742066697420696e203139322062697473000000604082015260600190565b60208082526015908201527413db9b1e4818db19585b995c8818dbdb9d1c9858dd605a1b604082015260600190565b6020808252601e908201527f546f6b656e206d697373696e67207772697465205650436f6e74726163740000604082015260600190565b60208082526026908201527f53616665436173743a2076616c756520646f65736e27742066697420696e203660408201526534206269747360d01b606082015260800190565b60208082526019908201527f74696d656c6f636b3a206e6f7420616c6c6f7765642079657400000000000000604082015260600190565b6020808252603d908201527f476f7665726e616e636520766f746520706f77657220636f6e7472616374206460408201527f6f6573206e6f742062656c6f6e6720746f207468697320746f6b656e2e000000606082015260800190565b60208082526021908201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736040820152607360f81b606082015260800190565b60208082526025908201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604082015264647265737360d81b606082015260800190565b60208082526024908201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646040820152637265737360e01b606082015260800190565b6020808252601e908201527f4e6f20636c65616e757020616674657220636c65616e757020626c6f636b0000604082015260600190565b60208082526030908201527f436865636b506f696e74486973746f72793a2072656164696e672066726f6d2060408201526f636c65616e65642d757020626c6f636b60801b606082015260800190565b602080825260149082015273696e697469616c6973656420213d2066616c736560601b604082015260600190565b60208082526017908201527f43616e6e6f74207472616e7366657220746f2073656c66000000000000000000604082015260600190565b6020808252601a908201527f6f6e6c7920636c65616e757020626c6f636b206d616e61676572000000000000604082015260600190565b6020808252600d908201526c37b7363c9032bc32b1baba37b960991b604082015260600190565b6020808252601a908201527f74696d656c6f636b3a20696e76616c69642073656c6563746f72000000000000604082015260600190565b6020808252601d908201527f546f6b656e206d697373696e672072656164205650436f6e7472616374000000604082015260600190565b6020808252601f908201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604082015260600190565b60208082526022908201527f5650436f6e7472616374206e6f74206f776e6564206279207468697320746f6b60408201526132b760f11b606082015260800190565b90815260200190565b6040518181016001600160401b0381118282101715614ef757fe5b604052919050565b60006001600160401b03821115614f1257fe5b5060209081020190565b60005b83811015614f37578181015183820152602001614f1f565b83811115611dfc5750506000910152565b6001600160a01b038116811461143d57600080fdfe45524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220ce7ac70849c0f2c17e85f0ca26d14bcf7c813b48abe9fa8125a7ab578ced959364736f6c634300070600330000000000000000000000005a11fa259c898e6973db2f3c9e82339a53c777c000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044658525000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000846546573745852500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008546573742058525000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000077465737458525000000000000000000000000000000000000000000000000000
Deployed ByteCode
0x608060405234801561001057600080fd5b50600436106103fc5760003560e01c80638c2b8ae111610215578063c9230c5d11610125578063e587497e116100b8578063f5a9838311610087578063f5a9838314610fa2578063f5f3d4f714610faa578063f62f8f3a14610fb2578063f683776714610fcf578063f6a494af14610ff5576103fc565b8063e587497e14610ee8578063e64767aa14610f14578063ed475a7914610f4a578063f0e292c914610f76576103fc565b8063dc4fcda7116100f4578063dc4fcda714610d87578063dd62ed3e14610eaa578063deea13e714610ed8578063e17f212e14610ee0576103fc565b8063c9230c5d14610d10578063caeb942b14610d18578063d06dc3ad14610d35578063d6aa0b7714610d61576103fc565b80639d6a890f116101a8578063a9059cbb11610177578063a9059cbb14610c7a578063b302f39314610ca6578063bbd6fbf814610cae578063be0ca74714610cda578063c787a8fc14610d08576103fc565b80639d6a890f14610bd85780639dc29fac14610bfe5780639e3bc20814610c2a578063a457c2d714610c4e576103fc565b8063981b24d0116101e4578063981b24d014610b855780639b3baa0e14610ba25780639ca20e4e14610baa5780639ca2231a14610bb2576103fc565b80638c2b8ae114610b4157806392bfe6d814610b4957806394217ad114610b7557806395d89b4114610b7d576103fc565b806340c10f19116103105780635ff27079116102a357806374e6310e1161027257806374e6310e14610956578063755d10a4146109fc5780637de5b8ed14610a225780637f4fcaa914610aef57806383035a8214610b15576103fc565b80635ff27079146108da57806362354e031461090157806367fc40291461090957806370a0823114610930576103fc565b80634eac870f116102df5780634eac870f146107fd5780634ee2cd7e146108055780635aa6e675146108315780635d6d11eb14610839576103fc565b806340c10f191461069b57806343060237146106c757806343ea370b146106ed57806349e3c7e51461070a576103fc565b8063176de7a81161039357806323b872dd1161036257806323b872dd146105d8578063313ce5671461060e57806331d12a161461062c57806339509351146106525780633e5aa26a1461067e576103fc565b8063176de7a81461059c57806318160ddd146105a4578063194307bf146105ac5780631fec092a146105b4576103fc565b8063095ea7b3116103cf578063095ea7b3146105255780630c08bf881461055157806313de97f514610559578063142d101814610576576103fc565b806301ffc9a714610401578063026e402b1461043c57806304bb4e431461046a57806306fdde03146104a8575b600080fd5b6104286004803603602081101561041757600080fd5b50356001600160e01b03191661101b565b604080519115158252519081900360200190f35b6104686004803603604081101561045257600080fd5b506001600160a01b0381351690602001356110c0565b005b6104966004803603604081101561048057600080fd5b506001600160a01b038135169060200135611137565b60408051918252519081900360200190f35b6104b06111c7565b6040805160208082528351818301528351919283929083019185019080838360005b838110156104ea5781810151838201526020016104d2565b50505050905090810190601f1680156105175780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6104286004803603604081101561053b57600080fd5b506001600160a01b0381351690602001356111d6565b6104686111f3565b6104686004803603602081101561056f57600080fd5b5035611286565b6104966004803603602081101561058c57600080fd5b50356001600160a01b0316611440565b6104b06114c5565b610496611553565b610428611559565b6105bc611571565b604080516001600160a01b039092168252519081900360200190f35b610428600480360360608110156105ee57600080fd5b506001600160a01b03813581169160208101359091169060400135611580565b610616611608565b6040805160ff9092168252519081900360200190f35b6104686004803603602081101561064257600080fd5b50356001600160a01b0316611612565b6104286004803603604081101561066857600080fd5b506001600160a01b0381351690602001356117ca565b6104966004803603602081101561069457600080fd5b5035611818565b610468600480360360408110156106b157600080fd5b506001600160a01b038135169060200135611823565b610468600480360360208110156106dd57600080fd5b50356001600160a01b0316611885565b6104966004803603602081101561070357600080fd5b5035611982565b6107ad6004803603604081101561072057600080fd5b810190602081018135600160201b81111561073a57600080fd5b82018360208201111561074c57600080fd5b803590602001918460208302840111600160201b8311171561076d57600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955050913592506119db915050565b60408051602080825283518183015283519192839290830191858101910280838360005b838110156107e95781810151838201526020016107d1565b505050509050019250505060405180910390f35b6105bc611a66565b6104966004803603604081101561081b57600080fd5b506001600160a01b038135169060200135611a75565b6105bc611a81565b6104966004803603602081101561084f57600080fd5b810190602081018135600160201b81111561086957600080fd5b82018360208201111561087b57600080fd5b803590602001918460208302840111600160201b8311171561089c57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550611b1e945050505050565b610468600480360360208110156108f057600080fd5b50356001600160e01b031916611b83565b6105bc611e02565b6104686004803603602081101561091f57600080fd5b50356001600160e01b031916611e0d565b6104966004803603602081101561094657600080fd5b50356001600160a01b0316611eb3565b61097d6004803603602081101561096c57600080fd5b50356001600160e01b031916611ece565b6040518083815260200180602001828103825283818151815260200191508051906020019080838360005b838110156109c05781810151838201526020016109a8565b50505050905090810190601f1680156109ed5780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b61046860048036036020811015610a1257600080fd5b50356001600160a01b0316611f75565b610a4860048036036020811015610a3857600080fd5b50356001600160a01b03166121d6565b604051808060200180602001858152602001848152602001838103835287818151815260200191508051906020019060200280838360005b83811015610a98578181015183820152602001610a80565b50505050905001838103825286818151815260200191508051906020019060200280838360005b83811015610ad7578181015183820152602001610abf565b50505050905001965050505050505060405180910390f35b61046860048036036020811015610b0557600080fd5b50356001600160a01b0316612272565b61049660048036036040811015610b2b57600080fd5b506001600160a01b0381351690602001356122c1565b6105bc612303565b61049660048036036040811015610b5f57600080fd5b506001600160a01b038135169060200135612312565b6105bc612349565b6104b0612358565b61049660048036036020811015610b9b57600080fd5b5035612362565b6105bc61236d565b6105bc61237c565b61046860048036036020811015610bc857600080fd5b50356001600160a01b031661238b565b61046860048036036020811015610bee57600080fd5b50356001600160a01b03166124c3565b61046860048036036040811015610c1457600080fd5b506001600160a01b038135169060200135612552565b610c326125b0565b604080516001600160401b039092168252519081900360200190f35b61042860048036036040811015610c6457600080fd5b506001600160a01b0381351690602001356125c6565b61042860048036036040811015610c9057600080fd5b506001600160a01b03813516906020013561262e565b610468612642565b61046860048036036040811015610cc457600080fd5b506001600160a01b0381351690602001356126ad565b61049660048036036040811015610cf057600080fd5b506001600160a01b03813581169160200135166127d2565b610428612813565b6104b0612823565b61049660048036036020811015610d2e57600080fd5b503561287e565b61046860048036036040811015610d4b57600080fd5b506001600160a01b038135169060200135612889565b61049660048036036020811015610d7757600080fd5b50356001600160a01b03166128aa565b61046860048036036040811015610d9d57600080fd5b810190602081018135600160201b811115610db757600080fd5b820183602082011115610dc957600080fd5b803590602001918460208302840111600160201b83111715610dea57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b811115610e3957600080fd5b820183602082011115610e4b57600080fd5b803590602001918460208302840111600160201b83111715610e6c57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295506128e9945050505050565b61049660048036036040811015610ec057600080fd5b506001600160a01b0381358116916020013516612a26565b610496612a51565b610428612a5b565b61049660048036036040811015610efe57600080fd5b506001600160a01b038135169060200135612a6b565b61049660048036036060811015610f2a57600080fd5b506001600160a01b03813581169160208101359091169060400135612ad0565b610a4860048036036040811015610f6057600080fd5b506001600160a01b038135169060200135612b6c565b61049660048036036040811015610f8c57600080fd5b506001600160a01b038135169060200135612c0b565b610468612c4b565b610496612cd5565b61049660048036036020811015610fc857600080fd5b5035612cdf565b61049660048036036020811015610fe557600080fd5b50356001600160a01b0316612d1d565b6104686004803603602081101561100b57600080fd5b50356001600160a01b0316612d52565b60006001600160e01b031982166301ffc9a760e01b148061104c57506001600160e01b031982166336372b0760e01b145b8061106757506001600160e01b031982166302d57e8d60e11b145b8061108257506001600160e01b03198216634113dcd360e11b145b8061109d57506001600160e01b03198216638562f30360e01b145b806110b857506001600160e01b03198216633b9010bd60e01b145b90505b919050565b6110c8612f0a565b6001600160a01b0316636230001a33846110e133611eb3565b856040518563ffffffff1660e01b815260040161110194939291906145a4565b600060405180830381600087803b15801561111b57600080fd5b505af115801561112f573d6000803e3d6000fd5b505050505050565b6000611141612f36565b6001600160a01b03166304bb4e4384846040518363ffffffff1660e01b815260040161116e9291906145f1565b60206040518083038186803b15801561118657600080fd5b505afa15801561119a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111be9190614519565b90505b92915050565b60606111d1612f62565b905090565b60006111ea6111e3612ff8565b8484612ffc565b50600192915050565b6012546001600160a01b03163314611247576040805162461bcd60e51b815260206004820152601260248201527137b7363c9030b9b9b2ba1036b0b730b3b2b960711b604482015290519081900360640190fd5b601254600160a01b90046001600160401b0316611284576012805467ffffffffffffffff60a01b1916600160a01b426001600160401b0316021790555b565b6011546001600160a01b031633146112b95760405162461bcd60e51b81526004016112b090614d8e565b60405180910390fd5b6112c2816130b0565b600e546001600160a01b03161561133657600e546040516313de97f560e01b81526001600160a01b03909116906313de97f590611303908490600401614ed3565b600060405180830381600087803b15801561131d57600080fd5b505af1158015611331573d6000803e3d6000fd5b505050505b600f546001600160a01b0316158015906113615750600e54600f546001600160a01b03908116911614155b156113c957600f546040516313de97f560e01b81526001600160a01b03909116906313de97f590611396908490600401614ed3565b600060405180830381600087803b1580156113b057600080fd5b505af11580156113c4573d6000803e3d6000fd5b505050505b6010546001600160a01b03161561143d576010546040516313de97f560e01b81526001600160a01b03909116906313de97f59061140a908490600401614ed3565b600060405180830381600087803b15801561142457600080fd5b505af1158015611438573d6000803e3d6000fd5b505050505b50565b600061144a612f36565b6001600160a01b031663142d1018836040518263ffffffff1660e01b81526004016114759190614590565b60206040518083038186803b15801561148d57600080fd5b505afa1580156114a1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b89190614519565b6014805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561154b5780601f106115205761010080835404028352916020019161154b565b820191906000526020600020905b81548152906001019060200180831161152e57829003601f168201915b505050505081565b60025490565b601254600160a01b90046001600160401b0316151590565b600f546001600160a01b031690565b600061158d8484846130f6565b6115fd84611599612ff8565b6115f885604051806060016040528060288152602001614fa6602891396001600160a01b038a166000908152600160205260408120906115d7612ff8565b6001600160a01b03168152602081019190915260400160002054919061320b565b612ffc565b5060015b9392505050565b60006111d1613237565b600c54600160b01b900460ff16806116345750600c54600160a81b900460ff16155b156117bf57611641613240565b6001600160a01b0381161561175757306001600160a01b0316816001600160a01b031663653718836040518163ffffffff1660e01b815260040160206040518083038186803b15801561169357600080fd5b505afa1580156116a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116cb91906143d9565b6001600160a01b0316146116f15760405162461bcd60e51b81526004016112b090614e91565b806001600160a01b03166313de97f5611708613275565b6040518263ffffffff1660e01b81526004016117249190614ed3565b600060405180830381600087803b15801561173e57600080fd5b505af1158015611752573d6000803e3d6000fd5b505050505b600e546040517fbec98a6c0f609cda6b9f23b95824ba6ac733cb57edd17d344f2f27968440073991611797916000916001600160a01b0316908590614702565b60405180910390a1600e80546001600160a01b0319166001600160a01b03831617905561143d565b61143d60003661327b565b60006111ea6117d7612ff8565b846115f885600160006117e8612ff8565b6001600160a01b03908116825260208083019390935260409182016000908120918c1681529252902054906133d4565b60006110b882612362565b6012546001600160a01b03163314611877576040805162461bcd60e51b815260206004820152601260248201527137b7363c9030b9b9b2ba1036b0b730b3b2b960711b604482015290519081900360640190fd5b61188182826133f9565b5050565b600c54600160b01b900460ff16806118a75750600c54600160a81b900460ff16155b156117bf576118b4613240565b6001600160a01b038116611904576040805162461bcd60e51b81526020600482015260126024820152713d32b9379030b9b9b2ba1036b0b730b3b2b960711b604482015290519081900360640190fd5b6012546001600160a01b031615611962576040805162461bcd60e51b815260206004820152601c60248201527f63616e6e6f74207265706c616365206173736574206d616e6167657200000000604482015290519081900360640190fd5b601280546001600160a01b0319166001600160a01b03831617905561143d565b600b546000906001600160a01b031633146119af5760405162461bcd60e51b81526004016112b090614a98565b600a5482106119d05760405162461bcd60e51b81526004016112b090614ca2565b6110b86009836134b9565b60606119e5612f36565b6001600160a01b03166349e3c7e584846040518363ffffffff1660e01b8152600401611a12929190614680565b60006040518083038186803b158015611a2a57600080fd5b505afa158015611a3e573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526111be91908101906144c7565b6011546001600160a01b031681565b60006111be83836134ed565b600c54600090600160a81b900460ff16611aa657600c546001600160a01b03166111d1565b60076001609c1b016001600160a01b031663732524946040518163ffffffff1660e01b815260040160206040518083038186803b158015611ae657600080fd5b505afa158015611afa573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111d191906143d9565b6000611b28612f0a565b6001600160a01b0316630f8b8af733846040518363ffffffff1660e01b8152600401611b559291906145cd565b602060405180830381600087803b158015611b6f57600080fd5b505af11580156114a1573d6000803e3d6000fd5b604051630debfda360e41b815260076001609c1b019063debfda3090611bad903390600401614590565b60206040518083038186803b158015611bc557600080fd5b505afa158015611bd9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bfd91906144f9565b611c195760405162461bcd60e51b81526004016112b090614dc5565b6001600160e01b031981166000908152600d602052604090208054611c505760405162461bcd60e51b81526004016112b090614dec565b8054421015611c715760405162461bcd60e51b81526004016112b090614b44565b6000816001018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015611d0b5780601f10611ce057610100808354040283529160200191611d0b565b820191906000526020600020905b815481529060010190602001808311611cee57829003601f168201915b505050506001600160e01b031985166000908152600d602052604081208181559293509050611d3d6001830182614290565b5050600c805460ff60b01b1916600160b01b1790556040516000903090611d65908490614574565b6000604051808303816000865af19150503d8060008114611da2576040519150601f19603f3d011682016040523d82523d6000602084013e611da7565b606091505b5050600c805460ff60b01b191690556040519091507fa7326b57fc9cfe267aaea5e7f0b01757154d265620a0585819416ee9ddd2c43890611deb90869042906146a2565b60405180910390a1611dfc8161351e565b50505050565b60076001609c1b0181565b611e1561353b565b6001600160e01b031981166000908152600d6020526040902054611e4b5760405162461bcd60e51b81526004016112b090614dec565b7f7735b2391c38a81419c513e30ca578db7158eadd7101511b23e221c654d19cf88142604051611e7c9291906146a2565b60405180910390a16001600160e01b031981166000908152600d6020526040812081815590611eae6001830182614290565b505050565b6001600160a01b031660009081526020819052604090205490565b600d602090815260009182526040918290208054600180830180548651600293821615610100026000190190911692909204601f810186900486028301860190965285825291949293909290830182828015611f6b5780601f10611f4057610100808354040283529160200191611f6b565b820191906000526020600020905b815481529060010190602001808311611f4e57829003601f168201915b5050505050905082565b600c54600160b01b900460ff1680611f975750600c54600160a81b900460ff16155b156117bf57611fa4613240565b6001600160a01b0381161561216e57306001600160a01b0316816001600160a01b031663653718836040518163ffffffff1660e01b815260040160206040518083038186803b158015611ff657600080fd5b505afa15801561200a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061202e91906143d9565b6001600160a01b0316146120545760405162461bcd60e51b81526004016112b090614e91565b601154600160a01b900460ff1615806120d95750806001600160a01b031663aa94d3f26040518163ffffffff1660e01b815260040160206040518083038186803b1580156120a157600080fd5b505afa1580156120b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120d991906144f9565b6120f55760405162461bcd60e51b81526004016112b090614a18565b806001600160a01b03166313de97f561210c613275565b6040518263ffffffff1660e01b81526004016121289190614ed3565b600060405180830381600087803b15801561214257600080fd5b505af1158015612156573d6000803e3d6000fd5b50506011805460ff60a01b1916600160a01b17905550505b600f546040517fbec98a6c0f609cda6b9f23b95824ba6ac733cb57edd17d344f2f279684400739916121ae916001916001600160a01b0316908590614702565b60405180910390a1600f80546001600160a01b0319166001600160a01b03831617905561143d565b6060806000806121e4612f36565b6001600160a01b0316637de5b8ed866040518263ffffffff1660e01b815260040161220f9190614590565b60006040518083038186803b15801561222757600080fd5b505afa15801561223b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261226391908101906143f5565b93509350935093509193509193565b600c54600160b01b900460ff16806122945750600c54600160a81b900460ff16155b156117bf576122a1613240565b601180546001600160a01b0319166001600160a01b03831617905561143d565b60006122cb612f36565b6001600160a01b03166331503927846122e48686611a75565b856040518463ffffffff1660e01b815260040161116e9392919061465f565b6010546001600160a01b031690565b600061231c612f36565b6001600160a01b03166392bfe6d884846040518363ffffffff1660e01b815260040161116e9291906145f1565b6012546001600160a01b031681565b60606111d1613573565b60006110b8826135d4565b600e546001600160a01b031690565b600b546001600160a01b031681565b600c54600160b01b900460ff16806123ad5750600c54600160a81b900460ff16155b156117bf576123ba613240565b306001600160a01b0316816001600160a01b031663653718836040518163ffffffff1660e01b815260040160206040518083038186803b1580156123fd57600080fd5b505afa158015612411573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061243591906143d9565b6001600160a01b03161461245b5760405162461bcd60e51b81526004016112b090614b7b565b6010546040517fbec98a6c0f609cda6b9f23b95824ba6ac733cb57edd17d344f2f2796844007399161249b916002916001600160a01b0316908590614702565b60405180910390a1601080546001600160a01b0319166001600160a01b03831617905561143d565b600c54600160a01b900460ff16156124ed5760405162461bcd60e51b81526004016112b090614d29565b600c8054600160a01b60ff60a01b19909116176001600160a01b0319166001600160a01b0383161790556040517f9789733827840833afc031fb2ef9ab6894271f77bad2085687cf4ae5c7bee4db90612547908390614590565b60405180910390a150565b6012546001600160a01b031633146125a6576040805162461bcd60e51b815260206004820152601260248201527137b7363c9030b9b9b2ba1036b0b730b3b2b960711b604482015290519081900360640190fd5b6118818282613604565b601254600160a01b90046001600160401b031681565b60006111ea6125d3612ff8565b846115f885604051806060016040528060258152602001614fce60259139600160006125fd612ff8565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919061320b565b60006111ea61263b612ff8565b84846130f6565b61264a612f0a565b6001600160a01b03166305109ecf3361266233611eb3565b6040518363ffffffff1660e01b815260040161267f9291906145f1565b600060405180830381600087803b15801561269957600080fd5b505af1158015611dfc573d6000803e3d6000fd5b600f54600e546001600160a01b039182169116811561273457816001600160a01b031663c7c62fab33866126e13388611a75565b876040518563ffffffff1660e01b815260040161270194939291906145a4565b600060405180830381600087803b15801561271b57600080fd5b505af115801561272f573d6000803e3d6000fd5b505050505b816001600160a01b0316816001600160a01b03161415801561275e57506001600160a01b03811615155b15611dfc57806001600160a01b031663c7c62fab338661277e3388611a75565b876040518563ffffffff1660e01b815260040161279e94939291906145a4565b600060405180830381600087803b1580156127b857600080fd5b505af19250505080156127c9575060015b611dfc57611dfc565b60006127dc612f36565b6001600160a01b0316639dc6b9f284846127f587611eb3565b6040518463ffffffff1660e01b815260040161116e9392919061460a565b601154600160a01b900460ff1681565b6013805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561154b5780601f106115205761010080835404028352916020019161154b565b60006110b8826136da565b612891612f0a565b6001600160a01b031663404d9e8233846110e133611eb3565b60006128b4612f36565b6001600160a01b0316634a03d556836128cc85611eb3565b6040518363ffffffff1660e01b81526004016114759291906145f1565b805182511461290a5760405162461bcd60e51b81526004016112b0906147d8565b6000612914612f0a565b9050600061292133611eb3565b6040516305109ecf60e01b81529091506001600160a01b038316906305109ecf9061295290339085906004016145f1565b600060405180830381600087803b15801561296c57600080fd5b505af1158015612980573d6000803e3d6000fd5b5050505060005b845181101561143857826001600160a01b0316636230001a338784815181106129ac57fe5b6020026020010151858886815181106129c157fe5b60200260200101516040518563ffffffff1660e01b81526004016129e894939291906145a4565b600060405180830381600087803b158015612a0257600080fd5b505af1158015612a16573d6000803e3d6000fd5b5050600190920191506129879050565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b60006111d1613275565b600c54600160a81b900460ff1681565b6000612a75612f36565b6001600160a01b031663e587497e84846040518363ffffffff1660e01b8152600401612aa29291906145f1565b602060405180830381600087803b158015612abc57600080fd5b505af115801561119a573d6000803e3d6000fd5b6000612ada612f36565b6001600160a01b031663833aca928585612af48887611a75565b866040518563ffffffff1660e01b8152600401612b1494939291906145a4565b60206040518083038186803b158015612b2c57600080fd5b505afa158015612b40573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b649190614519565b949350505050565b606080600080612b7a612f36565b6001600160a01b031663ed475a7987876040518363ffffffff1660e01b8152600401612ba79291906145f1565b60006040518083038186803b158015612bbf57600080fd5b505afa158015612bd3573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052612bfb91908101906143f5565b9299919850965090945092505050565b600b546000906001600160a01b03163314612c385760405162461bcd60e51b81526004016112b090614a98565b600a546111be9060069085908590613778565b612c5361353b565b600c54600160a81b900460ff1615612c7d5760405162461bcd60e51b81526004016112b090614934565b600c8054600161ff0160a01b031916600160a81b1790556040517f83af113638b5422f9e977cebc0aaf0eaf2188eb9a8baae7f9d46c42b33a1560c90612ccb9060076001609c1b0190614590565b60405180910390a1565b60006111d1611553565b600b546000906001600160a01b03163314612d0c5760405162461bcd60e51b81526004016112b090614a98565b600a546110b89060079084906137be565b6000612d27612f36565b6001600160a01b031663f6837767836040518263ffffffff1660e01b81526004016114759190614590565b600c54600160b01b900460ff1680612d745750600c54600160a81b900460ff16155b156117bf57612d81613240565b612d8a816138ab565b600e546001600160a01b031615612dfe57600e5460405163f6a494af60e01b81526001600160a01b039091169063f6a494af90612dcb908490600401614590565b600060405180830381600087803b158015612de557600080fd5b505af1158015612df9573d6000803e3d6000fd5b505050505b600f546001600160a01b031615801590612e295750600e54600f546001600160a01b03908116911614155b15612e9157600f5460405163f6a494af60e01b81526001600160a01b039091169063f6a494af90612e5e908490600401614590565b600060405180830381600087803b158015612e7857600080fd5b505af1158015612e8c573d6000803e3d6000fd5b505050505b6010546001600160a01b031615612f055760105460405163f6a494af60e01b81526001600160a01b039091169063f6a494af90612ed2908490600401614590565b600060405180830381600087803b158015612eec57600080fd5b505af1158015612f00573d6000803e3d6000fd5b505050505b61143d565b600f546000906001600160a01b0316806111d15760405162461bcd60e51b81526004016112b090614ac7565b600e546000906001600160a01b0316806111d15760405162461bcd60e51b81526004016112b090614e23565b60038054604080516020601f6002600019610100600188161502019095169490940493840181900481028201810190925282815260609390929091830182828015612fee5780601f10612fc357610100808354040283529160200191612fee565b820191906000526020600020905b815481529060010190602001808311612fd157829003601f168201915b5050505050905090565b3390565b6001600160a01b0383166130225760405162461bcd60e51b81526004016112b090614c5e565b6001600160a01b0382166130485760405162461bcd60e51b81526004016112b090614807565b6001600160a01b0380841660008181526001602090815260408083209487168084529490915290819020849055517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906130a3908590614ed3565b60405180910390a3505050565b600a548110156130d25760405162461bcd60e51b81526004016112b090614880565b4381106130f15760405162461bcd60e51b81526004016112b090614797565b600a55565b6001600160a01b03831661311c5760405162461bcd60e51b81526004016112b090614c19565b6001600160a01b0382166131425760405162461bcd60e51b81526004016112b090614754565b61314d8383836138cd565b61318a81604051806060016040528060268152602001614f80602691396001600160a01b038616600090815260208190526040902054919061320b565b6001600160a01b0380851660009081526020819052604080822093909355908416815220546131b990826133d4565b6001600160a01b0380841660008181526020819052604090819020939093559151908516907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906130a3908590614ed3565b6000818484111561322f5760405162461bcd60e51b81526004016112b09190614721565b505050900390565b60055460ff1690565b600c54600160b01b900460ff161561326d5733301461325b57fe5b600c805460ff60b01b19169055611284565b61128461353b565b600a5490565b61328361353b565b600082359050600060076001609c1b016001600160a01b0316636221a54b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156132cb57600080fd5b505afa1580156132df573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133039190614519565b905060008142019050604051806040016040528082815260200186868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509390945250506001600160e01b031986168152600d602090815260409091208351815583820151805191935061338c9260018501929101906142d4565b509050507fed948300a3694aa01d4a6b258bfd664350193d770c0b51f8387277f6d83ea3b6838287876040516133c594939291906146bc565b60405180910390a15050505050565b6000828201838110156111be5760405162461bcd60e51b81526004016112b090614849565b6001600160a01b03821661341f5760405162461bcd60e51b81526004016112b090614e5a565b61342b600083836138cd565b60025461343890826133d4565b6002556001600160a01b03821660009081526020819052604090205461345e90826133d4565b6001600160a01b0383166000818152602081905260408082209390935591519091907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906134ad908590614ed3565b60405180910390a35050565b600081815260208390526040812054156134e4575060008181526020839052604081205560016111c1565b50600092915050565b600081600a548110156135125760405162461bcd60e51b81526004016112b0906149cb565b612b64600685856139a1565b3d604051818101604052816000823e8215613537578181f35b8181fd5b613543611a81565b6001600160a01b0316336001600160a01b0316146112845760405162461bcd60e51b81526004016112b09061496b565b60048054604080516020601f6002600019610100600188161502019095169490940493840181900481028201810190925282815260609390929091830182828015612fee5780601f10612fc357610100808354040283529160200191612fee565b600081600a548110156135f95760405162461bcd60e51b81526004016112b0906149cb565b6116016007846139cc565b6001600160a01b03821661362a5760405162461bcd60e51b81526004016112b090614bd8565b613636826000836138cd565b61367381604051806060016040528060228152602001614f5e602291396001600160a01b038516600090815260208190526040902054919061320b565b6001600160a01b0383166000908152602081905260409020556002546136999082613af0565b6002556040516000906001600160a01b038416907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906134ad908590614ed3565b600081600a548110156136ff5760405162461bcd60e51b81526004016112b0906149cb565b43831061371e5760405162461bcd60e51b81526004016112b0906148c8565b60008061372e6009600787613b18565b915091508015613770577ffec477a10b4fcdfdf1114eb32b3caf6118b2d76d20e1fcb70007274bb4b616be856040516137679190614ed3565b60405180910390a15b509392505050565b60006001600160a01b038416156137b3576001600160a01b03841660009081526020869052604090206137ac9084846137be565b9050612b64565b506000949350505050565b6000816137cd57506000611601565b6001840154600160401b90046001600160401b0316806137f1576000915050611601565b60018501546001600160401b0316600061381761380e83886133d4565b60018503613b76565b9050815b818110801561384c575060018101600090815260208990526040902054600160c01b90046001600160401b03168610155b156138685760008181526020899052604081205560010161381b565b8281111561389d5761387981613b8c565b60018901805467ffffffffffffffff19166001600160401b03929092169190911790555b919091039695505050505050565b600b80546001600160a01b0319166001600160a01b0392909216919091179055565b601254600160a01b90046001600160401b031615613927576040805162461bcd60e51b8152602060048201526012602482015271198b585cdcd95d081d195c9b5a5b985d195960721b604482015290519081900360640190fd5b6001600160a01b038316158061394557508061394284611eb3565b10155b613996576040805162461bcd60e51b815260206004820152601760248201527f662d61737365742062616c616e636520746f6f206c6f77000000000000000000604482015290519081900360640190fd5b611eae838383613bb5565b6001600160a01b03821660009081526020849052604081206139c381846139cc565b95945050505050565b6001820154600090600160401b90046001600160401b0316806139f35760009150506111c1565b4383101580613a2557506000198101600090815260208590526040902054600160c01b90046001600160401b03168310155b15613a4d57600019016000908152602084905260409020546001600160c01b031690506111c1565b60018401546001600160401b039081166000818152602087905260409020549091600160c01b90910416841015613aa7578015613a9c5760405162461bcd60e51b81526004016112b090614cd9565b6000925050506111c1565b6001850154600090613acd9087908490600160401b90046001600160401b031688613d5b565b6000908152602087905260409020546001600160c01b0316935050505092915050565b600082821115613b125760405162461bcd60e51b81526004016112b0906148fd565b50900390565b60008181526020849052604081205481908015613b3e5760001901915060009050613b6e565b6000613b4a86866139cc565b9050613b578160016133d4565b600086815260208990526040902055925060019150505b935093915050565b6000818310613b8557816111be565b5090919050565b6000600160401b8210613bb15760405162461bcd60e51b81526004016112b090614afe565b5090565b816001600160a01b0316836001600160a01b03161415613be75760405162461bcd60e51b81526004016112b090614d57565b60006001600160a01b038416613bfe576000613c07565b613c0784611eb3565b905060006001600160a01b038416613c20576000613c29565b613c2984611eb3565b600f549091506001600160a01b03168015613ca95760405163756da1b160e11b81526001600160a01b0382169063eadb436290613c729089908990889088908b9060040161462e565b600060405180830381600087803b158015613c8c57600080fd5b505af1158015613ca0573d6000803e3d6000fd5b50505050613cce565b601154600160a01b900460ff16613cce576011805460ff60a01b1916600160a01b1790555b6010546001600160a01b03168015613d475760405163756da1b160e11b81526001600160a01b0382169063eadb436290613d14908a908a90899089908c9060040161462e565b600060405180830381600087803b158015613d2e57600080fd5b505af1158015613d42573d6000803e3d6000fd5b505050505b613d52878787613de5565b50505050505050565b60008381613d6a856001613af0565b90505b81811115613ddb576000613d976002613d916001613d8b86886133d4565b906133d4565b90613e25565b600081815260208a90526040902054909150600160c01b90046001600160401b03168510613dc757809250613dd5565b613dd2816001613af0565b91505b50613d6d565b5095945050505050565b6001600160a01b038316613e0257613dfd8282613e57565b611eae565b6001600160a01b038216613e1a57613dfd8382613eb4565b611eae838383613f63565b6000808211613e465760405162461bcd60e51b81526004016112b090614994565b818381613e4f57fe5b049392505050565b6000613e6782613d8b8543611a75565b9050613e7560068483613f99565b600a54613e89906006908590600290613778565b50613ea2613e9a83613d8b43612362565b600790613fb7565b600a54611dfc906007906002906137be565b6000613efa8260405180604001604052806016815260200175213ab937103a37b7903134b3903337b91037bbb732b960511b815250613ef38643611a75565b919061320b565b9050613f0860068483613f99565b600a54613f1c906006908590600290613778565b50613ea2613e9a836040518060400160405280601d81526020017f4275726e20746f6f2062696720666f7220746f74616c20737570706c79000000815250613ef343612362565b613f706006848484614178565b600a54613f84906006908590600290613778565b50600a54611dfc906006908490600290613778565b6001600160a01b0382166000908152602084905260409020611dfc81835b6001820154600160401b90046001600160401b03168061406e576040518060400160405280613fe584614207565b6001600160c01b03168152602001613ffc43613b8c565b6001600160401b03908116909152600080805260208681526040909120835181549490920151909216600160c01b026001600160c01b039182166001600160c01b0319909416939093171691909117905560018301805467ffffffffffffffff60401b1916600160401b179055611eae565b600019810160009081526020849052604090208054600160c01b90046001600160401b0316438114156140c4576140a484614207565b82546001600160c01b0319166001600160c01b0391909116178255611438565b8043116140cd57fe5b60405180604001604052806140e186614207565b6001600160c01b031681526020016140f843613b8c565b6001600160401b039081169091526000858152602088815260409091208351815494909201518316600160c01b026001600160c01b039283166001600160c01b0319909516949094179091169290921790915560018087018054918601909216600160401b0267ffffffffffffffff60401b199091161790555050505050565b8061418257611dfc565b6001600160a01b0383161580156141a057506001600160a01b038216155b156141a757fe5b6001600160a01b038316156141db5760006141cc826141c6878761422c565b90613af0565b90506141d9858583613f99565b505b6001600160a01b03821615611dfc5760006141fa82613d8b878661422c565b9050611438858483613f99565b6000600160c01b8210613bb15760405162461bcd60e51b81526004016112b090614a61565b6001600160a01b0381166000908152602083905260408120612b64816001810154600090600160401b90046001600160401b03168061426f5760009150506110bb565b6000190160009081526020929092525060409020546001600160c01b031690565b50805460018160011615610100020316600290046000825580601f106142b6575061143d565b601f01602090049060005260206000209081019061143d9190614358565b828054600181600116156101000203166002900490600052602060002090601f01602090048101928261430a5760008555614350565b82601f1061432357805160ff1916838001178555614350565b82800160010185558215614350579182015b82811115614350578251825591602001919060010190614335565b50613bb19291505b5b80821115613bb15760008155600101614359565b600082601f83011261437d578081fd5b8151602061439261438d83614eff565b614edc565b82815281810190858301838502870184018810156143ae578586fd5b855b858110156143cc578151845292840192908401906001016143b0565b5090979650505050505050565b6000602082840312156143ea578081fd5b81516111be81614f48565b6000806000806080858703121561440a578283fd5b84516001600160401b0380821115614420578485fd5b818701915087601f830112614433578485fd5b8151602061444361438d83614eff565b82815281810190858301838502870184018d101561445f57898afd5b8996505b8487101561448a57805161447681614f48565b835260019690960195918301918301614463565b50918a01519198509093505050808211156144a3578485fd5b506144b08782880161436d565b604087015160609097015195989097509350505050565b6000602082840312156144d8578081fd5b81516001600160401b038111156144ed578182fd5b612b648482850161436d565b60006020828403121561450a578081fd5b815180151581146111be578182fd5b60006020828403121561452a578081fd5b5051919050565b6000815180845260208085019450808401835b838110156145695781516001600160a01b031687529582019590820190600101614544565b509495945050505050565b60008251614586818460208701614f1c565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0394851681529290931660208301526040820152606081019190915260800190565b6001600160a01b0383168152604060208201819052600090612b6490830184614531565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03958616815293909416602084015260408301919091526060820152608081019190915260a00190565b6001600160a01b039390931683526020830191909152604082015260600190565b6000604082526146936040830185614531565b90508260208301529392505050565b6001600160e01b0319929092168252602082015260400190565b600063ffffffff60e01b861682528460208301526060604083015282606083015282846080840137818301608090810191909152601f909201601f191601019392505050565b9283526001600160a01b03918216602084015216604082015260600190565b6000602082528251806020840152614740816040850160208701614f1c565b601f01601f19169190910160400192915050565b60208082526023908201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260408201526265737360e81b606082015260800190565b60208082526021908201527f436c65616e757020626c6f636b206d75737420626520696e20746865207061736040820152601d60fa1b606082015260800190565b602080825260159082015274082e4e4c2f240d8cadccee8d040dad2e6dac2e8c6d605b1b604082015260600190565b60208082526022908201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604082015261737360f01b606082015260800190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b60208082526028908201527f436c65616e757020626c6f636b206e756d626572206d757374206e6576657220604082015267646563726561736560c01b606082015260800190565b6020808252818101527f43616e206f6e6c79206265207573656420666f72207061737420626c6f636b73604082015260600190565b6020808252601e908201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604082015260600190565b6020808252601a908201527f616c726561647920696e2070726f64756374696f6e206d6f6465000000000000604082015260600190565b6020808252600f908201526e6f6e6c7920676f7665726e616e636560881b604082015260600190565b6020808252601a908201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604082015260600190565b6020808252602d908201527f436865636b506f696e7461626c653a2072656164696e672066726f6d20636c6560408201526c616e65642d757020626c6f636b60981b606082015260800190565b60208082526029908201527f5650436f6e7472616374206e6f7420636f6e6669677572656420666f722072656040820152681c1b1858d95b595b9d60ba1b606082015260800190565b6020808252601d908201527f76616c756520646f65736e27742066697420696e203139322062697473000000604082015260600190565b60208082526015908201527413db9b1e4818db19585b995c8818dbdb9d1c9858dd605a1b604082015260600190565b6020808252601e908201527f546f6b656e206d697373696e67207772697465205650436f6e74726163740000604082015260600190565b60208082526026908201527f53616665436173743a2076616c756520646f65736e27742066697420696e203660408201526534206269747360d01b606082015260800190565b60208082526019908201527f74696d656c6f636b3a206e6f7420616c6c6f7765642079657400000000000000604082015260600190565b6020808252603d908201527f476f7665726e616e636520766f746520706f77657220636f6e7472616374206460408201527f6f6573206e6f742062656c6f6e6720746f207468697320746f6b656e2e000000606082015260800190565b60208082526021908201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736040820152607360f81b606082015260800190565b60208082526025908201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604082015264647265737360d81b606082015260800190565b60208082526024908201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646040820152637265737360e01b606082015260800190565b6020808252601e908201527f4e6f20636c65616e757020616674657220636c65616e757020626c6f636b0000604082015260600190565b60208082526030908201527f436865636b506f696e74486973746f72793a2072656164696e672066726f6d2060408201526f636c65616e65642d757020626c6f636b60801b606082015260800190565b602080825260149082015273696e697469616c6973656420213d2066616c736560601b604082015260600190565b60208082526017908201527f43616e6e6f74207472616e7366657220746f2073656c66000000000000000000604082015260600190565b6020808252601a908201527f6f6e6c7920636c65616e757020626c6f636b206d616e61676572000000000000604082015260600190565b6020808252600d908201526c37b7363c9032bc32b1baba37b960991b604082015260600190565b6020808252601a908201527f74696d656c6f636b3a20696e76616c69642073656c6563746f72000000000000604082015260600190565b6020808252601d908201527f546f6b656e206d697373696e672072656164205650436f6e7472616374000000604082015260600190565b6020808252601f908201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604082015260600190565b60208082526022908201527f5650436f6e7472616374206e6f74206f776e6564206279207468697320746f6b60408201526132b760f11b606082015260800190565b90815260200190565b6040518181016001600160401b0381118282101715614ef757fe5b604052919050565b60006001600160401b03821115614f1257fe5b5060209081020190565b60005b83811015614f37578181015183820152602001614f1f565b83811115611dfc5750506000910152565b6001600160a01b038116811461143d57600080fdfe45524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220ce7ac70849c0f2c17e85f0ca26d14bcf7c813b48abe9fa8125a7ab578ced959364736f6c63430007060033