Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
- Contract name:
- MntGovernor_Taiko
- Optimization enabled
- true
- Compiler version
- v0.8.17+commit.8df45f5f
- Optimization runs
- 200
- EVM Version
- default
- Verified at
- 2024-05-23T13:48:39.848842Z
contracts/multichain/taiko/MntGovernor_Taiko.sol
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.17; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "../../governance/MntGovernor.sol"; import "./libraries/TaikoContracts.sol"; import "./interfaces/ITaikoL2_L1BlockNumber.sol"; contract MntGovernor_Taiko is MntGovernor { using SafeCast for uint64; /// @dev Returns block number from L1 network. /// Note! Block number from L1 returns with the delay function clock() public view virtual override(GovernorVotesUpgradeable, IGovernorUpgradeable) returns (uint48) { return ITaikoL2_L1BlockNumber(TaikoContracts.TaikoL2).lastSyncedBlock().toUint48(); } }
@openzeppelin/contracts-upgradeable/governance/TimelockControllerUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (governance/TimelockController.sol) pragma solidity ^0.8.0; import "../access/AccessControlUpgradeable.sol"; import "../token/ERC721/IERC721ReceiverUpgradeable.sol"; import "../token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which acts as a timelocked controller. When set as the * owner of an `Ownable` smart contract, it enforces a timelock on all * `onlyOwner` maintenance operations. This gives time for users of the * controlled contract to exit before a potentially dangerous maintenance * operation is applied. * * By default, this contract is self administered, meaning administration tasks * have to go through the timelock process. The proposer (resp executor) role * is in charge of proposing (resp executing) operations. A common use case is * to position this {TimelockController} as the owner of a smart contract, with * a multisig or a DAO as the sole proposer. * * _Available since v3.3._ */ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE"); uint256 internal constant _DONE_TIMESTAMP = uint256(1); mapping(bytes32 => uint256) private _timestamps; uint256 private _minDelay; /** * @dev Emitted when a call is scheduled as part of operation `id`. */ event CallScheduled( bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay ); /** * @dev Emitted when a call is performed as part of operation `id`. */ event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); /** * @dev Emitted when new proposal is scheduled with non-zero salt. */ event CallSalt(bytes32 indexed id, bytes32 salt); /** * @dev Emitted when operation `id` is cancelled. */ event Cancelled(bytes32 indexed id); /** * @dev Emitted when the minimum delay for future operations is modified. */ event MinDelayChange(uint256 oldDuration, uint256 newDuration); /** * @dev Initializes the contract with the following parameters: * * - `minDelay`: initial minimum delay for operations * - `proposers`: accounts to be granted proposer and canceller roles * - `executors`: accounts to be granted executor role * - `admin`: optional account to be granted admin role; disable with zero address * * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment * without being subject to delay, but this role should be subsequently renounced in favor of * administration through timelocked proposals. Previous versions of this contract would assign * this admin to the deployer automatically and should be renounced as well. */ function __TimelockController_init(uint256 minDelay, address[] memory proposers, address[] memory executors, address admin) internal onlyInitializing { __TimelockController_init_unchained(minDelay, proposers, executors, admin); } function __TimelockController_init_unchained(uint256 minDelay, address[] memory proposers, address[] memory executors, address admin) internal onlyInitializing { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE); // self administration _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); // optional admin if (admin != address(0)) { _setupRole(TIMELOCK_ADMIN_ROLE, admin); } // register proposers and cancellers for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_ROLE, proposers[i]); _setupRole(CANCELLER_ROLE, proposers[i]); } // register executors for (uint256 i = 0; i < executors.length; ++i) { _setupRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRoleOrOpenRole(bytes32 role) { if (!hasRole(role, address(0))) { _checkRole(role, _msgSender()); } _; } /** * @dev Contract might receive/hold ETH as part of the maintenance process. */ receive() external payable {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, AccessControlUpgradeable) returns (bool) { return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns whether an id correspond to a registered operation. This * includes both Pending, Ready and Done operations. */ function isOperation(bytes32 id) public view virtual returns (bool) { return getTimestamp(id) > 0; } /** * @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready". */ function isOperationPending(bytes32 id) public view virtual returns (bool) { return getTimestamp(id) > _DONE_TIMESTAMP; } /** * @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending". */ function isOperationReady(bytes32 id) public view virtual returns (bool) { uint256 timestamp = getTimestamp(id); return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; } /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) public view virtual returns (bool) { return getTimestamp(id) == _DONE_TIMESTAMP; } /** * @dev Returns the timestamp at which an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) public view virtual returns (uint256) { return _timestamps[id]; } /** * @dev Returns the minimum delay for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() public view virtual returns (uint256) { return _minDelay; } /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32) { return keccak256(abi.encode(target, value, data, predecessor, salt)); } /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32) { return keccak256(abi.encode(targets, values, payloads, predecessor, salt)); } /** * @dev Schedule an operation containing a single transaction. * * Emits {CallSalt} if salt is nonzero, and {CallScheduled}. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); if (salt != bytes32(0)) { emit CallSalt(id, salt); } } /** * @dev Schedule an operation containing a batch of transactions. * * Emits {CallSalt} if salt is nonzero, and one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == payloads.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay); } if (salt != bytes32(0)) { emit CallSalt(id, salt); } } /** * @dev Schedule an operation that is to become valid after a given delay. */ function _schedule(bytes32 id, uint256 delay) private { require(!isOperation(id), "TimelockController: operation already scheduled"); require(delay >= getMinDelay(), "TimelockController: insufficient delay"); _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'canceller' role. */ function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) { require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); delete _timestamps[id]; emit Cancelled(id); } /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, // thus any modifications to the operation during reentrancy should be caught. // slither-disable-next-line reentrancy-eth function execute( address target, uint256 value, bytes calldata payload, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { bytes32 id = hashOperation(target, value, payload, predecessor, salt); _beforeCall(id, predecessor); _execute(target, value, payload); emit CallExecuted(id, 0, target, value, payload); _afterCall(id); } /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, // thus any modifications to the operation during reentrancy should be caught. // slither-disable-next-line reentrancy-eth function executeBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == payloads.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt); _beforeCall(id, predecessor); for (uint256 i = 0; i < targets.length; ++i) { address target = targets[i]; uint256 value = values[i]; bytes calldata payload = payloads[i]; _execute(target, value, payload); emit CallExecuted(id, i, target, value, payload); } _afterCall(id); } /** * @dev Execute an operation's call. */ function _execute(address target, uint256 value, bytes calldata data) internal virtual { (bool success, ) = target.call{value: value}(data); require(success, "TimelockController: underlying transaction reverted"); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 id, bytes32 predecessor) private view { require(isOperationReady(id), "TimelockController: operation is not ready"); require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency"); } /** * @dev Checks after execution of an operation's calls. */ function _afterCall(bytes32 id) private { require(isOperationReady(id), "TimelockController: operation is not ready"); _timestamps[id] = _DONE_TIMESTAMP; } /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external virtual { require(msg.sender == address(this), "TimelockController: caller must be timelock"); emit MinDelayChange(_minDelay, newDelay); _minDelay = newDelay; } /** * @dev See {IERC721Receiver-onERC721Received}. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155Received}. */ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155BatchReceived}. */ function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[48] private __gap; }
@openzeppelin/contracts-upgradeable/governance/extensions/GovernorVotesQuorumFractionUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorVotesQuorumFraction.sol) pragma solidity ^0.8.0; import "./GovernorVotesUpgradeable.sol"; import "../../utils/CheckpointsUpgradeable.sol"; import "../../utils/math/SafeCastUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token and a quorum expressed as a * fraction of the total supply. * * _Available since v4.3._ */ abstract contract GovernorVotesQuorumFractionUpgradeable is Initializable, GovernorVotesUpgradeable { using CheckpointsUpgradeable for CheckpointsUpgradeable.Trace224; uint256 private _quorumNumerator; // DEPRECATED in favor of _quorumNumeratorHistory /// @custom:oz-retyped-from Checkpoints.History CheckpointsUpgradeable.Trace224 private _quorumNumeratorHistory; event QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator); /** * @dev Initialize quorum as a fraction of the token's total supply. * * The fraction is specified as `numerator / denominator`. By default the denominator is 100, so quorum is * specified as a percent: a numerator of 10 corresponds to quorum being 10% of total supply. The denominator can be * customized by overriding {quorumDenominator}. */ function __GovernorVotesQuorumFraction_init(uint256 quorumNumeratorValue) internal onlyInitializing { __GovernorVotesQuorumFraction_init_unchained(quorumNumeratorValue); } function __GovernorVotesQuorumFraction_init_unchained(uint256 quorumNumeratorValue) internal onlyInitializing { _updateQuorumNumerator(quorumNumeratorValue); } /** * @dev Returns the current quorum numerator. See {quorumDenominator}. */ function quorumNumerator() public view virtual returns (uint256) { return _quorumNumeratorHistory._checkpoints.length == 0 ? _quorumNumerator : _quorumNumeratorHistory.latest(); } /** * @dev Returns the quorum numerator at a specific timepoint. See {quorumDenominator}. */ function quorumNumerator(uint256 timepoint) public view virtual returns (uint256) { // If history is empty, fallback to old storage uint256 length = _quorumNumeratorHistory._checkpoints.length; if (length == 0) { return _quorumNumerator; } // Optimistic search, check the latest checkpoint CheckpointsUpgradeable.Checkpoint224 memory latest = _quorumNumeratorHistory._checkpoints[length - 1]; if (latest._key <= timepoint) { return latest._value; } // Otherwise, do the binary search return _quorumNumeratorHistory.upperLookupRecent(SafeCastUpgradeable.toUint32(timepoint)); } /** * @dev Returns the quorum denominator. Defaults to 100, but may be overridden. */ function quorumDenominator() public view virtual returns (uint256) { return 100; } /** * @dev Returns the quorum for a timepoint, in terms of number of votes: `supply * numerator / denominator`. */ function quorum(uint256 timepoint) public view virtual override returns (uint256) { return (token.getPastTotalSupply(timepoint) * quorumNumerator(timepoint)) / quorumDenominator(); } /** * @dev Changes the quorum numerator. * * Emits a {QuorumNumeratorUpdated} event. * * Requirements: * * - Must be called through a governance proposal. * - New numerator must be smaller or equal to the denominator. */ function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance { _updateQuorumNumerator(newQuorumNumerator); } /** * @dev Changes the quorum numerator. * * Emits a {QuorumNumeratorUpdated} event. * * Requirements: * * - New numerator must be smaller or equal to the denominator. */ function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual { require( newQuorumNumerator <= quorumDenominator(), "GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator" ); uint256 oldQuorumNumerator = quorumNumerator(); // Make sure we keep track of the original numerator in contracts upgraded from a version without checkpoints. if (oldQuorumNumerator != 0 && _quorumNumeratorHistory._checkpoints.length == 0) { _quorumNumeratorHistory._checkpoints.push( CheckpointsUpgradeable.Checkpoint224({_key: 0, _value: SafeCastUpgradeable.toUint224(oldQuorumNumerator)}) ); } // Set new quorum for future proposals _quorumNumeratorHistory.push(SafeCastUpgradeable.toUint32(clock()), SafeCastUpgradeable.toUint224(newQuorumNumerator)); emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[48] private __gap; }
@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1, "Math: mulDiv overflow"); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); } } }
contracts/interfaces/IVesting.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/access/IAccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IBuyback.sol"; /** * @title Vesting contract provides unlocking of tokens on a schedule. It uses the *graded vesting* way, * which unlocks a specific amount of balance every period of time, until all balance unlocked. * * Vesting Schedule. * * The schedule of a vesting is described by data structure `VestingSchedule`: starting from the start timestamp * throughout the duration, the entire amount of totalAmount tokens will be unlocked. */ interface IVesting is IAccessControl { /** * @notice An event that's emitted when a new vesting schedule for a account is created. */ event VestingScheduleAdded(address target, VestingSchedule schedule); /** * @notice An event that's emitted when a vesting schedule revoked. */ event VestingScheduleRevoked(address target, uint256 unreleased, uint256 locked); /** * @notice An event that's emitted when the account Withdrawn the released tokens. */ event Withdrawn(address target, uint256 withdrawn); /** * @notice Emitted when an account is added to the delay list */ event AddedToDelayList(address account); /** * @notice Emitted when an account is removed from the delay list */ event RemovedFromDelayList(address account); /** * @notice The structure is used in the contract constructor for create vesting schedules * during contract deploying. * @param totalAmount the number of tokens to be vested during the vesting duration. * @param target the address that will receive tokens according to schedule parameters. * @param start offset in minutes at which vesting starts. Zero will vesting immediately. * @param duration duration in minutes of the period in which the tokens will vest. * @param revocable whether the vesting is revocable or not. */ struct ScheduleData { uint256 totalAmount; address target; uint32 start; uint32 duration; bool revocable; } /** * @notice Vesting schedules of an account. * @param totalAmount the number of tokens to be vested during the vesting duration. * @param released the amount of the token released. It means that the account has called withdraw() and received * @param start the timestamp in minutes at which vesting starts. Must not be equal to zero, as it is used to * check for the existence of a vesting schedule. * @param duration duration in minutes of the period in which the tokens will vest. * `released amount` of tokens to his address. * @param revocable whether the vesting is revocable or not. */ struct VestingSchedule { uint256 totalAmount; uint256 released; uint32 created; uint32 start; uint32 duration; bool revocable; } /// @notice get keccak-256 hash of GATEKEEPER role function GATEKEEPER() external view returns (bytes32); /// @notice get keccak-256 hash of TOKEN_PROVIDER role function TOKEN_PROVIDER() external view returns (bytes32); /** * @notice get vesting schedule of an account. */ function schedules(address) external view returns ( uint256 totalAmount, uint256 released, uint32 created, uint32 start, uint32 duration, bool revocable ); /** * @notice Gets the amount of MNT that was transferred to Vesting contract * and can be transferred to other accounts via vesting process. * Transferring rewards from Vesting via withdraw method will decrease this amount. */ function allocation() external view returns (uint256); /** * @notice Gets the amount of allocated MNT tokens that are not used in any vesting schedule yet. * Creation of new vesting schedules will decrease this amount. */ function freeAllocation() external view returns (uint256); /** * @notice get Whether or not the account is in the delay list */ function delayList(address) external view returns (bool); /** * @notice Withdraw the specified number of tokens. For a successful transaction, the requirement * `amount_ > 0 && amount_ <= unreleased` must be met. * If `amount_ == MaxUint256` withdraw all unreleased tokens. * @param amount_ The number of tokens to withdraw. */ function withdraw(uint256 amount_) external; /** * @notice Increases vesting schedule allocation and transfers MNT into Vesting. * @dev RESTRICTION: TOKEN_PROVIDER only */ function refill(uint256 amount) external; /** * @notice Transfers MNT that were added to the contract without calling the refill and are unallocated. * @dev RESTRICTION: Admin only */ function sweep(address recipient, uint256 amount) external; /** * @notice Allows the admin to create a new vesting schedules. * @param schedulesData an array of vesting schedules that will be created. * @dev RESTRICTION: Admin only. */ function createVestingScheduleBatch(ScheduleData[] memory schedulesData) external; /** * @notice Allows the admin to revoke the vesting schedule. Tokens already vested * transfer to the account, the rest are returned to the vesting contract. * Accounts that are in delay list have their withdraw blocked so they would not receive anything. * @param target_ the address from which the vesting schedule is revoked. * @dev RESTRICTION: Gatekeeper only. */ function revokeVestingSchedule(address target_) external; /** * @notice Calculates the end of the vesting. * @param who_ account address for which the parameter is returned. * @return the end of the vesting. */ function endOfVesting(address who_) external view returns (uint256); /** * @notice Calculates locked amount for a given `time`. * @param who_ account address for which the parameter is returned. * @return locked amount for a given `time`. */ function lockedAmount(address who_) external view returns (uint256); /** * @notice Calculates the amount that has already vested. * @param who_ account address for which the parameter is returned. * @return the amount that has already vested. */ function vestedAmount(address who_) external view returns (uint256); /** * @notice Calculates the amount that has already vested but hasn't been released yet. * @param who_ account address for which the parameter is returned. * @return the amount that has already vested but hasn't been released yet. */ function releasableAmount(address who_) external view returns (uint256); /** * @notice Gets the amount that has already vested but hasn't been released yet if account * schedule had no starting delay (cliff). */ function getReleasableWithoutCliff(address account) external view returns (uint256); /** * @notice Add an account with revocable schedule to the delay list * @param who_ The account that is being added to the delay list * @dev RESTRICTION: Gatekeeper only. */ function addToDelayList(address who_) external; /** * @notice Remove an account from the delay list * @param who_ The account that is being removed from the delay list * @dev RESTRICTION: Gatekeeper only. */ function removeFromDelayList(address who_) external; }
@openzeppelin/contracts-upgradeable/utils/CheckpointsUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Checkpoints.sol) // This file was procedurally generated from scripts/generate/templates/Checkpoints.js. pragma solidity ^0.8.0; import "./math/MathUpgradeable.sol"; import "./math/SafeCastUpgradeable.sol"; /** * @dev This library defines the `History` struct, for checkpointing values as they change at different points in * time, and later looking up past values by block number. See {Votes} as an example. * * To create a history of checkpoints define a variable type `Checkpoints.History` in your contract, and store a new * checkpoint for the current transaction block using the {push} function. * * _Available since v4.5._ */ library CheckpointsUpgradeable { struct History { Checkpoint[] _checkpoints; } struct Checkpoint { uint32 _blockNumber; uint224 _value; } /** * @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one * before it is returned, or zero otherwise. Because the number returned corresponds to that at the end of the * block, the requested block number must be in the past, excluding the current block. */ function getAtBlock(History storage self, uint256 blockNumber) internal view returns (uint256) { require(blockNumber < block.number, "Checkpoints: block not yet mined"); uint32 key = SafeCastUpgradeable.toUint32(blockNumber); uint256 len = self._checkpoints.length; uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one * before it is returned, or zero otherwise. Similar to {upperLookup} but optimized for the case when the searched * checkpoint is probably "recent", defined as being among the last sqrt(N) checkpoints where N is the number of * checkpoints. */ function getAtProbablyRecentBlock(History storage self, uint256 blockNumber) internal view returns (uint256) { require(blockNumber < block.number, "Checkpoints: block not yet mined"); uint32 key = SafeCastUpgradeable.toUint32(blockNumber); uint256 len = self._checkpoints.length; uint256 low = 0; uint256 high = len; if (len > 5) { uint256 mid = len - MathUpgradeable.sqrt(len); if (key < _unsafeAccess(self._checkpoints, mid)._blockNumber) { high = mid; } else { low = mid + 1; } } uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Pushes a value onto a History so that it is stored as the checkpoint for the current block. * * Returns previous value and new value. */ function push(History storage self, uint256 value) internal returns (uint256, uint256) { return _insert(self._checkpoints, SafeCastUpgradeable.toUint32(block.number), SafeCastUpgradeable.toUint224(value)); } /** * @dev Pushes a value onto a History, by updating the latest value using binary operation `op`. The new value will * be set to `op(latest, delta)`. * * Returns previous value and new value. */ function push( History storage self, function(uint256, uint256) view returns (uint256) op, uint256 delta ) internal returns (uint256, uint256) { return push(self, op(latest(self), delta)); } /** * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints. */ function latest(History storage self) internal view returns (uint224) { uint256 pos = self._checkpoints.length; return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value * in the most recent checkpoint. */ function latestCheckpoint( History storage self ) internal view returns (bool exists, uint32 _blockNumber, uint224 _value) { uint256 pos = self._checkpoints.length; if (pos == 0) { return (false, 0, 0); } else { Checkpoint memory ckpt = _unsafeAccess(self._checkpoints, pos - 1); return (true, ckpt._blockNumber, ckpt._value); } } /** * @dev Returns the number of checkpoint. */ function length(History storage self) internal view returns (uint256) { return self._checkpoints.length; } /** * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint, * or by updating the last one. */ function _insert(Checkpoint[] storage self, uint32 key, uint224 value) private returns (uint224, uint224) { uint256 pos = self.length; if (pos > 0) { // Copying to memory is important here. Checkpoint memory last = _unsafeAccess(self, pos - 1); // Checkpoint keys must be non-decreasing. require(last._blockNumber <= key, "Checkpoint: decreasing keys"); // Update or push new checkpoint if (last._blockNumber == key) { _unsafeAccess(self, pos - 1)._value = value; } else { self.push(Checkpoint({_blockNumber: key, _value: value})); } return (last._value, value); } else { self.push(Checkpoint({_blockNumber: key, _value: value})); return (0, value); } } /** * @dev Return the index of the last (most recent) checkpoint with key lower or equal than the search key, or `high` if there is none. * `low` and `high` define a section where to do the search, with inclusive `low` and exclusive `high`. * * WARNING: `high` should not be greater than the array's length. */ function _upperBinaryLookup( Checkpoint[] storage self, uint32 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(self, mid)._blockNumber > key) { high = mid; } else { low = mid + 1; } } return high; } /** * @dev Return the index of the first (oldest) checkpoint with key is greater or equal than the search key, or `high` if there is none. * `low` and `high` define a section where to do the search, with inclusive `low` and exclusive `high`. * * WARNING: `high` should not be greater than the array's length. */ function _lowerBinaryLookup( Checkpoint[] storage self, uint32 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(self, mid)._blockNumber < key) { low = mid + 1; } else { high = mid; } } return high; } /** * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. */ function _unsafeAccess(Checkpoint[] storage self, uint256 pos) private pure returns (Checkpoint storage result) { assembly { mstore(0, self.slot) result.slot := add(keccak256(0, 0x20), pos) } } struct Trace224 { Checkpoint224[] _checkpoints; } struct Checkpoint224 { uint32 _key; uint224 _value; } /** * @dev Pushes a (`key`, `value`) pair into a Trace224 so that it is stored as the checkpoint. * * Returns previous value and new value. */ function push(Trace224 storage self, uint32 key, uint224 value) internal returns (uint224, uint224) { return _insert(self._checkpoints, key, value); } /** * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if there is none. */ function lowerLookup(Trace224 storage self, uint32 key) internal view returns (uint224) { uint256 len = self._checkpoints.length; uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len); return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value; } /** * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none. */ function upperLookup(Trace224 storage self, uint32 key) internal view returns (uint224) { uint256 len = self._checkpoints.length; uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none. * * NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high keys). */ function upperLookupRecent(Trace224 storage self, uint32 key) internal view returns (uint224) { uint256 len = self._checkpoints.length; uint256 low = 0; uint256 high = len; if (len > 5) { uint256 mid = len - MathUpgradeable.sqrt(len); if (key < _unsafeAccess(self._checkpoints, mid)._key) { high = mid; } else { low = mid + 1; } } uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints. */ function latest(Trace224 storage self) internal view returns (uint224) { uint256 pos = self._checkpoints.length; return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value * in the most recent checkpoint. */ function latestCheckpoint(Trace224 storage self) internal view returns (bool exists, uint32 _key, uint224 _value) { uint256 pos = self._checkpoints.length; if (pos == 0) { return (false, 0, 0); } else { Checkpoint224 memory ckpt = _unsafeAccess(self._checkpoints, pos - 1); return (true, ckpt._key, ckpt._value); } } /** * @dev Returns the number of checkpoint. */ function length(Trace224 storage self) internal view returns (uint256) { return self._checkpoints.length; } /** * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint, * or by updating the last one. */ function _insert(Checkpoint224[] storage self, uint32 key, uint224 value) private returns (uint224, uint224) { uint256 pos = self.length; if (pos > 0) { // Copying to memory is important here. Checkpoint224 memory last = _unsafeAccess(self, pos - 1); // Checkpoint keys must be non-decreasing. require(last._key <= key, "Checkpoint: decreasing keys"); // Update or push new checkpoint if (last._key == key) { _unsafeAccess(self, pos - 1)._value = value; } else { self.push(Checkpoint224({_key: key, _value: value})); } return (last._value, value); } else { self.push(Checkpoint224({_key: key, _value: value})); return (0, value); } } /** * @dev Return the index of the last (most recent) checkpoint with key lower or equal than the search key, or `high` if there is none. * `low` and `high` define a section where to do the search, with inclusive `low` and exclusive `high`. * * WARNING: `high` should not be greater than the array's length. */ function _upperBinaryLookup( Checkpoint224[] storage self, uint32 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(self, mid)._key > key) { high = mid; } else { low = mid + 1; } } return high; } /** * @dev Return the index of the first (oldest) checkpoint with key is greater or equal than the search key, or `high` if there is none. * `low` and `high` define a section where to do the search, with inclusive `low` and exclusive `high`. * * WARNING: `high` should not be greater than the array's length. */ function _lowerBinaryLookup( Checkpoint224[] storage self, uint32 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(self, mid)._key < key) { low = mid + 1; } else { high = mid; } } return high; } /** * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. */ function _unsafeAccess( Checkpoint224[] storage self, uint256 pos ) private pure returns (Checkpoint224 storage result) { assembly { mstore(0, self.slot) result.slot := add(keccak256(0, 0x20), pos) } } struct Trace160 { Checkpoint160[] _checkpoints; } struct Checkpoint160 { uint96 _key; uint160 _value; } /** * @dev Pushes a (`key`, `value`) pair into a Trace160 so that it is stored as the checkpoint. * * Returns previous value and new value. */ function push(Trace160 storage self, uint96 key, uint160 value) internal returns (uint160, uint160) { return _insert(self._checkpoints, key, value); } /** * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if there is none. */ function lowerLookup(Trace160 storage self, uint96 key) internal view returns (uint160) { uint256 len = self._checkpoints.length; uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len); return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value; } /** * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none. */ function upperLookup(Trace160 storage self, uint96 key) internal view returns (uint160) { uint256 len = self._checkpoints.length; uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none. * * NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high keys). */ function upperLookupRecent(Trace160 storage self, uint96 key) internal view returns (uint160) { uint256 len = self._checkpoints.length; uint256 low = 0; uint256 high = len; if (len > 5) { uint256 mid = len - MathUpgradeable.sqrt(len); if (key < _unsafeAccess(self._checkpoints, mid)._key) { high = mid; } else { low = mid + 1; } } uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints. */ function latest(Trace160 storage self) internal view returns (uint160) { uint256 pos = self._checkpoints.length; return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value * in the most recent checkpoint. */ function latestCheckpoint(Trace160 storage self) internal view returns (bool exists, uint96 _key, uint160 _value) { uint256 pos = self._checkpoints.length; if (pos == 0) { return (false, 0, 0); } else { Checkpoint160 memory ckpt = _unsafeAccess(self._checkpoints, pos - 1); return (true, ckpt._key, ckpt._value); } } /** * @dev Returns the number of checkpoint. */ function length(Trace160 storage self) internal view returns (uint256) { return self._checkpoints.length; } /** * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint, * or by updating the last one. */ function _insert(Checkpoint160[] storage self, uint96 key, uint160 value) private returns (uint160, uint160) { uint256 pos = self.length; if (pos > 0) { // Copying to memory is important here. Checkpoint160 memory last = _unsafeAccess(self, pos - 1); // Checkpoint keys must be non-decreasing. require(last._key <= key, "Checkpoint: decreasing keys"); // Update or push new checkpoint if (last._key == key) { _unsafeAccess(self, pos - 1)._value = value; } else { self.push(Checkpoint160({_key: key, _value: value})); } return (last._value, value); } else { self.push(Checkpoint160({_key: key, _value: value})); return (0, value); } } /** * @dev Return the index of the last (most recent) checkpoint with key lower or equal than the search key, or `high` if there is none. * `low` and `high` define a section where to do the search, with inclusive `low` and exclusive `high`. * * WARNING: `high` should not be greater than the array's length. */ function _upperBinaryLookup( Checkpoint160[] storage self, uint96 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(self, mid)._key > key) { high = mid; } else { low = mid + 1; } } return high; } /** * @dev Return the index of the first (oldest) checkpoint with key is greater or equal than the search key, or `high` if there is none. * `low` and `high` define a section where to do the search, with inclusive `low` and exclusive `high`. * * WARNING: `high` should not be greater than the array's length. */ function _lowerBinaryLookup( Checkpoint160[] storage self, uint96 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (_unsafeAccess(self, mid)._key < key) { low = mid + 1; } else { high = mid; } } return high; } /** * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. */ function _unsafeAccess( Checkpoint160[] storage self, uint256 pos ) private pure returns (Checkpoint160 storage result) { assembly { mstore(0, self.slot) result.slot := add(keccak256(0, 0x20), pos) } } }
contracts/libraries/ErrorCodes.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; library ErrorCodes { // Common string internal constant ADMIN_ONLY = "E101"; string internal constant UNAUTHORIZED = "E102"; string internal constant OPERATION_PAUSED = "E103"; string internal constant WHITELISTED_ONLY = "E104"; string internal constant ADDRESS_IS_NOT_IN_AML_SYSTEM = "E105"; string internal constant ADDRESS_IS_BLACKLISTED = "E106"; // Invalid input string internal constant ADMIN_ADDRESS_CANNOT_BE_ZERO = "E201"; string internal constant INVALID_REDEEM = "E202"; string internal constant REDEEM_TOO_MUCH = "E203"; string internal constant MARKET_NOT_LISTED = "E204"; string internal constant INSUFFICIENT_LIQUIDITY = "E205"; string internal constant INVALID_SENDER = "E206"; string internal constant BORROW_CAP_REACHED = "E207"; string internal constant BALANCE_OWED = "E208"; string internal constant UNRELIABLE_LIQUIDATOR = "E209"; string internal constant INVALID_DESTINATION = "E210"; string internal constant INSUFFICIENT_STAKE = "E211"; string internal constant INVALID_DURATION = "E212"; string internal constant INVALID_PERIOD_RATE = "E213"; string internal constant EB_TIER_LIMIT_REACHED = "E214"; string internal constant LQ_INCORRECT_REPAY_AMOUNT = "E215"; string internal constant LQ_INSUFFICIENT_SEIZE_AMOUNT = "E216"; string internal constant EB_TIER_DOES_NOT_EXIST = "E217"; string internal constant EB_ZERO_TIER_CANNOT_BE_ENABLED = "E218"; string internal constant EB_ALREADY_ACTIVATED_TIER = "E219"; string internal constant EB_END_BLOCK_MUST_BE_LARGER_THAN_CURRENT = "E220"; string internal constant EB_CANNOT_MINT_TOKEN_FOR_ACTIVATED_TIER = "E221"; string internal constant EB_EMISSION_BOOST_IS_NOT_IN_RANGE = "E222"; string internal constant TARGET_ADDRESS_CANNOT_BE_ZERO = "E223"; string internal constant INSUFFICIENT_TOKEN_IN_VESTING_CONTRACT = "E224"; string internal constant VESTING_SCHEDULE_ALREADY_EXISTS = "E225"; string internal constant INSUFFICIENT_TOKENS_TO_CREATE_SCHEDULE = "E226"; string internal constant NO_VESTING_SCHEDULE = "E227"; string internal constant MNT_AMOUNT_IS_ZERO = "E230"; string internal constant INCORRECT_AMOUNT = "E231"; string internal constant MEMBERSHIP_LIMIT = "E232"; string internal constant MEMBER_NOT_EXIST = "E233"; string internal constant MEMBER_ALREADY_ADDED = "E234"; string internal constant MEMBERSHIP_LIMIT_REACHED = "E235"; string internal constant REPORTED_PRICE_SHOULD_BE_GREATER_THAN_ZERO = "E236"; string internal constant MTOKEN_ADDRESS_CANNOT_BE_ZERO = "E237"; string internal constant TOKEN_ADDRESS_CANNOT_BE_ZERO = "E238"; string internal constant REDEEM_TOKENS_OR_REDEEM_AMOUNT_MUST_BE_ZERO = "E239"; string internal constant FL_TOKEN_IS_NOT_UNDERLYING = "E240"; string internal constant FL_AMOUNT_IS_TOO_LARGE = "E241"; string internal constant FL_CALLBACK_FAILED = "E242"; string internal constant EB_MARKET_INDEX_IS_LESS_THAN_USER_INDEX = "E254"; string internal constant LQ_UNSUPPORTED_FULL_REPAY = "E255"; string internal constant LQ_UNSUPPORTED_FULL_SEIZE = "E256"; string internal constant LQ_UNSUPPORTED_MARKET_RECEIVED = "E257"; string internal constant LQ_UNSUCCESSFUL_CALLBACK = "E258"; string internal constant FL_UNAUTHORIZED_CALLBACK = "E270"; string internal constant FL_INCORRECT_TOKEN_OUT_DEVIATION = "E271"; string internal constant FL_SWAP_CALL_FAILS = "E272"; string internal constant FL_INVALID_AMOUNT_TOKEN_IN_SPENT = "E273"; string internal constant FL_INVALID_AMOUNT_TOKEN_OUT_RECEIVED = "E274"; string internal constant FL_EXACT_IN_INCORRECT_ALLOWANCE_AFTER = "E275"; string internal constant FL_RECEIVER_NOT_FOUND = "E276"; // Protocol errors string internal constant INVALID_PRICE = "E301"; string internal constant MARKET_NOT_FRESH = "E302"; string internal constant BORROW_RATE_TOO_HIGH = "E303"; string internal constant INSUFFICIENT_TOKEN_CASH = "E304"; string internal constant INSUFFICIENT_TOKENS_FOR_RELEASE = "E305"; string internal constant INSUFFICIENT_MNT_FOR_GRANT = "E306"; string internal constant TOKEN_TRANSFER_IN_UNDERFLOW = "E307"; string internal constant NOT_PARTICIPATING_IN_BUYBACK = "E308"; string internal constant NOT_ENOUGH_PARTICIPATING_ACCOUNTS = "E309"; string internal constant NOTHING_TO_DISTRIBUTE = "E310"; string internal constant ALREADY_PARTICIPATING_IN_BUYBACK = "E311"; string internal constant MNT_APPROVE_FAILS = "E312"; string internal constant TOO_EARLY_TO_DRIP = "E313"; string internal constant BB_UNSTAKE_TOO_EARLY = "E314"; string internal constant INSUFFICIENT_SHORTFALL = "E315"; string internal constant HEALTHY_FACTOR_NOT_IN_RANGE = "E316"; string internal constant BUYBACK_DRIPS_ALREADY_HAPPENED = "E317"; string internal constant EB_INDEX_SHOULD_BE_GREATER_THAN_INITIAL = "E318"; string internal constant NO_VESTING_SCHEDULES = "E319"; string internal constant INSUFFICIENT_UNRELEASED_TOKENS = "E320"; string internal constant ORACLE_PRICE_EXPIRED = "E321"; string internal constant TOKEN_NOT_FOUND = "E322"; string internal constant RECEIVED_PRICE_HAS_INVALID_ROUND = "E323"; string internal constant FL_PULL_AMOUNT_IS_TOO_LOW = "E324"; string internal constant INSUFFICIENT_TOTAL_PROTOCOL_INTEREST = "E325"; string internal constant BB_ACCOUNT_RECENTLY_VOTED = "E326"; string internal constant PRICE_FEED_ID_NOT_FOUND = "E327"; string internal constant INCORRECT_PRICE_MULTIPLIER = "E328"; string internal constant LL_NEW_ROOT_CANNOT_BE_ZERO = "E329"; string internal constant RH_PAYOUT_FROM_FUTURE = "E330"; string internal constant RH_ACCRUE_WITHOUT_UNLOCK = "E331"; string internal constant RH_LERP_DELTA_IS_GREATER_THAN_PERIOD = "E332"; string internal constant PRICE_FEED_ADDRESS_NOT_FOUND = "E333"; // Invalid input - Admin functions string internal constant ZERO_EXCHANGE_RATE = "E401"; string internal constant SECOND_INITIALIZATION = "E402"; string internal constant MARKET_ALREADY_LISTED = "E403"; string internal constant IDENTICAL_VALUE = "E404"; string internal constant ZERO_ADDRESS = "E405"; string internal constant EC_INVALID_PROVIDER_REPRESENTATIVE = "E406"; string internal constant EC_PROVIDER_CANT_BE_REPRESENTATIVE = "E407"; string internal constant OR_ORACLE_ADDRESS_CANNOT_BE_ZERO = "E408"; string internal constant OR_UNDERLYING_TOKENS_DECIMALS_SHOULD_BE_GREATER_THAN_ZERO = "E409"; string internal constant OR_REPORTER_MULTIPLIER_SHOULD_BE_GREATER_THAN_ZERO = "E410"; string internal constant INVALID_TOKEN = "E411"; string internal constant INVALID_PROTOCOL_INTEREST_FACTOR_MANTISSA = "E412"; string internal constant INVALID_REDUCE_AMOUNT = "E413"; string internal constant LIQUIDATION_FEE_MANTISSA_SHOULD_BE_GREATER_THAN_ZERO = "E414"; string internal constant INVALID_UTILISATION_FACTOR_MANTISSA = "E415"; string internal constant INVALID_MTOKENS_OR_BORROW_CAPS = "E416"; string internal constant FL_PARAM_IS_TOO_LARGE = "E417"; string internal constant MNT_INVALID_NONVOTING_PERIOD = "E418"; string internal constant INPUT_ARRAY_LENGTHS_ARE_NOT_EQUAL = "E419"; string internal constant EC_INVALID_BOOSTS = "E420"; string internal constant EC_ACCOUNT_IS_ALREADY_LIQUIDITY_PROVIDER = "E421"; string internal constant EC_ACCOUNT_HAS_NO_AGREEMENT = "E422"; string internal constant OR_TIMESTAMP_THRESHOLD_SHOULD_BE_GREATER_THAN_ZERO = "E423"; string internal constant OR_UNDERLYING_TOKENS_DECIMALS_TOO_BIG = "E424"; string internal constant OR_REPORTER_MULTIPLIER_TOO_BIG = "E425"; string internal constant SHOULD_HAVE_REVOCABLE_SCHEDULE = "E426"; string internal constant MEMBER_NOT_IN_DELAY_LIST = "E427"; string internal constant DELAY_LIST_LIMIT = "E428"; string internal constant NUMBER_IS_NOT_IN_SCALE = "E429"; string internal constant BB_STRATUM_OF_FIRST_LOYALTY_GROUP_IS_NOT_ZERO = "E430"; string internal constant INPUT_ARRAY_IS_EMPTY = "E431"; string internal constant OR_INCORRECT_PRICE_FEED_ID = "E432"; string internal constant OR_PRICE_AGE_CAN_NOT_BE_ZERO = "E433"; string internal constant OR_INCORRECT_PRICE_FEED_ADDRESS = "E434"; string internal constant OR_INCORRECT_SECONDARY_PRICE_FEED_ADDRESS = "E435"; string internal constant RH_COOLDOWN_START_ALREADY_SET = "E436"; string internal constant RH_INCORRECT_COOLDOWN_START = "E437"; string internal constant RH_COOLDOWN_IS_FINISHED = "E438"; string internal constant RH_INCORRECT_NUMBER_OF_CHARGES = "E439"; string internal constant RH_INCORRECT_CHARGE_SHARE = "E440"; string internal constant RH_COOLDOWN_START_NOT_SET = "E441"; }
@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1, "Math: mulDiv overflow"); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); } } }
@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV // Deprecated in v4.8 } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) { // 32 is the length in bytes of hash, // enforced by the type signature above /// @solidity memory-safe-assembly assembly { mstore(0x00, "\x19Ethereum Signed Message:\n32") mstore(0x1c, hash) message := keccak256(0x00, 0x3c) } } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, "\x19\x01") mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) data := keccak256(ptr, 0x42) } } /** * @dev Returns an Ethereum Signed Data with intended validator, created from a * `validator` and `data` according to the version 0 of EIP-191. * * See {recover}. */ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x00", validator, data)); } }
@openzeppelin/contracts-upgradeable/interfaces/IERC5267Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol) pragma solidity ^0.8.0; interface IERC5267Upgradeable { /** * @dev MAY be emitted to signal that the domain could have changed. */ event EIP712DomainChanged(); /** * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712 * signature. */ function eip712Domain() external view returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ); }
@openzeppelin/contracts-upgradeable/interfaces/IERC6372Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC6372.sol) pragma solidity ^0.8.0; interface IERC6372Upgradeable { /** * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting). */ function clock() external view returns (uint48); /** * @dev Description of the clock */ // solhint-disable-next-line func-name-mixedcase function CLOCK_MODE() external view returns (string memory); }
contracts/interfaces/IWeightAggregator.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; interface IWeightAggregator { /** * @notice Returns MNTs of the account that are used in buyback weight calculation. */ function getAccountFunds(address account) external view returns (uint256); /** * @notice Returns loyalty factor of the specified account. */ function getLoyaltyFactor(address account) external view returns (uint256); /** * @notice Returns Buyback weight for the user */ function getBuybackWeight(address account) external view returns (uint256); /** * @notice Return voting weight for the user */ function getVotingWeight(address account) external view returns (uint256); }
@openzeppelin/contracts-upgradeable/governance/extensions/GovernorTimelockControlUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorTimelockControl.sol) pragma solidity ^0.8.0; import "./IGovernorTimelockUpgradeable.sol"; import "../GovernorUpgradeable.sol"; import "../TimelockControllerUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a * delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The * {Governor} needs the proposer (and ideally the executor) roles for the {Governor} to work properly. * * Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus, * the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be * inaccessible. * * WARNING: Setting up the TimelockController to have additional proposers besides the governor is very risky, as it * grants them powers that they must be trusted or known not to use: 1) {onlyGovernance} functions like {relay} are * available to them through the timelock, and 2) approved governance proposals can be blocked by them, effectively * executing a Denial of Service attack. This risk will be mitigated in a future release. * * _Available since v4.3._ */ abstract contract GovernorTimelockControlUpgradeable is Initializable, IGovernorTimelockUpgradeable, GovernorUpgradeable { TimelockControllerUpgradeable private _timelock; mapping(uint256 => bytes32) private _timelockIds; /** * @dev Emitted when the timelock controller used for proposal execution is modified. */ event TimelockChange(address oldTimelock, address newTimelock); /** * @dev Set the timelock. */ function __GovernorTimelockControl_init(TimelockControllerUpgradeable timelockAddress) internal onlyInitializing { __GovernorTimelockControl_init_unchained(timelockAddress); } function __GovernorTimelockControl_init_unchained(TimelockControllerUpgradeable timelockAddress) internal onlyInitializing { _updateTimelock(timelockAddress); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, GovernorUpgradeable) returns (bool) { return interfaceId == type(IGovernorTimelockUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Overridden version of the {Governor-state} function with added support for the `Queued` state. */ function state(uint256 proposalId) public view virtual override(IGovernorUpgradeable, GovernorUpgradeable) returns (ProposalState) { ProposalState currentState = super.state(proposalId); if (currentState != ProposalState.Succeeded) { return currentState; } // core tracks execution, so we just have to check if successful proposal have been queued. bytes32 queueid = _timelockIds[proposalId]; if (queueid == bytes32(0)) { return currentState; } else if (_timelock.isOperationDone(queueid)) { return ProposalState.Executed; } else if (_timelock.isOperationPending(queueid)) { return ProposalState.Queued; } else { return ProposalState.Canceled; } } /** * @dev Public accessor to check the address of the timelock */ function timelock() public view virtual override returns (address) { return address(_timelock); } /** * @dev Public accessor to check the eta of a queued proposal */ function proposalEta(uint256 proposalId) public view virtual override returns (uint256) { uint256 eta = _timelock.getTimestamp(_timelockIds[proposalId]); return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value } /** * @dev Function to queue a proposal to the timelock. */ function queue( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public virtual override returns (uint256) { uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful"); uint256 delay = _timelock.getMinDelay(); _timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, descriptionHash); _timelock.scheduleBatch(targets, values, calldatas, 0, descriptionHash, delay); emit ProposalQueued(proposalId, block.timestamp + delay); return proposalId; } /** * @dev Overridden execute function that run the already queued proposal through the timelock. */ function _execute( uint256 /* proposalId */, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal virtual override { _timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash); } /** * @dev Overridden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already * been queued. */ // This function can reenter through the external call to the timelock, but we assume the timelock is trusted and // well behaved (according to TimelockController) and this will not happen. // slither-disable-next-line reentrancy-no-eth function _cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal virtual override returns (uint256) { uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash); if (_timelockIds[proposalId] != 0) { _timelock.cancel(_timelockIds[proposalId]); delete _timelockIds[proposalId]; } return proposalId; } /** * @dev Address through which the governor executes action. In this case, the timelock. */ function _executor() internal view virtual override returns (address) { return address(_timelock); } /** * @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates * must be proposed, scheduled, and executed through governance proposals. * * CAUTION: It is not recommended to change the timelock while there are other queued governance proposals. */ function updateTimelock(TimelockControllerUpgradeable newTimelock) external virtual onlyGovernance { _updateTimelock(newTimelock); } function _updateTimelock(TimelockControllerUpgradeable newTimelock) private { emit TimelockChange(address(_timelock), address(newTimelock)); _timelock = newTimelock; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[48] private __gap; }
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
@openzeppelin/contracts-upgradeable/utils/math/SignedMathUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.0; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMathUpgradeable { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/Math.sol"; import "./math/SignedMath.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant _SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toString(int256 value) internal pure returns (string memory) { return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value)))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); } }
@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCastUpgradeable { /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toUint248(uint256 value) internal pure returns (uint248) { require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits"); return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toUint240(uint256 value) internal pure returns (uint240) { require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits"); return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toUint232(uint256 value) internal pure returns (uint232) { require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits"); return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.2._ */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toUint216(uint256 value) internal pure returns (uint216) { require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits"); return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toUint208(uint256 value) internal pure returns (uint208) { require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits"); return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toUint200(uint256 value) internal pure returns (uint200) { require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits"); return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits"); return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toUint184(uint256 value) internal pure returns (uint184) { require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits"); return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toUint176(uint256 value) internal pure returns (uint176) { require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits"); return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toUint168(uint256 value) internal pure returns (uint168) { require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits"); return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toUint160(uint256 value) internal pure returns (uint160) { require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits"); return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toUint152(uint256 value) internal pure returns (uint152) { require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits"); return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toUint144(uint256 value) internal pure returns (uint144) { require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits"); return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toUint136(uint256 value) internal pure returns (uint136) { require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits"); return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v2.5._ */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toUint120(uint256 value) internal pure returns (uint120) { require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits"); return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.2._ */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toUint88(uint256 value) internal pure returns (uint88) { require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits"); return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toUint80(uint256 value) internal pure returns (uint80) { require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits"); return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toUint72(uint256 value) internal pure returns (uint72) { require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits"); return uint72(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 * * _Available since v2.5._ */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toUint56(uint256 value) internal pure returns (uint56) { require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits"); return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toUint48(uint256 value) internal pure returns (uint48) { require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits"); return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toUint40(uint256 value) internal pure returns (uint40) { require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits"); return uint40(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 * * _Available since v2.5._ */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toUint24(uint256 value) internal pure returns (uint24) { require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits"); return uint24(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 * * _Available since v2.5._ */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v2.5._ */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. * * _Available since v3.0._ */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); require(downcasted == value, "SafeCast: value doesn't fit in 248 bits"); } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); require(downcasted == value, "SafeCast: value doesn't fit in 240 bits"); } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); require(downcasted == value, "SafeCast: value doesn't fit in 232 bits"); } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.7._ */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); require(downcasted == value, "SafeCast: value doesn't fit in 224 bits"); } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); require(downcasted == value, "SafeCast: value doesn't fit in 216 bits"); } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); require(downcasted == value, "SafeCast: value doesn't fit in 208 bits"); } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); require(downcasted == value, "SafeCast: value doesn't fit in 200 bits"); } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); require(downcasted == value, "SafeCast: value doesn't fit in 192 bits"); } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); require(downcasted == value, "SafeCast: value doesn't fit in 184 bits"); } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); require(downcasted == value, "SafeCast: value doesn't fit in 176 bits"); } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); require(downcasted == value, "SafeCast: value doesn't fit in 168 bits"); } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); require(downcasted == value, "SafeCast: value doesn't fit in 160 bits"); } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); require(downcasted == value, "SafeCast: value doesn't fit in 152 bits"); } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); require(downcasted == value, "SafeCast: value doesn't fit in 144 bits"); } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); require(downcasted == value, "SafeCast: value doesn't fit in 136 bits"); } /** * @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 downcasted) { downcasted = int128(value); require(downcasted == value, "SafeCast: value doesn't fit in 128 bits"); } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); require(downcasted == value, "SafeCast: value doesn't fit in 120 bits"); } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); require(downcasted == value, "SafeCast: value doesn't fit in 112 bits"); } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); require(downcasted == value, "SafeCast: value doesn't fit in 104 bits"); } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.7._ */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); require(downcasted == value, "SafeCast: value doesn't fit in 96 bits"); } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); require(downcasted == value, "SafeCast: value doesn't fit in 88 bits"); } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); require(downcasted == value, "SafeCast: value doesn't fit in 80 bits"); } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); require(downcasted == value, "SafeCast: value doesn't fit in 72 bits"); } /** * @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 downcasted) { downcasted = int64(value); require(downcasted == value, "SafeCast: value doesn't fit in 64 bits"); } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); require(downcasted == value, "SafeCast: value doesn't fit in 56 bits"); } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); require(downcasted == value, "SafeCast: value doesn't fit in 48 bits"); } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); require(downcasted == value, "SafeCast: value doesn't fit in 40 bits"); } /** * @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 downcasted) { downcasted = int32(value); require(downcasted == value, "SafeCast: value doesn't fit in 32 bits"); } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); require(downcasted == value, "SafeCast: value doesn't fit in 24 bits"); } /** * @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 downcasted) { downcasted = int16(value); require(downcasted == value, "SafeCast: value doesn't fit in 16 bits"); } /** * @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 downcasted) { downcasted = int8(value); require(downcasted == value, "SafeCast: value doesn't fit in 8 bits"); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. * * _Available since v3.0._ */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
contracts/interfaces/IBDSystem.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/access/IAccessControl.sol"; import "./ILinkageLeaf.sol"; interface IBDSystem is IAccessControl, ILinkageLeaf { event AgreementAdded( address indexed liquidityProvider, address indexed representative, uint256 representativeBonus, uint256 liquidityProviderBoost, uint32 startBlock, uint32 endBlock ); event AgreementEnded( address indexed liquidityProvider, address indexed representative, uint256 representativeBonus, uint256 liquidityProviderBoost, uint32 endBlock ); /** * @notice getter function to get liquidity provider agreement */ function providerToAgreement(address) external view returns ( uint256 liquidityProviderBoost, uint256 representativeBonus, uint32 endBlock, address representative ); /** * @notice getter function to get counts * of liquidity providers of the representative */ function representativesProviderCounter(address) external view returns (uint256); /** * @notice Creates a new agreement between liquidity provider and representative * @dev Admin function to create a new agreement * @param liquidityProvider_ address of the liquidity provider * @param representative_ address of the liquidity provider representative. * @param representativeBonus_ percentage of the emission boost for representative * @param liquidityProviderBoost_ percentage of the boost for liquidity provider * @param endBlock_ The number of the first block when agreement will not be in effect * @dev RESTRICTION: Admin only */ function createAgreement( address liquidityProvider_, address representative_, uint256 representativeBonus_, uint256 liquidityProviderBoost_, uint32 endBlock_ ) external; /** * @notice Removes a agreement between liquidity provider and representative * @dev Admin function to remove a agreement * @param liquidityProvider_ address of the liquidity provider * @param representative_ address of the representative. * @dev RESTRICTION: Admin only */ function removeAgreement(address liquidityProvider_, address representative_) external; /** * @notice checks if `account_` is liquidity provider. * @dev account_ is liquidity provider if he has agreement. * @param account_ address to check * @return `true` if `account_` is liquidity provider, otherwise returns false */ function isAccountLiquidityProvider(address account_) external view returns (bool); /** * @notice checks if `account_` is business development representative. * @dev account_ is business development representative if he has liquidity providers. * @param account_ address to check * @return `true` if `account_` is business development representative, otherwise returns false */ function isAccountRepresentative(address account_) external view returns (bool); /** * @notice checks if agreement is expired * @dev reverts if the `account_` is not a valid liquidity provider * @param account_ address of the liquidity provider * @return `true` if agreement is expired, otherwise returns false */ function isAgreementExpired(address account_) external view returns (bool); }
contracts/interfaces/ISupervisor.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/access/IAccessControl.sol"; import "./IMToken.sol"; import "./IBuyback.sol"; import "./IRewardsHub.sol"; import "./ILinkageLeaf.sol"; import "./IWhitelist.sol"; /** * @title Minterest Supervisor Contract * @author Minterest */ interface ISupervisor is IAccessControl, ILinkageLeaf { /** * @notice Emitted when an admin supports a market */ event MarketListed(IMToken mToken); /** * @notice Emitted when an account enable a market */ event MarketEnabledAsCollateral(IMToken mToken, address account); /** * @notice Emitted when an account disable a market */ event MarketDisabledAsCollateral(IMToken mToken, address account); /** * @notice Emitted when a utilisation factor is changed by admin */ event NewUtilisationFactor( IMToken mToken, uint256 oldUtilisationFactorMantissa, uint256 newUtilisationFactorMantissa ); /** * @notice Emitted when liquidation fee is changed by admin */ event NewLiquidationFee(IMToken marketAddress, uint256 oldLiquidationFee, uint256 newLiquidationFee); /** * @notice Emitted when borrow cap for a mToken is changed */ event NewBorrowCap(IMToken indexed mToken, uint256 newBorrowCap); /** * @notice Per-account mapping of "assets you are in" */ function accountAssets(address, uint256) external view returns (IMToken); /** * @notice Collection of states of supported markets * @dev Types containing (nested) mappings could not be parameters or return of external methods */ function markets(IMToken) external view returns ( bool isListed, uint256 utilisationFactorMantissa, uint256 liquidationFeeMantissa ); /** * @notice get A list of all markets */ function allMarkets(uint256) external view returns (IMToken); /** * @notice get Borrow caps enforced by beforeBorrow for each mToken address. */ function borrowCaps(IMToken) external view returns (uint256); /** * @notice get keccak-256 hash of gatekeeper role */ function GATEKEEPER() external view returns (bytes32); /** * @notice get keccak-256 hash of timelock */ function TIMELOCK() external view returns (bytes32); /** * @notice Returns the assets an account has enabled as collateral * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has enabled as collateral */ function getAccountAssets(address account) external view returns (IMToken[] memory); /** * @notice Returns whether the given account is enabled as collateral in the given asset * @param account The address of the account to check * @param mToken The mToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, IMToken mToken) external view returns (bool); /** * @notice Add assets to be included in account liquidity calculation * @param mTokens The list of addresses of the mToken markets to be enabled as collateral */ function enableAsCollateral(IMToken[] memory mTokens) external; /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param mTokenAddress The address of the asset to be removed */ function disableAsCollateral(IMToken mTokenAddress) external; /** * @notice Makes checks if the account should be allowed to lend tokens in the given market * @param mToken The market to verify the lend against * @param lender The account which would get the lent tokens */ function beforeLend(IMToken mToken, address lender) external; /** * @notice Checks if the account should be allowed to redeem tokens in the given market and triggers emission system * @param mToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market * @param isAmlProcess Do we need to check the AML system or not */ function beforeRedeem( IMToken mToken, address redeemer, uint256 redeemTokens, bool isAmlProcess ) external; /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param mToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow */ function beforeBorrow( IMToken mToken, address borrower, uint256 borrowAmount ) external; /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param mToken The market to verify the repay against * @param borrower The account which would borrowed the asset */ function beforeRepayBorrow(IMToken mToken, address borrower) external; /** * @notice Checks if the seizing of assets should be allowed to occur (auto liquidation process) * @param mToken Asset which was used as collateral and will be seized * @param liquidator_ The address of liquidator contract * @param borrower The address of the borrower */ function beforeAutoLiquidationSeize( IMToken mToken, address liquidator_, address borrower ) external; /** * @notice Checks if the sender should be allowed to repay borrow in the given market (auto liquidation process) * @param liquidator_ The address of liquidator contract * @param borrower_ The account which borrowed the asset * @param mToken_ The market to verify the repay against */ function beforeAutoLiquidationRepay( address liquidator_, address borrower_, IMToken mToken_ ) external; /** * @notice Checks if the address is the Liquidation contract * @dev Used in liquidation process * @param liquidator_ Prospective address of the Liquidation contract */ function isLiquidator(address liquidator_) external view; /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param mToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of mTokens to transfer */ function beforeTransfer( IMToken mToken, address src, address dst, uint256 transferTokens ) external; /** * @notice Makes checks before flash loan in MToken * @param mToken The address of the token * receiver - The address of the loan receiver * amount - How much tokens to flash loan * fee - Flash loan fee */ function beforeFlashLoan( IMToken mToken, address, /* receiver */ uint256, /* amount */ uint256 /* fee */ ) external view; /** * @notice Calculate account liquidity in USD related to utilisation factors of underlying assets * @return (USD value above total utilisation requirements of all assets, * USD value below total utilisation requirements of all assets) */ function getAccountLiquidity(address account) external view returns (uint256, uint256); /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, IMToken mTokenModify, uint256 redeemTokens, uint256 borrowAmount ) external returns (uint256, uint256); /** * @notice Get liquidationFeeMantissa and utilisationFactorMantissa for market * @param market Market for which values are obtained * @return (liquidationFeeMantissa, utilisationFactorMantissa) */ function getMarketData(IMToken market) external view returns (uint256, uint256); /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(uint256 redeemAmount, uint256 redeemTokens) external view; /** * @notice Sets the utilisationFactor for a market * @dev Governance function to set per-market utilisationFactor * @param mToken The market to set the factor on * @param newUtilisationFactorMantissa The new utilisation factor, scaled by 1e18 * @dev RESTRICTION: Timelock only. */ function setUtilisationFactor(IMToken mToken, uint256 newUtilisationFactorMantissa) external; /** * @notice Sets the liquidationFee for a market * @dev Governance function to set per-market liquidationFee * @param mToken The market to set the fee on * @param newLiquidationFeeMantissa The new liquidation fee, scaled by 1e18 * @dev RESTRICTION: Timelock only. */ function setLiquidationFee(IMToken mToken, uint256 newLiquidationFeeMantissa) external; /** * @notice Add the market to the markets mapping and set it as listed, also initialize MNT market state. * @dev Admin function to set isListed and add support for the market * @param mToken The address of the market (token) to list * @dev RESTRICTION: Admin only. */ function supportMarket(IMToken mToken) external; /** * @notice Set the given borrow caps for the given mToken markets. * Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or gateKeeper function to set the borrow caps. * A borrow cap of 0 corresponds to unlimited borrowing. * @param mTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. * A value of 0 corresponds to unlimited borrowing. * @dev RESTRICTION: Gatekeeper only. */ function setMarketBorrowCaps(IMToken[] calldata mTokens, uint256[] calldata newBorrowCaps) external; /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() external view returns (IMToken[] memory); /** * @notice Returns true if market is listed in Supervisor */ function isMarketListed(IMToken) external view returns (bool); /** * @notice Check that account is not in the black list and protocol operations are available. * @param account The address of the account to check */ function isNotBlacklisted(address account) external view returns (bool); /** * @notice Check if transfer of MNT is allowed for accounts. * @param from The source account address to check * @param to The destination account address to check */ function isMntTransferAllowed(address from, address to) external view returns (bool); /** * @notice Returns block number */ function getBlockNumber() external view returns (uint256); }
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
contracts/interfaces/ILinkageRoot.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; interface ILinkageRoot { /** * @notice Emitted when new root contract connected to all leafs */ event LinkageRootSwitch(ILinkageRoot newRoot); /** * @notice Emitted when root interconnects its contracts */ event LinkageRootInterconnected(); /** * @notice Connects new root to all leafs contracts * @param newRoot New root contract address */ function switchLinkageRoot(ILinkageRoot newRoot) external; /** * @notice Update root for all leaf contracts * @dev Should include only leaf contracts */ function interconnect() external; }
@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); }
contracts/libraries/ProtocolLinkage.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/StorageSlot.sol"; import "../interfaces/ILinkageLeaf.sol"; import "../interfaces/ILinkageRoot.sol"; import "./ErrorCodes.sol"; abstract contract LinkageRoot is ILinkageRoot { /// @notice Store self address to prevent context changing while delegateCall ILinkageRoot internal immutable _self = this; /// @notice Owner address address public immutable _linkage_owner; constructor(address owner_) { require(owner_ != address(0), ErrorCodes.ADMIN_ADDRESS_CANNOT_BE_ZERO); _linkage_owner = owner_; } /// @inheritdoc ILinkageRoot function switchLinkageRoot(ILinkageRoot newRoot) external { require(msg.sender == _linkage_owner, ErrorCodes.UNAUTHORIZED); emit LinkageRootSwitch(newRoot); Address.functionDelegateCall( address(newRoot), abi.encodePacked(LinkageRoot.interconnect.selector), "LinkageRoot: low-level delegate call failed" ); } /// @inheritdoc ILinkageRoot function interconnect() external { emit LinkageRootInterconnected(); interconnectInternal(); } function interconnectInternal() internal virtual; } abstract contract LinkageLeaf is ILinkageLeaf { /// @inheritdoc ILinkageLeaf function switchLinkageRoot(ILinkageRoot newRoot) public { require(address(newRoot) != address(0), ErrorCodes.LL_NEW_ROOT_CANNOT_BE_ZERO); StorageSlot.AddressSlot storage slot = getRootSlot(); address oldRoot = slot.value; if (oldRoot == address(newRoot)) return; require(oldRoot == address(0) || oldRoot == msg.sender, ErrorCodes.UNAUTHORIZED); slot.value = address(newRoot); emit LinkageRootSwitched(newRoot, LinkageRoot(oldRoot)); } /** * @dev Gets current root contract address */ function getLinkageRootAddress() internal view returns (address) { return getRootSlot().value; } /** * @dev Gets current root contract storage slot */ function getRootSlot() private pure returns (StorageSlot.AddressSlot storage) { // keccak256("minterest.slot.linkageRoot") return StorageSlot.getAddressSlot(0xc34f336ef21a27e6cdbefdb1e201a57e5e6cb9d267e34fc3134d22f9decc8bbf); } }
contracts/interfaces/IMnt.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "./ILinkageLeaf.sol"; interface IMnt is IERC20Upgradeable, IERC165, IAccessControlUpgradeable, ILinkageLeaf { event MaxNonVotingPeriodChanged(uint256 oldPeriod, uint256 newPeriod); event NewGovernor(address governor); event VotesUpdated(address account, uint256 oldVotingWeight, uint256 newVotingWeight); event TotalVotesUpdated(uint256 oldTotalVotes, uint256 newTotalVotes); /** * @notice get governor */ function governor() external view returns (address); /** * @notice returns votingWeight for user */ function votingWeight(address) external view returns (uint256); /** * @notice get total voting weight */ function totalVotingWeight() external view returns (uint256); /** * @notice Updates voting power of the account */ function updateVotingWeight(address account) external; /** * @notice Creates new total voting weight checkpoint * @dev RESTRICTION: Governor only. */ function updateTotalWeightCheckpoint() external; /** * @notice Checks user activity for the last `maxNonVotingPeriod` blocks * @param account_ The address of the account * @return returns true if the user voted or his delegatee voted for the last maxNonVotingPeriod blocks, * otherwise returns false */ function isParticipantActive(address account_) external view returns (bool); /** * @notice Updates last voting timestamp of the account * @dev RESTRICTION: Governor only. */ function updateVoteTimestamp(address account) external; /** * @notice Gets the latest voting timestamp for account. * @dev If the user delegated his votes, then it also checks the timestamp of the last vote of the delegatee * @param account The address of the account * @return latest voting timestamp for account */ function lastActivityTimestamp(address account) external view returns (uint256); /** * @notice set new governor * @dev RESTRICTION: Admin only. */ function setGovernor(address newGovernor) external; /** * @notice Sets the maxNonVotingPeriod * @dev Admin function to set maxNonVotingPeriod * @param newPeriod_ The new maxNonVotingPeriod (in sec). Must be greater than 90 days and lower than 2 years. * @dev RESTRICTION: Admin only. */ function setMaxNonVotingPeriod(uint256 newPeriod_) external; }
@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol) pragma solidity ^0.8.8; import "./ECDSAUpgradeable.sol"; import "../../interfaces/IERC5267Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the * separator from the immutable values, which is cheaper than accessing a cached version in cold storage. * * _Available since v3.4._ * * @custom:storage-size 52 */ abstract contract EIP712Upgradeable is Initializable, IERC5267Upgradeable { bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /// @custom:oz-renamed-from _HASHED_NAME bytes32 private _hashedName; /// @custom:oz-renamed-from _HASHED_VERSION bytes32 private _hashedVersion; string private _name; string private _version; /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal onlyInitializing { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing { _name = name; _version = version; // Reset prior values in storage if upgrading _hashedName = 0; _hashedVersion = 0; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(); } function _buildDomainSeparator() private view returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev See {EIP-5267}. * * _Available since v4.9._ */ function eip712Domain() public view virtual override returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ) { // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized // and the EIP712 domain is not reliable, as it will be missing name and version. require(_hashedName == 0 && _hashedVersion == 0, "EIP712: Uninitialized"); return ( hex"0f", // 01111 _EIP712Name(), _EIP712Version(), block.chainid, address(this), bytes32(0), new uint256[](0) ); } /** * @dev The name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712Name() internal virtual view returns (string memory) { return _name; } /** * @dev The version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712Version() internal virtual view returns (string memory) { return _version; } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead. */ function _EIP712NameHash() internal view returns (bytes32) { string memory name = _EIP712Name(); if (bytes(name).length > 0) { return keccak256(bytes(name)); } else { // If the name is empty, the contract may have been upgraded without initializing the new storage. // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design. bytes32 hashedName = _hashedName; if (hashedName != 0) { return hashedName; } else { return keccak256(""); } } } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead. */ function _EIP712VersionHash() internal view returns (bytes32) { string memory version = _EIP712Version(); if (bytes(version).length > 0) { return keccak256(bytes(version)); } else { // If the version is empty, the contract may have been upgraded without initializing the new storage. // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design. bytes32 hashedVersion = _hashedVersion; if (hashedVersion != 0) { return hashedVersion; } else { return keccak256(""); } } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[48] private __gap; }
@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV // Deprecated in v4.8 } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) { // 32 is the length in bytes of hash, // enforced by the type signature above /// @solidity memory-safe-assembly assembly { mstore(0x00, "\x19Ethereum Signed Message:\n32") mstore(0x1c, hash) message := keccak256(0x00, 0x3c) } } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, "\x19\x01") mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) data := keccak256(ptr, 0x42) } } /** * @dev Returns an Ethereum Signed Data with intended validator, created from a * `validator` and `data` according to the version 0 of EIP-191. * * See {recover}. */ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x00", validator, data)); } }
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Permit.sol) pragma solidity ^0.8.0; import "./IERC20PermitUpgradeable.sol"; import "../ERC20Upgradeable.sol"; import "../../../utils/cryptography/ECDSAUpgradeable.sol"; import "../../../utils/cryptography/EIP712Upgradeable.sol"; import "../../../utils/CountersUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ * * @custom:storage-size 51 */ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping(address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private constant _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`. * However, to ensure consistency with the upgradeable transpiler, we will continue * to reserve a slot. * @custom:oz-renamed-from _PERMIT_TYPEHASH */ // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal onlyInitializing { __EIP712_init_unchained(name, "1"); } function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { CountersUpgradeable.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); }
contracts/interfaces/ILinkageLeaf.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "./ILinkageRoot.sol"; interface ILinkageLeaf { /** * @notice Emitted when root contract address is changed */ event LinkageRootSwitched(ILinkageRoot newRoot, ILinkageRoot oldRoot); /** * @notice Connects new root contract address * @param newRoot New root contract address */ function switchLinkageRoot(ILinkageRoot newRoot) external; }
contracts/InterconnectorLeaf.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "./libraries/ProtocolLinkage.sol"; import "./interfaces/IInterconnectorLeaf.sol"; abstract contract InterconnectorLeaf is IInterconnectorLeaf, LinkageLeaf { function getInterconnector() public view returns (IInterconnector) { return IInterconnector(getLinkageRootAddress()); } }
contracts/interfaces/IRewardsHubLight.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "./IMToken.sol"; import "./ILinkageLeaf.sol"; interface IRewardsHubLight is ILinkageLeaf { event DistributedSupplierMnt(IMToken mToken, address supplier, uint256 mntDelta, uint256 mntSupplyIndex); event DistributedBorrowerMnt(IMToken mToken, address borrower, uint256 mntDelta, uint256 mntBorrowIndex); event EmissionRewardAccrued(address account, uint256 amount); event RepresentativeRewardAccrued(address account, address provider, uint256 amount); event BuybackRewardAccrued(address account, uint256 amount); event Withdraw(address account, uint256 amount); event MntGranted(address recipient, uint256 amount); event MntSupplyEmissionRateUpdated(IMToken mToken, uint256 newSupplyEmissionRate); event MntBorrowEmissionRateUpdated(IMToken mToken, uint256 newBorrowEmissionRate); /** * @notice get keccak-256 hash of gatekeeper */ function GATEKEEPER() external view returns (bytes32); /** * @notice get keccak-256 hash of timelock */ function TIMELOCK() external view returns (bytes32); /** * @notice Gets the rate at which MNT is distributed to the corresponding supply market (per block) */ function mntSupplyEmissionRate(IMToken) external view returns (uint256); /** * @notice Gets the rate at which MNT is distributed to the corresponding borrow market (per block) */ function mntBorrowEmissionRate(IMToken) external view returns (uint256); /** * @notice Gets the MNT market supply state for each market */ function mntSupplyState(IMToken) external view returns (uint224 index, uint32 blockN); /** * @notice Gets the MNT market borrow state for each market */ function mntBorrowState(IMToken) external view returns (uint224 index, uint32 blockN); /** * @notice Gets the MNT supply index and block number for each market */ function mntSupplierState(IMToken, address) external view returns (uint224 index, uint32 blockN); /** * @notice Gets the MNT borrow index and block number for each market */ function mntBorrowerState(IMToken, address) external view returns (uint224 index, uint32 blockN); /** * @notice Gets amount of available balance of an account. */ function totalBalanceOf(address account) external view returns (uint256); /** * @notice Gets amount of MNT that can be withdrawn from an account at this block. */ function availableBalanceOf(address account) external view returns (uint256); /** * @notice Initializes market in RewardsHub. Should be called once from Supervisor.supportMarket * @dev RESTRICTION: Supervisor only */ function initMarket(IMToken mToken) external; /** * @notice Accrues MNT to the market by updating the borrow and supply indexes * @dev This method doesn't update MNT index history in Minterest NFT. * @param market The market whose supply and borrow index to update * @return (MNT supply index, MNT borrow index) */ function updateAndGetMntIndexes(IMToken market) external returns (uint224, uint224); /** * @notice Shorthand function to distribute MNT emissions from supplies of one market. */ function distributeSupplierMnt(IMToken mToken, address account) external; /** * @notice Shorthand function to distribute MNT emissions from borrows of one market. */ function distributeBorrowerMnt(IMToken mToken, address account) external; /** * @notice Updates market indexes and distributes tokens (if any) for holder * @dev Updates indexes and distributes only for those markets where the holder have a * non-zero supply or borrow balance. * @param account The address to distribute MNT for */ function distributeAllMnt(address account) external; /** * @notice Distribute all MNT accrued by the accounts * @param accounts The addresses to distribute MNT for * @param mTokens The list of markets to distribute MNT in * @param borrowers Whether or not to distribute MNT earned by borrowing * @param suppliers Whether or not to distribute MNT earned by supplying */ function distributeMnt( address[] memory accounts, IMToken[] memory mTokens, bool borrowers, bool suppliers ) external; /** * @notice Accrues buyback reward * @dev RESTRICTION: Buyback only */ function accrueBuybackReward(address account, uint256 amount) external; /** * @notice Transfers available part of MNT rewards to the sender. * This will decrease accounts buyback and voting weights. */ function withdraw(uint256 amount) external; /** * @notice Transfers * @dev RESTRICTION: Admin only */ function grant(address recipient, uint256 amount) external; /** * @notice Set MNT borrow and supply emission rates for a single market * @param mToken The market whose MNT emission rate to update * @param newMntSupplyEmissionRate New supply MNT emission rate for market * @param newMntBorrowEmissionRate New borrow MNT emission rate for market * @dev RESTRICTION Timelock only */ function setMntEmissionRates( IMToken mToken, uint256 newMntSupplyEmissionRate, uint256 newMntBorrowEmissionRate ) external; }
contracts/interfaces/IMinterestNFT.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/access/IAccessControl.sol"; import "./ILinkageLeaf.sol"; /** * @title MinterestNFT * @dev Contract module which provides functionality to mint new ERC1155 tokens * Each token connected with image and metadata. The image and metadata saved * on IPFS and this contract stores the CID of the folder where lying metadata. * Also each token belongs one of the Minterest tiers, and give some emission * boost for Minterest distribution system. */ interface IMinterestNFT is IAccessControl, IERC1155, ILinkageLeaf { /** * @notice Emitted when new base URI was installed */ event NewBaseUri(string newBaseUri); /** * @notice get name for Minterst NFT Token */ function name() external view returns (string memory); /** * @notice get symbool for Minterst NFT Token */ function symbol() external view returns (string memory); /** * @notice get keccak-256 hash of GATEKEEPER role */ function GATEKEEPER() external view returns (bytes32); /** * @notice Mint new 1155 standard token * @param account_ The address of the owner of minterestNFT * @param amount_ Instance count for minterestNFT * @param data_ The _data argument MAY be re-purposed for the new context. * @param tier_ tier */ function mint( address account_, uint256 amount_, bytes memory data_, uint256 tier_ ) external; /** * @notice Mint new ERC1155 standard tokens in one transaction * @param account_ The address of the owner of tokens * @param amounts_ Array of instance counts for tokens * @param data_ The _data argument MAY be re-purposed for the new context. * @param tiers_ Array of tiers * @dev RESTRICTION: Gatekeeper only */ function mintBatch( address account_, uint256[] memory amounts_, bytes memory data_, uint256[] memory tiers_ ) external; /** * @notice Transfer token to another account * @param to_ The address of the token receiver * @param id_ token id * @param amount_ Count of tokens * @param data_ The _data argument MAY be re-purposed for the new context. */ function safeTransfer( address to_, uint256 id_, uint256 amount_, bytes memory data_ ) external; /** * @notice Transfer tokens to another account * @param to_ The address of the tokens receiver * @param ids_ Array of token ids * @param amounts_ Array of tokens count * @param data_ The _data argument MAY be re-purposed for the new context. */ function safeBatchTransfer( address to_, uint256[] memory ids_, uint256[] memory amounts_, bytes memory data_ ) external; /** * @notice Set new base URI * @param newBaseUri Base URI * @dev RESTRICTION: Admin only */ function setURI(string memory newBaseUri) external; /** * @notice Override function to return image URL, opensea requirement * @param tokenId_ Id of token to get URL * @return IPFS URI for token id, opensea requirement */ function uri(uint256 tokenId_) external view returns (string memory); /** * @dev Returns the next token ID to be minted * @return the next token ID to be minted */ function nextIdToBeMinted() external view returns (uint256); }
@openzeppelin/contracts-upgradeable/utils/structs/DoubleEndedQueueUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/DoubleEndedQueue.sol) pragma solidity ^0.8.4; import "../math/SafeCastUpgradeable.sol"; /** * @dev A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends of * the sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and * FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes {clear}, given that * the existing queue contents are left in storage. * * The struct is called `Bytes32Deque`. Other types can be cast to and from `bytes32`. This data structure can only be * used in storage, and not in memory. * ```solidity * DoubleEndedQueue.Bytes32Deque queue; * ``` * * _Available since v4.6._ */ library DoubleEndedQueueUpgradeable { /** * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty. */ error Empty(); /** * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds. */ error OutOfBounds(); /** * @dev Indices are signed integers because the queue can grow in any direction. They are 128 bits so begin and end * are packed in a single storage slot for efficient access. Since the items are added one at a time we can safely * assume that these 128-bit indices will not overflow, and use unchecked arithmetic. * * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and * lead to unexpected behavior. * * Indices are in the range [begin, end) which means the first item is at data[begin] and the last item is at * data[end - 1]. */ struct Bytes32Deque { int128 _begin; int128 _end; mapping(int128 => bytes32) _data; } /** * @dev Inserts an item at the end of the queue. */ function pushBack(Bytes32Deque storage deque, bytes32 value) internal { int128 backIndex = deque._end; deque._data[backIndex] = value; unchecked { deque._end = backIndex + 1; } } /** * @dev Removes the item at the end of the queue and returns it. * * Reverts with `Empty` if the queue is empty. */ function popBack(Bytes32Deque storage deque) internal returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 backIndex; unchecked { backIndex = deque._end - 1; } value = deque._data[backIndex]; delete deque._data[backIndex]; deque._end = backIndex; } /** * @dev Inserts an item at the beginning of the queue. */ function pushFront(Bytes32Deque storage deque, bytes32 value) internal { int128 frontIndex; unchecked { frontIndex = deque._begin - 1; } deque._data[frontIndex] = value; deque._begin = frontIndex; } /** * @dev Removes the item at the beginning of the queue and returns it. * * Reverts with `Empty` if the queue is empty. */ function popFront(Bytes32Deque storage deque) internal returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 frontIndex = deque._begin; value = deque._data[frontIndex]; delete deque._data[frontIndex]; unchecked { deque._begin = frontIndex + 1; } } /** * @dev Returns the item at the beginning of the queue. * * Reverts with `Empty` if the queue is empty. */ function front(Bytes32Deque storage deque) internal view returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 frontIndex = deque._begin; return deque._data[frontIndex]; } /** * @dev Returns the item at the end of the queue. * * Reverts with `Empty` if the queue is empty. */ function back(Bytes32Deque storage deque) internal view returns (bytes32 value) { if (empty(deque)) revert Empty(); int128 backIndex; unchecked { backIndex = deque._end - 1; } return deque._data[backIndex]; } /** * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at * `length(deque) - 1`. * * Reverts with `OutOfBounds` if the index is out of bounds. */ function at(Bytes32Deque storage deque, uint256 index) internal view returns (bytes32 value) { // int256(deque._begin) is a safe upcast int128 idx = SafeCastUpgradeable.toInt128(int256(deque._begin) + SafeCastUpgradeable.toInt256(index)); if (idx >= deque._end) revert OutOfBounds(); return deque._data[idx]; } /** * @dev Resets the queue back to being empty. * * NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses * out on potential gas refunds. */ function clear(Bytes32Deque storage deque) internal { deque._begin = 0; deque._end = 0; } /** * @dev Returns the number of items in the queue. */ function length(Bytes32Deque storage deque) internal view returns (uint256) { // The interface preserves the invariant that begin <= end so we assume this will not overflow. // We also assume there are at most int256.max items in the queue. unchecked { return uint256(int256(deque._end) - int256(deque._begin)); } } /** * @dev Returns true if the queue is empty. */ function empty(Bytes32Deque storage deque) internal view returns (bool) { return deque._end <= deque._begin; } }
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized != type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } }
@openzeppelin/contracts/interfaces/IERC3156FlashLender.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashLender.sol) pragma solidity ^0.8.0; import "./IERC3156FlashBorrower.sol"; /** * @dev Interface of the ERC3156 FlashLender, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * _Available since v4.1._ */ interface IERC3156FlashLender { /** * @dev The amount of currency available to be lended. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan(address token) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee(address token, uint256 amount) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); }
@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/MathUpgradeable.sol"; import "./math/SignedMathUpgradeable.sol"; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = MathUpgradeable.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toString(int256 value) internal pure returns (string memory) { return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value)))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, MathUpgradeable.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); } }
@openzeppelin/contracts-upgradeable/governance/extensions/IGovernorTimelockUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (governance/extensions/IGovernorTimelock.sol) pragma solidity ^0.8.0; import "../IGovernorUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Extension of the {IGovernor} for timelock supporting modules. * * _Available since v4.3._ */ abstract contract IGovernorTimelockUpgradeable is Initializable, IGovernorUpgradeable { function __IGovernorTimelock_init() internal onlyInitializing { } function __IGovernorTimelock_init_unchained() internal onlyInitializing { } event ProposalQueued(uint256 proposalId, uint256 eta); function timelock() public view virtual returns (address); function proposalEta(uint256 proposalId) public view virtual returns (uint256); function queue( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public virtual returns (uint256 proposalId); /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
contracts/interfaces/IMToken.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/interfaces/IERC3156FlashLender.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "@openzeppelin/contracts/access/IAccessControl.sol"; import "./IInterestRateModel.sol"; interface IMToken is IAccessControl, IERC20, IERC3156FlashLender, IERC165 { /** * @notice Event emitted when interest is accrued */ event AccrueInterest( uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows, uint256 totalProtocolInterest ); /** * @notice Event emitted when tokens are lended */ event Lend(address lender, uint256 lendAmount, uint256 lendTokens, uint256 newTotalTokenSupply); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens, uint256 newTotalTokenSupply); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when tokens are seized */ event Seize( address borrower, address receiver, uint256 seizeTokens, uint256 accountsTokens, uint256 totalSupply, uint256 seizeUnderlyingAmount ); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is repaid during autoliquidation */ event AutoLiquidationRepayBorrow( address borrower, uint256 repayAmount, uint256 accountBorrowsNew, uint256 totalBorrowsNew, uint256 TotalProtocolInterestNew ); /** * @notice Event emitted when flash loan is executed */ event FlashLoanExecuted(address receiver, uint256 amount, uint256 fee); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(IInterestRateModel oldInterestRateModel, IInterestRateModel newInterestRateModel); /** * @notice Event emitted when the protocol interest factor is changed */ event NewProtocolInterestFactor( uint256 oldProtocolInterestFactorMantissa, uint256 newProtocolInterestFactorMantissa ); /** * @notice Event emitted when the flash loan max share is changed */ event NewFlashLoanMaxShare(uint256 oldMaxShare, uint256 newMaxShare); /** * @notice Event emitted when the flash loan fee is changed */ event NewFlashLoanFee(uint256 oldFee, uint256 newFee); /** * @notice Event emitted when the protocol interest are added */ event ProtocolInterestAdded(address benefactor, uint256 addAmount, uint256 newTotalProtocolInterest); /** * @notice Event emitted when the protocol interest reduced */ event ProtocolInterestReduced(address admin, uint256 reduceAmount, uint256 newTotalProtocolInterest); /** * @notice Value is the Keccak-256 hash of "TIMELOCK" */ function TIMELOCK() external view returns (bytes32); /** * @notice Underlying asset for this MToken */ function underlying() external view returns (IERC20); /** * @notice EIP-20 token name for this token */ function name() external view returns (string memory); /** * @notice EIP-20 token symbol for this token */ function symbol() external view returns (string memory); /** * @notice EIP-20 token decimals for this token */ function decimals() external view returns (uint8); /** * @notice Model which tells what the current interest rate should be */ function interestRateModel() external view returns (IInterestRateModel); /** * @notice Initial exchange rate used when lending the first MTokens (used when totalTokenSupply = 0) */ function initialExchangeRateMantissa() external view returns (uint256); /** * @notice Fraction of interest currently set aside for protocol interest */ function protocolInterestFactorMantissa() external view returns (uint256); /** * @notice Block number that interest was last accrued at */ function accrualBlockNumber() external view returns (uint256); /** * @notice Accumulator of the total earned interest rate since the opening of the market */ function borrowIndex() external view returns (uint256); /** * @notice Total amount of outstanding borrows of the underlying in this market */ function totalBorrows() external view returns (uint256); /** * @notice Total amount of protocol interest of the underlying held in this market */ function totalProtocolInterest() external view returns (uint256); /** * @notice Share of market's current underlying token balance that can be used as flash loan (scaled by 1e18). */ function maxFlashLoanShare() external view returns (uint256); /** * @notice Share of flash loan amount that would be taken as fee (scaled by 1e18). */ function flashLoanFeeShare() external view returns (uint256); /** * @notice Returns total token supply */ function totalSupply() external view returns (uint256); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256); /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256); /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256); /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by supervisor to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256 ); /** * @notice Returns the current per-block borrow interest rate for this mToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256); /** * @notice Returns the current per-block supply interest rate for this mToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256); /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint256); /** * @notice Accrue interest to updated borrowIndex and then calculate account's * borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external returns (uint256); /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) external view returns (uint256); /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() external returns (uint256); /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() external view returns (uint256); /** * @notice Get cash balance of this mToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256); /** * @notice Applies accrued interest to total borrows and protocol interest * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() external; /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param lendAmount The amount of the underlying asset to supply */ function lend(uint256 lendAmount) external; /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying */ function redeem(uint256 redeemTokens) external; /** * @notice Redeems all mTokens for account in exchange for the underlying asset. * Can only be called within the AML system! * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param account An account that is potentially sanctioned by the AML system */ function redeemByAmlDecision(address account) external; /** * @notice Sender redeems mTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming mTokens */ function redeemUnderlying(uint256 redeemAmount) external; /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow */ function borrow(uint256 borrowAmount) external; /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay */ function repayBorrow(uint256 repayAmount) external; /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay */ function repayBorrowBehalf(address borrower, uint256 repayAmount) external; /** * @notice Liquidator repays a borrow belonging to borrower * @param borrower_ the account with the debt being payed off * @param repayAmount_ the amount of underlying tokens being returned */ function autoLiquidationRepayBorrow(address borrower_, uint256 repayAmount_) external; /** * @notice A public function to sweep accidental ERC-20 transfers to this contract. * Tokens are sent to admin (timelock) * @param token The address of the ERC-20 token to sweep * @dev RESTRICTION: Admin only. */ function sweepToken(IERC20 token, address admin_) external; /** * @notice Burns collateral tokens at the borrower's address, transfer underlying assets to the Liquidator address. * @dev Called only during an auto liquidation process, msg.sender must be the Liquidation contract. * @param borrower_ The account having collateral seized * @param seizeUnderlyingAmount_ The number of underlying assets to seize. The caller must ensure that the parameter is greater than zero. * @param isLoanInsignificant_ Marker for insignificant loan whose collateral must be credited to the protocolInterest * @param receiver_ Address that receives accounts collateral */ function autoLiquidationSeize( address borrower_, uint256 seizeUnderlyingAmount_, bool isLoanInsignificant_, address receiver_ ) external; /** * @notice The amount of currency available to be lent. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan(address token) external view returns (uint256); /** * @notice The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee(address token, uint256 amount) external view returns (uint256); /** * @notice Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); /** * @notice accrues interest and sets a new protocol interest factor for the protocol * @dev Admin function to accrue interest and set a new protocol interest factor * @dev RESTRICTION: Timelock only. */ function setProtocolInterestFactor(uint256 newProtocolInterestFactorMantissa) external; /** * @notice Accrues interest and increase protocol interest by transferring from msg.sender * @param addAmount_ Amount of addition to protocol interest */ function addProtocolInterest(uint256 addAmount_) external; /** * @notice Can only be called by liquidation contract. Increase protocol interest by transferring from payer. * @dev Calling code should make sure that accrueInterest() was called before. * @param payer_ The address from which the protocol interest will be transferred * @param addAmount_ Amount of addition to protocol interest */ function addProtocolInterestBehalf(address payer_, uint256 addAmount_) external; /** * @notice Accrues interest and reduces protocol interest by transferring to admin * @param reduceAmount Amount of reduction to protocol interest * @dev RESTRICTION: Admin only. */ function reduceProtocolInterest(uint256 reduceAmount, address admin_) external; /** * @notice accrues interest and updates the interest rate model using setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @dev RESTRICTION: Timelock only. */ function setInterestRateModel(IInterestRateModel newInterestRateModel) external; /** * @notice Updates share of markets cash that can be used as maximum amount of flash loan. * @param newMax New max amount share * @dev RESTRICTION: Timelock only. */ function setFlashLoanMaxShare(uint256 newMax) external; /** * @notice Updates fee of flash loan. * @param newFee New fee share of flash loan * @dev RESTRICTION: Timelock only. */ function setFlashLoanFeeShare(uint256 newFee) external; }
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol) // This file was procedurally generated from scripts/generate/templates/StorageSlot.js. pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ```solidity * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._ * _Available since v4.9 for `string`, `bytes`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } struct StringSlot { string value; } struct BytesSlot { bytes value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` representation of the string storage pointer `store`. */ function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } /** * @dev Returns an `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. */ function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } }
@openzeppelin/contracts-upgradeable/governance/GovernorUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.1) (governance/Governor.sol) pragma solidity ^0.8.0; import "../token/ERC721/IERC721ReceiverUpgradeable.sol"; import "../token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "../utils/cryptography/ECDSAUpgradeable.sol"; import "../utils/cryptography/EIP712Upgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../utils/math/SafeCastUpgradeable.sol"; import "../utils/structs/DoubleEndedQueueUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "./IGovernorUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Core of the governance system, designed to be extended though various modules. * * This contract is abstract and requires several functions to be implemented in various modules: * * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote} * - A voting module must implement {_getVotes} * - Additionally, {votingPeriod} must also be implemented * * _Available since v4.3._ */ abstract contract GovernorUpgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, EIP712Upgradeable, IGovernorUpgradeable, IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { using DoubleEndedQueueUpgradeable for DoubleEndedQueueUpgradeable.Bytes32Deque; bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); bytes32 public constant EXTENDED_BALLOT_TYPEHASH = keccak256("ExtendedBallot(uint256 proposalId,uint8 support,string reason,bytes params)"); // solhint-disable var-name-mixedcase struct ProposalCore { // --- start retyped from Timers.BlockNumber at offset 0x00 --- uint64 voteStart; address proposer; bytes4 __gap_unused0; // --- start retyped from Timers.BlockNumber at offset 0x20 --- uint64 voteEnd; bytes24 __gap_unused1; // --- Remaining fields starting at offset 0x40 --------------- bool executed; bool canceled; } // solhint-enable var-name-mixedcase string private _name; /// @custom:oz-retyped-from mapping(uint256 => Governor.ProposalCore) mapping(uint256 => ProposalCore) private _proposals; // This queue keeps track of the governor operating on itself. Calls to functions protected by the // {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute}, // consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. This ensures that the // execution of {onlyGovernance} protected calls can only be achieved through successful proposals. DoubleEndedQueueUpgradeable.Bytes32Deque private _governanceCall; /** * @dev Restricts a function so it can only be executed through governance proposals. For example, governance * parameter setters in {GovernorSettings} are protected using this modifier. * * The governance executing address may be different from the Governor's own address, for example it could be a * timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these * functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus, * for example, additional timelock proposers are not able to change governance parameters without going through the * governance protocol (since v4.6). */ modifier onlyGovernance() { require(_msgSender() == _executor(), "Governor: onlyGovernance"); if (_executor() != address(this)) { bytes32 msgDataHash = keccak256(_msgData()); // loop until popping the expected operation - throw if deque is empty (operation not authorized) while (_governanceCall.popFront() != msgDataHash) {} } _; } /** * @dev Sets the value for {name} and {version} */ function __Governor_init(string memory name_) internal onlyInitializing { __EIP712_init_unchained(name_, version()); __Governor_init_unchained(name_); } function __Governor_init_unchained(string memory name_) internal onlyInitializing { _name = name_; } /** * @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract) */ receive() external payable virtual { require(_executor() == address(this), "Governor: must send to executor"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC165Upgradeable) returns (bool) { bytes4 governorCancelId = this.cancel.selector ^ this.proposalProposer.selector; bytes4 governorParamsId = this.castVoteWithReasonAndParams.selector ^ this.castVoteWithReasonAndParamsBySig.selector ^ this.getVotesWithParams.selector; // The original interface id in v4.3. bytes4 governor43Id = type(IGovernorUpgradeable).interfaceId ^ type(IERC6372Upgradeable).interfaceId ^ governorCancelId ^ governorParamsId; // An updated interface id in v4.6, with params added. bytes4 governor46Id = type(IGovernorUpgradeable).interfaceId ^ type(IERC6372Upgradeable).interfaceId ^ governorCancelId; // For the updated interface id in v4.9, we use governorCancelId directly. return interfaceId == governor43Id || interfaceId == governor46Id || interfaceId == governorCancelId || interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IGovernor-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IGovernor-version}. */ function version() public view virtual override returns (string memory) { return "1"; } /** * @dev See {IGovernor-hashProposal}. * * The proposal id is produced by hashing the ABI encoded `targets` array, the `values` array, the `calldatas` array * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in * advance, before the proposal is submitted. * * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the * same proposal (with same operation and same description) will have the same id if submitted on multiple governors * across multiple networks. This also means that in order to execute the same operation twice (on the same * governor) the proposer will have to change the description in order to avoid proposal id conflicts. */ function hashProposal( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public pure virtual override returns (uint256) { return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash))); } /** * @dev See {IGovernor-state}. */ function state(uint256 proposalId) public view virtual override returns (ProposalState) { ProposalCore storage proposal = _proposals[proposalId]; if (proposal.executed) { return ProposalState.Executed; } if (proposal.canceled) { return ProposalState.Canceled; } uint256 snapshot = proposalSnapshot(proposalId); if (snapshot == 0) { revert("Governor: unknown proposal id"); } uint256 currentTimepoint = clock(); if (snapshot >= currentTimepoint) { return ProposalState.Pending; } uint256 deadline = proposalDeadline(proposalId); if (deadline >= currentTimepoint) { return ProposalState.Active; } if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) { return ProposalState.Succeeded; } else { return ProposalState.Defeated; } } /** * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_. */ function proposalThreshold() public view virtual returns (uint256) { return 0; } /** * @dev See {IGovernor-proposalSnapshot}. */ function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) { return _proposals[proposalId].voteStart; } /** * @dev See {IGovernor-proposalDeadline}. */ function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) { return _proposals[proposalId].voteEnd; } /** * @dev Returns the account that created a given proposal. */ function proposalProposer(uint256 proposalId) public view virtual override returns (address) { return _proposals[proposalId].proposer; } /** * @dev Amount of votes already cast passes the threshold limit. */ function _quorumReached(uint256 proposalId) internal view virtual returns (bool); /** * @dev Is the proposal successful or not. */ function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool); /** * @dev Get the voting weight of `account` at a specific `timepoint`, for a vote as described by `params`. */ function _getVotes(address account, uint256 timepoint, bytes memory params) internal view virtual returns (uint256); /** * @dev Register a vote for `proposalId` by `account` with a given `support`, voting `weight` and voting `params`. * * Note: Support is generic and can represent various things depending on the voting system used. */ function _countVote( uint256 proposalId, address account, uint8 support, uint256 weight, bytes memory params ) internal virtual; /** * @dev Default additional encoded parameters used by castVote methods that don't include them * * Note: Should be overridden by specific implementations to use an appropriate value, the * meaning of the additional params, in the context of that implementation */ function _defaultParams() internal view virtual returns (bytes memory) { return ""; } /** * @dev See {IGovernor-propose}. This function has opt-in frontrunning protection, described in {_isValidDescriptionForProposer}. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual override returns (uint256) { address proposer = _msgSender(); require(_isValidDescriptionForProposer(proposer, description), "Governor: proposer restricted"); uint256 currentTimepoint = clock(); require( getVotes(proposer, currentTimepoint - 1) >= proposalThreshold(), "Governor: proposer votes below proposal threshold" ); uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description))); require(targets.length == values.length, "Governor: invalid proposal length"); require(targets.length == calldatas.length, "Governor: invalid proposal length"); require(targets.length > 0, "Governor: empty proposal"); require(_proposals[proposalId].voteStart == 0, "Governor: proposal already exists"); uint256 snapshot = currentTimepoint + votingDelay(); uint256 deadline = snapshot + votingPeriod(); _proposals[proposalId] = ProposalCore({ proposer: proposer, voteStart: SafeCastUpgradeable.toUint64(snapshot), voteEnd: SafeCastUpgradeable.toUint64(deadline), executed: false, canceled: false, __gap_unused0: 0, __gap_unused1: 0 }); emit ProposalCreated( proposalId, proposer, targets, values, new string[](targets.length), calldatas, snapshot, deadline, description ); return proposalId; } /** * @dev See {IGovernor-execute}. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual override returns (uint256) { uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); ProposalState currentState = state(proposalId); require( currentState == ProposalState.Succeeded || currentState == ProposalState.Queued, "Governor: proposal not successful" ); _proposals[proposalId].executed = true; emit ProposalExecuted(proposalId); _beforeExecute(proposalId, targets, values, calldatas, descriptionHash); _execute(proposalId, targets, values, calldatas, descriptionHash); _afterExecute(proposalId, targets, values, calldatas, descriptionHash); return proposalId; } /** * @dev See {IGovernor-cancel}. */ function cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public virtual override returns (uint256) { uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); require(state(proposalId) == ProposalState.Pending, "Governor: too late to cancel"); require(_msgSender() == _proposals[proposalId].proposer, "Governor: only proposer can cancel"); return _cancel(targets, values, calldatas, descriptionHash); } /** * @dev Internal execution mechanism. Can be overridden to implement different execution mechanism */ function _execute( uint256 /* proposalId */, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 /*descriptionHash*/ ) internal virtual { string memory errorMessage = "Governor: call reverted without message"; for (uint256 i = 0; i < targets.length; ++i) { (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]); AddressUpgradeable.verifyCallResult(success, returndata, errorMessage); } } /** * @dev Hook before execution is triggered. */ function _beforeExecute( uint256 /* proposalId */, address[] memory targets, uint256[] memory /* values */, bytes[] memory calldatas, bytes32 /*descriptionHash*/ ) internal virtual { if (_executor() != address(this)) { for (uint256 i = 0; i < targets.length; ++i) { if (targets[i] == address(this)) { _governanceCall.pushBack(keccak256(calldatas[i])); } } } } /** * @dev Hook after execution is triggered. */ function _afterExecute( uint256 /* proposalId */, address[] memory /* targets */, uint256[] memory /* values */, bytes[] memory /* calldatas */, bytes32 /*descriptionHash*/ ) internal virtual { if (_executor() != address(this)) { if (!_governanceCall.empty()) { _governanceCall.clear(); } } } /** * @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as * canceled to allow distinguishing it from executed proposals. * * Emits a {IGovernor-ProposalCanceled} event. */ function _cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal virtual returns (uint256) { uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); ProposalState currentState = state(proposalId); require( currentState != ProposalState.Canceled && currentState != ProposalState.Expired && currentState != ProposalState.Executed, "Governor: proposal not active" ); _proposals[proposalId].canceled = true; emit ProposalCanceled(proposalId); return proposalId; } /** * @dev See {IGovernor-getVotes}. */ function getVotes(address account, uint256 timepoint) public view virtual override returns (uint256) { return _getVotes(account, timepoint, _defaultParams()); } /** * @dev See {IGovernor-getVotesWithParams}. */ function getVotesWithParams( address account, uint256 timepoint, bytes memory params ) public view virtual override returns (uint256) { return _getVotes(account, timepoint, params); } /** * @dev See {IGovernor-castVote}. */ function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, ""); } /** * @dev See {IGovernor-castVoteWithReason}. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, reason); } /** * @dev See {IGovernor-castVoteWithReasonAndParams}. */ function castVoteWithReasonAndParams( uint256 proposalId, uint8 support, string calldata reason, bytes memory params ) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, reason, params); } /** * @dev See {IGovernor-castVoteBySig}. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual override returns (uint256) { address voter = ECDSAUpgradeable.recover( _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))), v, r, s ); return _castVote(proposalId, voter, support, ""); } /** * @dev See {IGovernor-castVoteWithReasonAndParamsBySig}. */ function castVoteWithReasonAndParamsBySig( uint256 proposalId, uint8 support, string calldata reason, bytes memory params, uint8 v, bytes32 r, bytes32 s ) public virtual override returns (uint256) { address voter = ECDSAUpgradeable.recover( _hashTypedDataV4( keccak256( abi.encode( EXTENDED_BALLOT_TYPEHASH, proposalId, support, keccak256(bytes(reason)), keccak256(params) ) ) ), v, r, s ); return _castVote(proposalId, voter, support, reason, params); } /** * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams(). * * Emits a {IGovernor-VoteCast} event. */ function _castVote( uint256 proposalId, address account, uint8 support, string memory reason ) internal virtual returns (uint256) { return _castVote(proposalId, account, support, reason, _defaultParams()); } /** * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. * * Emits a {IGovernor-VoteCast} event. */ function _castVote( uint256 proposalId, address account, uint8 support, string memory reason, bytes memory params ) internal virtual returns (uint256) { ProposalCore storage proposal = _proposals[proposalId]; require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active"); uint256 weight = _getVotes(account, proposal.voteStart, params); _countVote(proposalId, account, support, weight, params); if (params.length == 0) { emit VoteCast(account, proposalId, support, weight, reason); } else { emit VoteCastWithParams(account, proposalId, support, weight, reason, params); } return weight; } /** * @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor * is some contract other than the governor itself, like when using a timelock, this function can be invoked * in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake. * Note that if the executor is simply the governor itself, use of `relay` is redundant. */ function relay(address target, uint256 value, bytes calldata data) external payable virtual onlyGovernance { (bool success, bytes memory returndata) = target.call{value: value}(data); AddressUpgradeable.verifyCallResult(success, returndata, "Governor: relay reverted without message"); } /** * @dev Address through which the governor executes action. Will be overloaded by module that execute actions * through another contract such as a timelock. */ function _executor() internal view virtual returns (address) { return address(this); } /** * @dev See {IERC721Receiver-onERC721Received}. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155Received}. */ function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } /** * @dev See {IERC1155Receiver-onERC1155BatchReceived}. */ function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } /** * @dev Check if the proposer is authorized to submit a proposal with the given description. * * If the proposal description ends with `#proposer=0x???`, where `0x???` is an address written as a hex string * (case insensitive), then the submission of this proposal will only be authorized to said address. * * This is used for frontrunning protection. By adding this pattern at the end of their proposal, one can ensure * that no other address can submit the same proposal. An attacker would have to either remove or change that part, * which would result in a different proposal id. * * If the description does not match this pattern, it is unrestricted and anyone can submit it. This includes: * - If the `0x???` part is not a valid hex string. * - If the `0x???` part is a valid hex string, but does not contain exactly 40 hex digits. * - If it ends with the expected suffix followed by newlines or other whitespace. * - If it ends with some other similar suffix, e.g. `#other=abc`. * - If it does not end with any such suffix. */ function _isValidDescriptionForProposer( address proposer, string memory description ) internal view virtual returns (bool) { uint256 len = bytes(description).length; // Length is too short to contain a valid proposer suffix if (len < 52) { return true; } // Extract what would be the `#proposer=0x` marker beginning the suffix bytes12 marker; assembly { // - Start of the string contents in memory = description + 32 // - First character of the marker = len - 52 // - Length of "#proposer=0x0000000000000000000000000000000000000000" = 52 // - We read the memory word starting at the first character of the marker: // - (description + 32) + (len - 52) = description + (len - 20) // - Note: Solidity will ignore anything past the first 12 bytes marker := mload(add(description, sub(len, 20))) } // If the marker is not found, there is no proposer suffix to check if (marker != bytes12("#proposer=0x")) { return true; } // Parse the 40 characters following the marker as uint160 uint160 recovered = 0; for (uint256 i = len - 40; i < len; ++i) { (bool isHex, uint8 value) = _tryHexToUint(bytes(description)[i]); // If any of the characters is not a hex digit, ignore the suffix entirely if (!isHex) { return true; } recovered = (recovered << 4) | value; } return recovered == uint160(proposer); } /** * @dev Try to parse a character from a string as a hex value. Returns `(true, value)` if the char is in * `[0-9a-fA-F]` and `(false, 0)` otherwise. Value is guaranteed to be in the range `0 <= value < 16` */ function _tryHexToUint(bytes1 char) private pure returns (bool, uint8) { uint8 c = uint8(char); unchecked { // Case 0-9 if (47 < c && c < 58) { return (true, c - 48); } // Case A-F else if (64 < c && c < 71) { return (true, c - 55); } // Case a-f else if (96 < c && c < 103) { return (true, c - 87); } // Else: not a hex char else { return (false, 0); } } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[46] private __gap; }
@openzeppelin/contracts-upgradeable/governance/utils/IVotesUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (governance/utils/IVotes.sol) pragma solidity ^0.8.0; /** * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. * * _Available since v4.5._ */ interface IVotesUpgradeable { /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Returns the current amount of votes that `account` has. */ function getVotes(address account) external view returns (uint256); /** * @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is * configured to use block numbers, this will return the value at the end of the corresponding block. */ function getPastVotes(address account, uint256 timepoint) external view returns (uint256); /** * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is * configured to use block numbers, this will return the value at the end of the corresponding block. * * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. * Votes that have not been delegated are still part of total supply, even though they would not participate in a * vote. */ function getPastTotalSupply(uint256 timepoint) external view returns (uint256); /** * @dev Returns the delegate that `account` has chosen. */ function delegates(address account) external view returns (address); /** * @dev Delegates votes from the sender to `delegatee`. */ function delegate(address delegatee) external; /** * @dev Delegates votes from signer to `delegatee`. */ function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external; }
@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC3156FlashBorrower.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC3156 FlashBorrower, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * _Available since v4.1._ */ interface IERC3156FlashBorrower { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); }
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); }
contracts/governance/MntVotes.sol
// SPDX-License-Identifier: (MIT AND BSD-3-Clause) // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Votes.sol) pragma solidity 0.8.17; import "@openzeppelin/contracts-upgradeable/governance/utils/IVotesUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /** * @dev Differences from OpenZeppelin ERC20Votes: * - Voting power is accessed via virtual method {getStoredVotingPower} instead of {balanceOf}. * - Removed `_mint`, `_burn` and `_afterTokenTransfer` overrides. * - Some dependency libraries are not from `openzeppelin/contracts-upgradeable` * - Added 2 (TWO) storage variables so __gap in the end was decreased by 2 * * @dev Unlike in the original ERC20Votes this implementation don't use account balance as voting power. * Instead we use aggregated weight that is calculated using three different sources: Vesting, Buyback and RewardsHub. * Voting weight update should be done automatically each time when weight changes in any of its sources. * In order to enable voting, account should first call {delegate} function with their own address or their delegates. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * _Available since v4.2._ */ abstract contract MntVotes is IVotesUpgradeable, ERC20PermitUpgradeable { struct Checkpoint { uint32 fromBlock; uint224 votes; } struct VoteTimestamps { uint32 delegated; uint32 voted; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) internal _checkpoints; Checkpoint[] internal _totalSupplyCheckpoints; // Vote timestamp tracking uint256 public maxNonVotingPeriod; mapping(address => VoteTimestamps) internal voteTimestamps; function __ERC20Votes_init(uint256 initialNonVotingPeriod) internal onlyInitializing { __ERC20Votes_init_unchained(initialNonVotingPeriod); } function __ERC20Votes_init_unchained(uint256 initialNonVotingPeriod) internal onlyInitializing { maxNonVotingPeriod = initialNonVotingPeriod; } /** * @dev Accessor of stored voting power. */ function getStoredVotingPower(address account) internal view virtual returns (uint256); /** * @dev Accessor of stored total voting power. */ function getStoredTotalVotingPower() internal view virtual returns (uint256); /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual override returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view virtual override returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { require(blockNumber < getBlockNumber(), "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve total voting weights at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) { require(blockNumber < getBlockNumber(), "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // Each iteration, either `low` or `high` moves towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual override { _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); _delegate(signer, delegatee); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorVotes = getStoredVotingPower(delegator); _delegates[delegator] = delegatee; VoteTimestamps memory delegatorLast = voteTimestamps[delegator]; // If current delegatee voted after the delegator assigned their votes to it we should update the voting // timestamp as if delegator voted themselves. Update delegatorLast.voted with new value here so we can // use the same variable value below to set a new timestamp pair for the delegator uint32 delegateVoted = voteTimestamps[currentDelegate].voted; if (delegateVoted > delegatorLast.delegated) delegatorLast.voted = delegateVoted; voteTimestamps[delegator] = VoteTimestamps({ delegated: SafeCast.toUint32(block.timestamp), voted: delegatorLast.voted // either old delegator voting timestamp or new delegatee's latest vote }); emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorVotes); } function _moveVotingPower( address src, address dst, uint256 amount ) internal { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeightSrc, uint256 newWeightSrc) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeightSrc, newWeightSrc); } if (dst != address(0)) { (uint256 oldWeightDst, uint256 newWeightDst) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeightDst, newWeightDst); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == uint32(getBlockNumber())) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push( Checkpoint({fromBlock: SafeCast.toUint32(getBlockNumber()), votes: SafeCast.toUint224(newWeight)}) ); } } function _pushTotalWeightCheckpoint() internal returns (uint256 oldWeight) { Checkpoint[] storage ckpts = _totalSupplyCheckpoints; uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; uint256 newWeight = getStoredTotalVotingPower(); if (pos > 0 && ckpts[pos - 1].fromBlock == uint32(getBlockNumber())) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push( Checkpoint({fromBlock: SafeCast.toUint32(getBlockNumber()), votes: SafeCast.toUint224(newWeight)}) ); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } // // // // Utils // // // // /// @dev Function to simply retrieve block number /// This exists mainly for inheriting test contracts to stub this result. function getBlockNumber() internal view virtual returns (uint256) { return block.number; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; }
@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; }
@openzeppelin/contracts-upgradeable/governance/extensions/GovernorVotesUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorVotes.sol) pragma solidity ^0.8.0; import "../GovernorUpgradeable.sol"; import "../../interfaces/IERC5805Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token, or since v4.5 an {ERC721Votes} token. * * _Available since v4.3._ * * @custom:storage-size 51 */ abstract contract GovernorVotesUpgradeable is Initializable, GovernorUpgradeable { IERC5805Upgradeable public token; function __GovernorVotes_init(IVotesUpgradeable tokenAddress) internal onlyInitializing { __GovernorVotes_init_unchained(tokenAddress); } function __GovernorVotes_init_unchained(IVotesUpgradeable tokenAddress) internal onlyInitializing { token = IERC5805Upgradeable(address(tokenAddress)); } /** * @dev Clock (as specified in EIP-6372) is set to match the token's clock. Fallback to block numbers if the token * does not implement EIP-6372. */ function clock() public view virtual override returns (uint48) { try token.clock() returns (uint48 timepoint) { return timepoint; } catch { return SafeCastUpgradeable.toUint48(block.number); } } /** * @dev Machine-readable description of the clock as specified in EIP-6372. */ // solhint-disable-next-line func-name-mixedcase function CLOCK_MODE() public view virtual override returns (string memory) { try token.CLOCK_MODE() returns (string memory clockmode) { return clockmode; } catch { return "mode=blocknumber&from=default"; } } /** * Read the voting weight from the token's built in snapshot mechanism (see {Governor-_getVotes}). */ function _getVotes( address account, uint256 timepoint, bytes memory /*params*/ ) internal view virtual override returns (uint256) { return token.getPastVotes(account, timepoint); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
contracts/governance/Mnt.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "./MntVotes.sol"; import "../libraries/ErrorCodes.sol"; import "../InterconnectorLeaf.sol"; import "../interfaces/IMnt.sol"; import "../interfaces/IWeightAggregator.sol"; contract Mnt is IMnt, MntVotes, AccessControlUpgradeable, InterconnectorLeaf { /// @notice Total number of tokens in circulation uint256 internal constant TOTAL_SUPPLY = 65_902_270e18; // 65,902,270 MNT address public governor; mapping(address => uint256) public votingWeight; uint256 public totalVotingWeight; constructor() { _disableInitializers(); } function initialize(address holder, address owner) public virtual initializer { __ERC20_init("Minterest", "MINTY"); __ERC20Permit_init("Minterest"); __ERC20Votes_init(365 days); _grantRole(DEFAULT_ADMIN_ROLE, owner); _mint(holder, TOTAL_SUPPLY); } /// @dev Hook that is called before any transfer of tokens function _beforeTokenTransfer( address from, address to, uint256 ) internal override { IInterconnector interconnector = getInterconnector(); if (address(interconnector) != address(0)) { // this check required only if MNT interconnected with supervisor, // otherwise (for example on initial mint) it will be skipped require(interconnector.supervisor().isMntTransferAllowed(from, to), ErrorCodes.ADDRESS_IS_BLACKLISTED); } } /** * @dev Used to replace `balanceOf` method and pass stored voting power into parent MntVotes contract */ function getStoredVotingPower(address account) internal view override returns (uint256) { return votingWeight[account]; } function getStoredTotalVotingPower() internal view override returns (uint256) { return totalVotingWeight; } // // // // Vote updates /// @inheritdoc IMnt function updateVotingWeight(address account) external { require(account != address(0), ErrorCodes.ZERO_ADDRESS); uint256 oldWeight = getStoredVotingPower(account); uint256 newWeight = weightAggregator().getVotingWeight(account); if (newWeight == oldWeight) return; if (newWeight > oldWeight) { uint256 delta = newWeight - oldWeight; _moveVotingPower(address(0), delegates(account), delta); totalVotingWeight += delta; } else { uint256 delta = oldWeight - newWeight; _moveVotingPower(delegates(account), address(0), delta); totalVotingWeight -= delta; } votingWeight[account] = newWeight; emit VotesUpdated(account, oldWeight, newWeight); } /// @inheritdoc IMnt function updateTotalWeightCheckpoint() external { require(msg.sender == address(governor), ErrorCodes.UNAUTHORIZED); uint256 oldWeight = _pushTotalWeightCheckpoint(); emit TotalVotesUpdated(oldWeight, totalVotingWeight); } // // // // Vote timestamp tracking /// @inheritdoc IMnt function isParticipantActive(address account_) public view virtual returns (bool) { return lastActivityTimestamp(account_) > block.timestamp - maxNonVotingPeriod; } /// @inheritdoc IMnt function updateVoteTimestamp(address account) external { require(msg.sender == address(governor), ErrorCodes.UNAUTHORIZED); voteTimestamps[account].voted = SafeCast.toUint32(block.timestamp); } /// @inheritdoc IMnt function lastActivityTimestamp(address account) public view virtual returns (uint256) { VoteTimestamps memory accountLast = voteTimestamps[account]; // if the votes are not delegated to anyone, then return the timestamp of the last vote of the account address currentDelegate = delegates(account); if (currentDelegate == address(0)) return accountLast.voted; // if delegate voted after delegation then returns its vote timestamp, otherwise return accounts uint32 delegateLastVoted = voteTimestamps[currentDelegate].voted; return delegateLastVoted > accountLast.delegated ? delegateLastVoted : accountLast.voted; } function weightAggregator() internal view returns (IWeightAggregator) { return getInterconnector().weightAggregator(); } // // // // Admin zone /// @inheritdoc IMnt function setGovernor(address newGovernor) external onlyRole(DEFAULT_ADMIN_ROLE) { require(governor == address(0), ErrorCodes.SECOND_INITIALIZATION); require(newGovernor != address(0), ErrorCodes.ZERO_ADDRESS); governor = newGovernor; emit NewGovernor(newGovernor); } /// @inheritdoc IMnt function setMaxNonVotingPeriod(uint256 newPeriod_) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newPeriod_ >= 90 days && newPeriod_ <= 2 * 365 days, ErrorCodes.MNT_INVALID_NONVOTING_PERIOD); uint256 oldPeriod = maxNonVotingPeriod; require(newPeriod_ != oldPeriod, ErrorCodes.IDENTICAL_VALUE); emit MaxNonVotingPeriodChanged(oldPeriod, newPeriod_); maxNonVotingPeriod = newPeriod_; } /// @dev Returns true if this contract implements the interface defined by `interfaceId` function supportsInterface(bytes4 interfaceId) public pure virtual override(IERC165, AccessControlUpgradeable) returns (bool) { return interfaceId == type(IERC20).interfaceId || // EIP-20 - 0x36372b07 interfaceId == type(IERC20PermitUpgradeable).interfaceId || // EIP-2612 - 0x9d8ff7da interfaceId == type(IVotesUpgradeable).interfaceId; // OpenZeppelin Votes - 0xe90fb3f6 } }
@openzeppelin/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.0; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
contracts/interfaces/IInterestRateModel.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @title Minterest InterestRateModel Interface * @author Minterest */ interface IInterestRateModel { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param protocolInterest The total amount of protocol interest the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 protocolInterest ) external view returns (uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param protocolInterest The total amount of protocol interest the market has * @param protocolInterestFactorMantissa The current protocol interest factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 protocolInterest, uint256 protocolInterestFactorMantissa ) external view returns (uint256); }
@openzeppelin/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toUint248(uint256 value) internal pure returns (uint248) { require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits"); return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toUint240(uint256 value) internal pure returns (uint240) { require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits"); return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toUint232(uint256 value) internal pure returns (uint232) { require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits"); return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.2._ */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toUint216(uint256 value) internal pure returns (uint216) { require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits"); return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toUint208(uint256 value) internal pure returns (uint208) { require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits"); return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toUint200(uint256 value) internal pure returns (uint200) { require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits"); return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits"); return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toUint184(uint256 value) internal pure returns (uint184) { require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits"); return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toUint176(uint256 value) internal pure returns (uint176) { require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits"); return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toUint168(uint256 value) internal pure returns (uint168) { require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits"); return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toUint160(uint256 value) internal pure returns (uint160) { require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits"); return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toUint152(uint256 value) internal pure returns (uint152) { require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits"); return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toUint144(uint256 value) internal pure returns (uint144) { require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits"); return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toUint136(uint256 value) internal pure returns (uint136) { require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits"); return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v2.5._ */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toUint120(uint256 value) internal pure returns (uint120) { require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits"); return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.2._ */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toUint88(uint256 value) internal pure returns (uint88) { require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits"); return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toUint80(uint256 value) internal pure returns (uint80) { require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits"); return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toUint72(uint256 value) internal pure returns (uint72) { require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits"); return uint72(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 * * _Available since v2.5._ */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toUint56(uint256 value) internal pure returns (uint56) { require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits"); return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toUint48(uint256 value) internal pure returns (uint48) { require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits"); return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toUint40(uint256 value) internal pure returns (uint40) { require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits"); return uint40(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 * * _Available since v2.5._ */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toUint24(uint256 value) internal pure returns (uint24) { require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits"); return uint24(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 * * _Available since v2.5._ */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v2.5._ */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. * * _Available since v3.0._ */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); require(downcasted == value, "SafeCast: value doesn't fit in 248 bits"); } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); require(downcasted == value, "SafeCast: value doesn't fit in 240 bits"); } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); require(downcasted == value, "SafeCast: value doesn't fit in 232 bits"); } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.7._ */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); require(downcasted == value, "SafeCast: value doesn't fit in 224 bits"); } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); require(downcasted == value, "SafeCast: value doesn't fit in 216 bits"); } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); require(downcasted == value, "SafeCast: value doesn't fit in 208 bits"); } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); require(downcasted == value, "SafeCast: value doesn't fit in 200 bits"); } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); require(downcasted == value, "SafeCast: value doesn't fit in 192 bits"); } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); require(downcasted == value, "SafeCast: value doesn't fit in 184 bits"); } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); require(downcasted == value, "SafeCast: value doesn't fit in 176 bits"); } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); require(downcasted == value, "SafeCast: value doesn't fit in 168 bits"); } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); require(downcasted == value, "SafeCast: value doesn't fit in 160 bits"); } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); require(downcasted == value, "SafeCast: value doesn't fit in 152 bits"); } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); require(downcasted == value, "SafeCast: value doesn't fit in 144 bits"); } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); require(downcasted == value, "SafeCast: value doesn't fit in 136 bits"); } /** * @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 downcasted) { downcasted = int128(value); require(downcasted == value, "SafeCast: value doesn't fit in 128 bits"); } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); require(downcasted == value, "SafeCast: value doesn't fit in 120 bits"); } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); require(downcasted == value, "SafeCast: value doesn't fit in 112 bits"); } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); require(downcasted == value, "SafeCast: value doesn't fit in 104 bits"); } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.7._ */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); require(downcasted == value, "SafeCast: value doesn't fit in 96 bits"); } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); require(downcasted == value, "SafeCast: value doesn't fit in 88 bits"); } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); require(downcasted == value, "SafeCast: value doesn't fit in 80 bits"); } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); require(downcasted == value, "SafeCast: value doesn't fit in 72 bits"); } /** * @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 downcasted) { downcasted = int64(value); require(downcasted == value, "SafeCast: value doesn't fit in 64 bits"); } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); require(downcasted == value, "SafeCast: value doesn't fit in 56 bits"); } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); require(downcasted == value, "SafeCast: value doesn't fit in 48 bits"); } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); require(downcasted == value, "SafeCast: value doesn't fit in 40 bits"); } /** * @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 downcasted) { downcasted = int32(value); require(downcasted == value, "SafeCast: value doesn't fit in 32 bits"); } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); require(downcasted == value, "SafeCast: value doesn't fit in 24 bits"); } /** * @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 downcasted) { downcasted = int16(value); require(downcasted == value, "SafeCast: value doesn't fit in 16 bits"); } /** * @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 downcasted) { downcasted = int8(value); require(downcasted == value, "SafeCast: value doesn't fit in 8 bits"); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. * * _Available since v3.0._ */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
contracts/interfaces/IPriceOracle.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "./IMToken.sol"; interface IPriceOracle { /** * @notice Get the underlying price of a mToken asset * @param mToken The mToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. * * @dev Price should be scaled to 1e18 for tokens with tokenDecimals = 1e18 * and for 1e30 for tokens with tokenDecimals = 1e6. */ function getUnderlyingPrice(IMToken mToken) external view returns (uint256); /** * @notice Return price for an asset * @param asset address of token * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. * @dev Price should be scaled to 1e18 for tokens with tokenDecimals = 1e18 * and for 1e30 for tokens with tokenDecimals = 1e6. */ function getAssetPrice(address asset) external view returns (uint256); }
contracts/interfaces/IEmissionBooster.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/access/IAccessControl.sol"; import "./ISupervisor.sol"; import "./IRewardsHub.sol"; import "./IMToken.sol"; import "./ILinkageLeaf.sol"; interface IEmissionBooster is IAccessControl, ILinkageLeaf { /** * @notice Emitted when new Tier was created */ event NewTierCreated(uint256 createdTier, uint32 endBoostBlock, uint256 emissionBoost); /** * @notice Emitted when Tier was enabled */ event TierEnabled( IMToken market, uint256 enabledTier, uint32 startBoostBlock, uint224 mntSupplyIndex, uint224 mntBorrowIndex ); /** * @notice Emitted when emission boost mode was enabled */ event EmissionBoostEnabled(address caller); /** * @notice Emitted when MNT supply index of the tier ending on the market was saved to storage */ event SupplyIndexUpdated(address market, uint256 nextTier, uint224 newIndex, uint32 endBlock); /** * @notice Emitted when MNT borrow index of the tier ending on the market was saved to storage */ event BorrowIndexUpdated(address market, uint256 nextTier, uint224 newIndex, uint32 endBlock); /** * @notice get the Tier for each MinterestNFT token */ function tokenTier(uint256) external view returns (uint256); /** * @notice get a list of all created Tiers */ function tiers(uint256) external view returns ( uint32, uint32, uint256 ); /** * @notice get status of emission boost mode. */ function isEmissionBoostingEnabled() external view returns (bool); /** * @notice get Stored markets indexes per block. */ function marketSupplyIndexes(IMToken, uint256) external view returns (uint256); /** * @notice get Stored markets indexes per block. */ function marketBorrowIndexes(IMToken, uint256) external view returns (uint256); /** * @notice Mint token hook which is called from MinterestNFT.mint() and sets specific * settings for this NFT * @param to_ NFT ovner * @param ids_ NFTs IDs * @param amounts_ Amounts of minted NFTs per tier * @param tiers_ NFT tiers * @dev RESTRICTION: MinterestNFT only */ function onMintToken( address to_, uint256[] memory ids_, uint256[] memory amounts_, uint256[] memory tiers_ ) external; /** * @notice Transfer token hook which is called from MinterestNFT.transfer() and sets specific * settings for this NFT * @param from_ Address of the tokens previous owner. Should not be zero (minter). * @param to_ Address of the tokens new owner. * @param ids_ NFTs IDs * @param amounts_ Amounts of minted NFTs per tier * @dev RESTRICTION: MinterestNFT only */ function onTransferToken( address from_, address to_, uint256[] memory ids_, uint256[] memory amounts_ ) external; /** * @notice Enables emission boost mode. * @dev Admin function for enabling emission boosts. * @dev RESTRICTION: Whitelist only */ function enableEmissionBoosting() external; /** * @notice Creates new Tiers for MinterestNFT tokens * @dev Admin function for creating Tiers * @param endBoostBlocks Emission boost end blocks for created Tiers * @param emissionBoosts Emission boosts for created Tiers, scaled by 1e18 * Note: The arrays passed to the function must be of the same length and the order of the elements must match * each other * @dev RESTRICTION: Admin only */ function createTiers(uint32[] memory endBoostBlocks, uint256[] memory emissionBoosts) external; /** * @notice Enables emission boost in specified Tiers * @param tiersForEnabling Tier for enabling emission boost * @dev RESTRICTION: Admin only */ function enableTiers(uint256[] memory tiersForEnabling) external; /** * @notice Return the number of created Tiers * @return The number of created Tiers */ function getNumberOfTiers() external view returns (uint256); /** * @notice Checks if the specified Tier is active * @param tier_ The Tier that is being checked */ function isTierActive(uint256 tier_) external view returns (bool); /** * @notice Checks if the specified Tier exists * @param tier_ The Tier that is being checked */ function tierExists(uint256 tier_) external view returns (bool); /** * @param account_ The address of the account * @return Bitmap of all accounts tiers */ function getAccountTiersBitmap(address account_) external view returns (uint256); /** * @param account_ The address of the account to check if they have any tokens with tier */ function isAccountHaveTiers(address account_) external view returns (bool); /** * @param account_ Address of the account * @return tier Highest tier number * @return boost Highest boost amount */ function getCurrentAccountBoost(address account_) external view returns (uint256 tier, uint256 boost); /** * @notice Calculates emission boost for the account. * @param market_ Market for which we are calculating emission boost * @param account_ The address of the account for which we are calculating emission boost * @param userLastIndex_ The account's last updated mntBorrowIndex or mntSupplyIndex * @param userLastBlock_ The block number in which the index for the account was last updated * @param marketIndex_ The market's current mntBorrowIndex or mntSupplyIndex * @param isSupply_ boolean value, if true, then return calculate emission boost for suppliers * @return boostedIndex Boost part of delta index */ function calculateEmissionBoost( IMToken market_, address account_, uint256 userLastIndex_, uint256 userLastBlock_, uint256 marketIndex_, bool isSupply_ ) external view returns (uint256 boostedIndex); /** * @notice Update MNT supply index for market for NFT tiers that are expired but not yet updated. * @dev This function checks if there are tiers to update and process them one by one: * calculates the MNT supply index depending on the delta index and delta blocks between * last MNT supply index update and the current state, * emits SupplyIndexUpdated event and recalculates next tier to update. * @param market Address of the market to update * @param lastUpdatedBlock Last updated block number * @param lastUpdatedIndex Last updated index value * @param currentSupplyIndex Current MNT supply index value * @dev RESTRICTION: RewardsHub only */ function updateSupplyIndexesHistory( IMToken market, uint256 lastUpdatedBlock, uint256 lastUpdatedIndex, uint256 currentSupplyIndex ) external; /** * @notice Update MNT borrow index for market for NFT tiers that are expired but not yet updated. * @dev This function checks if there are tiers to update and process them one by one: * calculates the MNT borrow index depending on the delta index and delta blocks between * last MNT borrow index update and the current state, * emits BorrowIndexUpdated event and recalculates next tier to update. * @param market Address of the market to update * @param lastUpdatedBlock Last updated block number * @param lastUpdatedIndex Last updated index value * @param currentBorrowIndex Current MNT borrow index value * @dev RESTRICTION: RewardsHub only */ function updateBorrowIndexesHistory( IMToken market, uint256 lastUpdatedBlock, uint256 lastUpdatedIndex, uint256 currentBorrowIndex ) external; /** * @notice Get Id of NFT tier to update next on provided market MNT index, supply or borrow * @param market Market for which should the next Tier to update be updated * @param isSupply_ Flag that indicates whether MNT supply or borrow market should be updated * @return Id of tier to update */ function getNextTierToBeUpdatedIndex(IMToken market, bool isSupply_) external view returns (uint256); }
contracts/multichain/taiko/interfaces/ITaikoL2_L1BlockNumber.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @title ITaikoL2_L1BlockNumber */ interface ITaikoL2_L1BlockNumber { /******************** * Public Functions * ********************/ function lastSyncedBlock() external view returns (uint64); }
contracts/multichain/taiko/libraries/TaikoContracts.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; // @dev Store the address of Taiko `TaikoL2` contract library TaikoContracts { address internal constant TaikoL2 = 0x1670090000000000000000000000000000010001; }
@openzeppelin/contracts-upgradeable/governance/extensions/GovernorCountingSimpleUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorCountingSimple.sol) pragma solidity ^0.8.0; import "../GovernorUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Extension of {Governor} for simple, 3 options, vote counting. * * _Available since v4.3._ */ abstract contract GovernorCountingSimpleUpgradeable is Initializable, GovernorUpgradeable { function __GovernorCountingSimple_init() internal onlyInitializing { } function __GovernorCountingSimple_init_unchained() internal onlyInitializing { } /** * @dev Supported vote types. Matches Governor Bravo ordering. */ enum VoteType { Against, For, Abstain } struct ProposalVote { uint256 againstVotes; uint256 forVotes; uint256 abstainVotes; mapping(address => bool) hasVoted; } mapping(uint256 => ProposalVote) private _proposalVotes; /** * @dev See {IGovernor-COUNTING_MODE}. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public pure virtual override returns (string memory) { return "support=bravo&quorum=for,abstain"; } /** * @dev See {IGovernor-hasVoted}. */ function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) { return _proposalVotes[proposalId].hasVoted[account]; } /** * @dev Accessor to the internal vote counts. */ function proposalVotes( uint256 proposalId ) public view virtual returns (uint256 againstVotes, uint256 forVotes, uint256 abstainVotes) { ProposalVote storage proposalVote = _proposalVotes[proposalId]; return (proposalVote.againstVotes, proposalVote.forVotes, proposalVote.abstainVotes); } /** * @dev See {Governor-_quorumReached}. */ function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) { ProposalVote storage proposalVote = _proposalVotes[proposalId]; return quorum(proposalSnapshot(proposalId)) <= proposalVote.forVotes + proposalVote.abstainVotes; } /** * @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be strictly over the againstVotes. */ function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) { ProposalVote storage proposalVote = _proposalVotes[proposalId]; return proposalVote.forVotes > proposalVote.againstVotes; } /** * @dev See {Governor-_countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo). */ function _countVote( uint256 proposalId, address account, uint8 support, uint256 weight, bytes memory // params ) internal virtual override { ProposalVote storage proposalVote = _proposalVotes[proposalId]; require(!proposalVote.hasVoted[account], "GovernorVotingSimple: vote already cast"); proposalVote.hasVoted[account] = true; if (support == uint8(VoteType.Against)) { proposalVote.againstVotes += weight; } else if (support == uint8(VoteType.For)) { proposalVote.forVotes += weight; } else if (support == uint8(VoteType.Abstain)) { proposalVote.abstainVotes += weight; } else { revert("GovernorVotingSimple: invalid value for enum VoteType"); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
contracts/interfaces/IBuyback.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/access/IAccessControl.sol"; import "./ILinkageLeaf.sol"; interface IBuyback is IAccessControl, ILinkageLeaf { event Stake(address who, uint256 amount); event Unstake(address who, uint256 amount); event NewBuyback(uint256 amount, uint256 share); event ParticipateBuyback(address who); event LeaveBuyback(address who, uint256 currentStaked); event BuybackWeightChanged(address who, uint256 newWeight, uint256 oldWeight, uint256 newTotalWeight); event LoyaltyParametersChanged(uint256 newCoreFactor, uint32 newCoreResetPenalty); event LoyaltyStrataChanged(); event LoyaltyGroupsChanged(uint256 newGroupCount); /** * @notice Gets info about account membership in Buyback */ function getMemberInfo(address account) external view returns ( bool participating, uint256 weight, uint256 lastIndex, uint256 stakeAmount ); /** * @notice Gets info about accounts loyalty calculation */ function getLoyaltyInfo(address account) external view returns ( uint32 loyaltyStart, uint256 coreBalance, uint256 lastBalance ); /** * @notice Gets if an account is participating in Buyback */ function isParticipating(address account) external view returns (bool); /** * @notice Gets stake of the account */ function getStakedAmount(address account) external view returns (uint256); /** * @notice Gets buyback weight of an account */ function getWeight(address account) external view returns (uint256); /** * @notice Gets loyalty factor of an account with given balance. */ function getLoyaltyFactorForBalance(address account, uint256 balance) external view returns (uint256); /** * @notice Gets total Buyback weight, which is the sum of weights of all accounts. */ function getTotalWeight() external view returns (uint256); /** * @notice Gets current Buyback index. * Its the accumulated sum of MNTs shares that are given for each weight of an account. */ function getBuybackIndex() external view returns (uint256); /** * @notice Gets all global loyalty parameters. */ function getLoyaltyParameters() external view returns ( uint256[24] memory loyaltyStrata, uint256[] memory groupThresholds, uint32[] memory groupStartStrata, uint256 coreFactor, uint32 coreResetPenalty ); /** * @notice Stakes the specified amount of MNT and transfers them to this contract. * @notice This contract should be approved to transfer MNT from sender account * @param amount The amount of MNT to stake */ function stake(uint256 amount) external; /** * @notice Unstakes the specified amount of MNT and transfers them back to sender if he participates * in the Buyback system, otherwise just transfers MNT tokens to the sender. * would not be greater than staked amount left. If `amount == MaxUint256` unstakes all staked tokens. * @param amount The amount of MNT to unstake */ function unstake(uint256 amount) external; /** * @notice Claims buyback rewards, updates buyback weight and voting power. * Does nothing if account is not participating. Reverts if operation is paused. * @param account Address to update weights for */ function updateBuybackAndVotingWeights(address account) external; /** * @notice Claims buyback rewards, updates buyback weight and voting power. * Does nothing if account is not participating or update is paused. * @param account Address to update weights for */ function updateBuybackAndVotingWeightsRelaxed(address account) external; /** * @notice Does a buyback using the specified amount of MNT from sender's account * @param amount The amount of MNT to take and distribute as buyback * @dev RESTRICTION: Distributor only */ function buyback(uint256 amount) external; /** * @notice Make account participating in the buyback. */ function participate() external; /** * @notice Make accounts participate in buyback before its start. * @param accounts Address to make participate in buyback. * @dev RESTRICTION: Admin only */ function participateOnBehalf(address[] memory accounts) external; /** * @notice Leave buyback participation, claim any MNTs rewarded by the buyback. * Leaving does not withdraw staked MNTs but reduces weight of the account to zero */ function leave() external; /** * @notice Leave buyback participation on behalf, claim any MNTs rewarded by the buyback and * reduce the weight of account to zero. All staked MNTs remain on the buyback contract and available * for their owner to be claimed * Can only be called if (timestamp > participantLastVoteTimestamp + maxNonVotingPeriod). * @param participant Address to leave for * @dev RESTRICTION: GATEKEEPER only */ function leaveOnBehalf(address participant) external; /** * @notice Leave buyback participation on behalf, claim any MNTs rewarded by the buyback and * reduce the weight of account to zero. All staked MNTs remain on the buyback contract and available * for their owner to be claimed. * @dev Function to leave sanctioned accounts from Buyback system * Can only be called if the participant is sanctioned by the AML system. * @param participant Address to leave for */ function leaveByAmlDecision(address participant) external; /** * @notice Changes loyalty core factor and core reset penalty parameters. * @dev RESTRICTION: Admin only */ function setLoyaltyParameters(uint256 newCoreFactor, uint32 newCoreResetPenalty) external; /** * @notice Sets new loyalty factors for all strata. * @dev RESTRICTION: Admin only */ function setLoyaltyStrata(uint256[24] memory newLoyaltyStrata) external; /** * @notice Sets new groups and their parameters * @param newGroupThresholds New list of groups and their balance thresholds. * @param newGroupStartStrata Indexes of starting stratum of each group. First index MUST be zero. * Length of array must be equal to the newGroupThresholds * @dev RESTRICTION: Admin only */ function setLoyaltyGroups(uint256[] memory newGroupThresholds, uint32[] memory newGroupStartStrata) external; }
contracts/interfaces/IInterconnectorLeaf.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "./IInterconnector.sol"; import "./ILinkageLeaf.sol"; interface IInterconnectorLeaf is ILinkageLeaf { function getInterconnector() external view returns (IInterconnector); }
@openzeppelin/contracts-upgradeable/interfaces/IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165Upgradeable.sol";
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
contracts/governance/MntGovernor.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts-upgradeable/governance/GovernorUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/governance/extensions/GovernorSettingsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/governance/extensions/GovernorCountingSimpleUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/governance/extensions/GovernorVotesUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/governance/extensions/GovernorVotesQuorumFractionUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/governance/extensions/GovernorTimelockControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./Mnt.sol"; import "../libraries/ErrorCodes.sol"; contract MntGovernor is Initializable, GovernorUpgradeable, GovernorSettingsUpgradeable, GovernorCountingSimpleUpgradeable, GovernorVotesUpgradeable, GovernorVotesQuorumFractionUpgradeable, GovernorTimelockControlUpgradeable { bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE"); constructor() { _disableInitializers(); } function initialize( IVotesUpgradeable _token, TimelockControllerUpgradeable _timelock, uint256 initialVotingDelay, // how long after a proposal is created should voting power be fixed (blocks) uint256 initialVotingPeriod, // how long does a proposal remain open to votes (blocks) uint256 initialProposalThreshold, // minimal voting power required to create the proposal (weight points) uint256 quorumNumeratorValue ) external initializer { __Governor_init("MntGovernor"); __GovernorSettings_init(initialVotingDelay, initialVotingPeriod, initialProposalThreshold); __GovernorCountingSimple_init(); __GovernorVotes_init(_token); // Set % of quorum required for a proposal to pass. Usually it is about 4% of total token supply // available. We use Buyback weights as voting power, it is available only for accounts that // committed to perform voting actions by participating in Buyback, so quorum is going to be // much higher __GovernorVotesQuorumFraction_init(quorumNumeratorValue); __GovernorTimelockControl_init(_timelock); } /** * @dev Modifier to make a function callable only by a canceller role defined in timelock contract. */ modifier onlyCanceller() { AccessControlUpgradeable ac = AccessControlUpgradeable(timelock()); require(ac.hasRole(CANCELLER_ROLE, msg.sender), ErrorCodes.UNAUTHORIZED); _; } /** * @dev Modifier to make a function callable only by a proposer role defined in timelock contract. In * addition to checking the sender's role, `address(0)` 's role is also considered. Granting a role * to `address(0)` is equivalent to enabling this role for everyone. */ modifier onlyProposerOrOpenRole() { AccessControlUpgradeable ac = AccessControlUpgradeable(timelock()); require( ac.hasRole(PROPOSER_ROLE, msg.sender) || ac.hasRole(PROPOSER_ROLE, address(0)), ErrorCodes.UNAUTHORIZED ); _; } // The following functions are overrides required by Solidity. /// @notice Delay (in number of blocks) since the proposal is submitted until voting power is fixed and voting /// starts. This can be used to enforce a delay after a proposal is published for users to buy tokens, /// or delegate their votes. function votingDelay() public view override(IGovernorUpgradeable, GovernorSettingsUpgradeable) returns (uint256) { return super.votingDelay(); } /// @notice Delay (in number of blocks) since the proposal starts until voting ends. function votingPeriod() public view override(IGovernorUpgradeable, GovernorSettingsUpgradeable) returns (uint256) { return super.votingPeriod(); } /// @notice Quorum required for a proposal to be successful. This function includes a blockNumber argument so /// the quorum can adapt through time function quorum(uint256 blockNumber) public view override(IGovernorUpgradeable, GovernorVotesQuorumFractionUpgradeable) returns (uint256) { return super.quorum(blockNumber); } /// @notice Current state of a proposal, see the { ProposalState } for details. function state(uint256 proposalId) public view override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (ProposalState) { return super.state(proposalId); } /// @notice Create a new proposal. Vote start votingDelay blocks after the proposal is created and ends /// votingPeriod blocks after the voting starts. Emits a ProposalCreated event. function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public override(GovernorUpgradeable, IGovernorUpgradeable) onlyProposerOrOpenRole returns (uint256) { Mnt(address(token)).updateTotalWeightCheckpoint(); return super.propose(targets, values, calldatas, description); } /// @notice The number of votes required in order for a voter to become a proposer function proposalThreshold() public view override(GovernorUpgradeable, GovernorSettingsUpgradeable) returns (uint256) { return super.proposalThreshold(); } function _execute( uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) { super._execute(proposalId, targets, values, calldatas, descriptionHash); } function cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public override(GovernorUpgradeable, IGovernorUpgradeable) onlyCanceller returns (uint256) { return _cancel(targets, values, calldatas, descriptionHash); } function _cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (uint256) { return super._cancel(targets, values, calldatas, descriptionHash); } function _executor() internal view override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (address) { return super._executor(); } function _castVote( uint256 proposalId, address account, uint8 support, string memory reason ) internal override returns (uint256) { Mnt(address(token)).updateVoteTimestamp(account); return super._castVote(proposalId, account, support, reason); } function supportsInterface(bytes4 interfaceId) public view override(GovernorUpgradeable, GovernorTimelockControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } }
contracts/interfaces/IWhitelist.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/access/IAccessControl.sol"; interface IWhitelist is IAccessControl { /** * @notice The given member was added to the whitelist */ event MemberAdded(address); /** * @notice The given member was removed from the whitelist */ event MemberRemoved(address); /** * @notice Protocol operation mode switched */ event WhitelistModeWasTurnedOff(); /** * @notice Amount of maxMembers changed */ event MaxMemberAmountChanged(uint256); /** * @notice get maximum number of members. * When membership reaches this number, no new members may join. */ function maxMembers() external view returns (uint256); /** * @notice get the total number of members stored in the map. */ function memberCount() external view returns (uint256); /** * @notice get protocol operation mode. */ function whitelistModeEnabled() external view returns (bool); /** * @notice get is account member of whitelist */ function accountMembership(address) external view returns (bool); /** * @notice get keccak-256 hash of GATEKEEPER role */ function GATEKEEPER() external view returns (bytes32); /** * @notice Add a new member to the whitelist. * @param newAccount The account that is being added to the whitelist. * @dev RESTRICTION: Gatekeeper only. */ function addMember(address newAccount) external; /** * @notice Remove a member from the whitelist. * @param accountToRemove The account that is being removed from the whitelist. * @dev RESTRICTION: Gatekeeper only. */ function removeMember(address accountToRemove) external; /** * @notice Disables whitelist mode and enables emission boost mode. * @dev RESTRICTION: Admin only. */ function turnOffWhitelistMode() external; /** * @notice Set a new threshold of participants. * @param newThreshold New number of participants. * @dev RESTRICTION: Gatekeeper only. */ function setMaxMembers(uint256 newThreshold) external; /** * @notice Check protocol operation mode. In whitelist mode, only members from whitelist and who have * EmissionBooster can work with protocol. * @param who The address of the account to check for participation. */ function isWhitelisted(address who) external view returns (bool); }
@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ```solidity * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ```solidity * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules} * to enforce additional security measures for this role. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `_msgSender()` is missing `role`. * Overriding this function changes the behavior of the {onlyRole} modifier. * * Format of the revert message is described in {_checkRole}. * * _Available since v4.6._ */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(account), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. * * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * May emit a {RoleGranted} event. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. * * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. * * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
@openzeppelin/contracts/token/ERC1155/IERC1155.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] calldata accounts, uint256[] calldata ids ) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; }
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
contracts/interfaces/IRewardsHub.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "./IRewardsHubLight.sol"; interface IRewardsHub is IRewardsHubLight { event RewardUnlocked(address account, uint256 amount); /** * @notice Gets summary amount of available and delayed balances of an account. */ function totalBalanceOf(address account) external view override returns (uint256); /** * @notice Gets part of delayed rewards that is unlocked and have become available. */ function getUnlockableRewards(address account) external view returns (uint256); }
contracts/interfaces/IInterconnector.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "./ISupervisor.sol"; import "./IRewardsHub.sol"; import "./IMnt.sol"; import "./IBuyback.sol"; import "./IVesting.sol"; import "./IMinterestNFT.sol"; import "./IPriceOracle.sol"; import "./ILiquidation.sol"; import "./IBDSystem.sol"; import "./IWeightAggregator.sol"; import "./IEmissionBooster.sol"; interface IInterconnector { function supervisor() external view returns (ISupervisor); function buyback() external view returns (IBuyback); function emissionBooster() external view returns (IEmissionBooster); function bdSystem() external view returns (IBDSystem); function rewardsHub() external view returns (IRewardsHub); function mnt() external view returns (IMnt); function minterestNFT() external view returns (IMinterestNFT); function liquidation() external view returns (ILiquidation); function oracle() external view returns (IPriceOracle); function vesting() external view returns (IVesting); function whitelist() external view returns (IWhitelist); function weightAggregator() external view returns (IWeightAggregator); }
@openzeppelin/contracts-upgradeable/interfaces/IERC5805Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5805.sol) pragma solidity ^0.8.0; import "../governance/utils/IVotesUpgradeable.sol"; import "./IERC6372Upgradeable.sol"; interface IERC5805Upgradeable is IERC6372Upgradeable, IVotesUpgradeable {}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; // EIP-2612 is Final as of 2022-11-01. This file is deprecated. import "./ERC20PermitUpgradeable.sol";
@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
@openzeppelin/contracts-upgradeable/governance/IGovernorUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (governance/IGovernor.sol) pragma solidity ^0.8.0; import "../interfaces/IERC165Upgradeable.sol"; import "../interfaces/IERC6372Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Interface of the {Governor} core. * * _Available since v4.3._ */ abstract contract IGovernorUpgradeable is Initializable, IERC165Upgradeable, IERC6372Upgradeable { function __IGovernor_init() internal onlyInitializing { } function __IGovernor_init_unchained() internal onlyInitializing { } enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /** * @dev Emitted when a proposal is created. */ event ProposalCreated( uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 voteStart, uint256 voteEnd, string description ); /** * @dev Emitted when a proposal is canceled. */ event ProposalCanceled(uint256 proposalId); /** * @dev Emitted when a proposal is executed. */ event ProposalExecuted(uint256 proposalId); /** * @dev Emitted when a vote is cast without params. * * Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used. */ event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason); /** * @dev Emitted when a vote is cast with params. * * Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used. * `params` are additional encoded parameters. Their interpepretation also depends on the voting module used. */ event VoteCastWithParams( address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason, bytes params ); /** * @notice module:core * @dev Name of the governor instance (used in building the ERC712 domain separator). */ function name() public view virtual returns (string memory); /** * @notice module:core * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" */ function version() public view virtual returns (string memory); /** * @notice module:core * @dev See {IERC6372} */ function clock() public view virtual override returns (uint48); /** * @notice module:core * @dev See EIP-6372. */ // solhint-disable-next-line func-name-mixedcase function CLOCK_MODE() public view virtual override returns (string memory); /** * @notice module:voting * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`. * * There are 2 standard keys: `support` and `quorum`. * * - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`. * - `quorum=bravo` means that only For votes are counted towards quorum. * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. * * If a counting module makes use of encoded `params`, it should include this under a `params` key with a unique * name that describes the behavior. For example: * * - `params=fractional` might refer to a scheme where votes are divided fractionally between for/against/abstain. * - `params=erc721` might refer to a scheme where specific NFTs are delegated to vote. * * NOTE: The string can be decoded by the standard * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] * JavaScript class. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public view virtual returns (string memory); /** * @notice module:core * @dev Hashing function used to (re)build the proposal id from the proposal details.. */ function hashProposal( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public pure virtual returns (uint256); /** * @notice module:core * @dev Current state of a proposal, following Compound's convention */ function state(uint256 proposalId) public view virtual returns (ProposalState); /** * @notice module:core * @dev Timepoint used to retrieve user's votes and quorum. If using block number (as per Compound's Comp), the * snapshot is performed at the end of this block. Hence, voting for this proposal starts at the beginning of the * following block. */ function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:core * @dev Timepoint at which votes close. If using block number, votes close at the end of this block, so it is * possible to cast a vote during this block. */ function proposalDeadline(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:core * @dev The account that created a proposal. */ function proposalProposer(uint256 proposalId) public view virtual returns (address); /** * @notice module:user-config * @dev Delay, between the proposal is created and the vote starts. The unit this duration is expressed in depends * on the clock (see EIP-6372) this contract uses. * * This can be increased to leave time for users to buy voting power, or delegate it, before the voting of a * proposal starts. */ function votingDelay() public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay between the vote start and vote end. The unit this duration is expressed in depends on the clock * (see EIP-6372) this contract uses. * * NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting * duration compared to the voting delay. */ function votingPeriod() public view virtual returns (uint256); /** * @notice module:user-config * @dev Minimum number of cast voted required for a proposal to be successful. * * NOTE: The `timepoint` parameter corresponds to the snapshot used for counting vote. This allows to scale the * quorum depending on values such as the totalSupply of a token at this timepoint (see {ERC20Votes}). */ function quorum(uint256 timepoint) public view virtual returns (uint256); /** * @notice module:reputation * @dev Voting power of an `account` at a specific `timepoint`. * * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or * multiple), {ERC20Votes} tokens. */ function getVotes(address account, uint256 timepoint) public view virtual returns (uint256); /** * @notice module:reputation * @dev Voting power of an `account` at a specific `timepoint` given additional encoded parameters. */ function getVotesWithParams( address account, uint256 timepoint, bytes memory params ) public view virtual returns (uint256); /** * @notice module:voting * @dev Returns whether `account` has cast a vote on `proposalId`. */ function hasVoted(uint256 proposalId, address account) public view virtual returns (bool); /** * @dev Create a new proposal. Vote start after a delay specified by {IGovernor-votingDelay} and lasts for a * duration specified by {IGovernor-votingPeriod}. * * Emits a {ProposalCreated} event. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual returns (uint256 proposalId); /** * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the * deadline to be reached. * * Emits a {ProposalExecuted} event. * * Note: some module can modify the requirements for execution, for example by adding an additional timelock. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual returns (uint256 proposalId); /** * @dev Cancel a proposal. A proposal is cancellable by the proposer, but only while it is Pending state, i.e. * before the vote starts. * * Emits a {ProposalCanceled} event. */ function cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public virtual returns (uint256 proposalId); /** * @dev Cast a vote * * Emits a {VoteCast} event. */ function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); /** * @dev Cast a vote with a reason * * Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual returns (uint256 balance); /** * @dev Cast a vote with a reason and additional encoded parameters * * Emits a {VoteCast} or {VoteCastWithParams} event depending on the length of params. */ function castVoteWithReasonAndParams( uint256 proposalId, uint8 support, string calldata reason, bytes memory params ) public virtual returns (uint256 balance); /** * @dev Cast a vote using the user's cryptographic signature. * * Emits a {VoteCast} event. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual returns (uint256 balance); /** * @dev Cast a vote with a reason and additional encoded parameters using the user's cryptographic signature. * * Emits a {VoteCast} or {VoteCastWithParams} event depending on the length of params. */ function castVoteWithReasonAndParamsBySig( uint256 proposalId, uint8 support, string calldata reason, bytes memory params, uint8 v, bytes32 r, bytes32 s ) public virtual returns (uint256 balance); /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); }
@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
@openzeppelin/contracts-upgradeable/governance/extensions/GovernorSettingsUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (governance/extensions/GovernorSettings.sol) pragma solidity ^0.8.0; import "../GovernorUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Extension of {Governor} for settings updatable through governance. * * _Available since v4.4._ */ abstract contract GovernorSettingsUpgradeable is Initializable, GovernorUpgradeable { uint256 private _votingDelay; uint256 private _votingPeriod; uint256 private _proposalThreshold; event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay); event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod); event ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold); /** * @dev Initialize the governance parameters. */ function __GovernorSettings_init(uint256 initialVotingDelay, uint256 initialVotingPeriod, uint256 initialProposalThreshold) internal onlyInitializing { __GovernorSettings_init_unchained(initialVotingDelay, initialVotingPeriod, initialProposalThreshold); } function __GovernorSettings_init_unchained(uint256 initialVotingDelay, uint256 initialVotingPeriod, uint256 initialProposalThreshold) internal onlyInitializing { _setVotingDelay(initialVotingDelay); _setVotingPeriod(initialVotingPeriod); _setProposalThreshold(initialProposalThreshold); } /** * @dev See {IGovernor-votingDelay}. */ function votingDelay() public view virtual override returns (uint256) { return _votingDelay; } /** * @dev See {IGovernor-votingPeriod}. */ function votingPeriod() public view virtual override returns (uint256) { return _votingPeriod; } /** * @dev See {Governor-proposalThreshold}. */ function proposalThreshold() public view virtual override returns (uint256) { return _proposalThreshold; } /** * @dev Update the voting delay. This operation can only be performed through a governance proposal. * * Emits a {VotingDelaySet} event. */ function setVotingDelay(uint256 newVotingDelay) public virtual onlyGovernance { _setVotingDelay(newVotingDelay); } /** * @dev Update the voting period. This operation can only be performed through a governance proposal. * * Emits a {VotingPeriodSet} event. */ function setVotingPeriod(uint256 newVotingPeriod) public virtual onlyGovernance { _setVotingPeriod(newVotingPeriod); } /** * @dev Update the proposal threshold. This operation can only be performed through a governance proposal. * * Emits a {ProposalThresholdSet} event. */ function setProposalThreshold(uint256 newProposalThreshold) public virtual onlyGovernance { _setProposalThreshold(newProposalThreshold); } /** * @dev Internal setter for the voting delay. * * Emits a {VotingDelaySet} event. */ function _setVotingDelay(uint256 newVotingDelay) internal virtual { emit VotingDelaySet(_votingDelay, newVotingDelay); _votingDelay = newVotingDelay; } /** * @dev Internal setter for the voting period. * * Emits a {VotingPeriodSet} event. */ function _setVotingPeriod(uint256 newVotingPeriod) internal virtual { // voting period must be at least one block long require(newVotingPeriod > 0, "GovernorSettings: voting period too low"); emit VotingPeriodSet(_votingPeriod, newVotingPeriod); _votingPeriod = newVotingPeriod; } /** * @dev Internal setter for the proposal threshold. * * Emits a {ProposalThresholdSet} event. */ function _setProposalThreshold(uint256 newProposalThreshold) internal virtual { emit ProposalThresholdSet(_proposalThreshold, newProposalThreshold); _proposalThreshold = newProposalThreshold; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[47] private __gap; }
@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } }
contracts/interfaces/ILiquidation.sol
// SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.17; import "@openzeppelin/contracts/access/IAccessControl.sol"; import "./IMToken.sol"; import "./ILinkageLeaf.sol"; import "./IPriceOracle.sol"; /** * This contract provides the liquidation functionality. */ interface ILiquidation is IAccessControl, ILinkageLeaf { event HealthyFactorLimitChanged(uint256 oldValue, uint256 newValue); event ReliableLiquidation( bool isDebtHealthy, address liquidator, address borrower, IMToken seizeMarket, IMToken repayMarket, uint256 seizeAmountUnderlying, uint256 repayAmountUnderlying ); /** * @dev Local accountState for avoiding stack-depth limits in calculating liquidation amounts. */ struct AccountLiquidationAmounts { uint256 accountTotalSupplyUsd; uint256 accountTotalCollateralUsd; uint256 accountPresumedTotalRepayUsd; uint256 accountTotalBorrowUsd; uint256 accountTotalCollateralUsdAfter; uint256 accountTotalBorrowUsdAfter; uint256 seizeAmount; } /** * @notice GET The maximum allowable value of a healthy factor after liquidation, scaled by 1e18 */ function healthyFactorLimit() external view returns (uint256); /** * @notice get keccak-256 hash of TRUSTED_LIQUIDATOR role */ function TRUSTED_LIQUIDATOR() external view returns (bytes32); /** * @notice get keccak-256 hash of TIMELOCK role */ function TIMELOCK() external view returns (bytes32); /** * @notice Liquidate insolvent debt position * @param seizeMarket Market from which the account's collateral will be seized * @param repayMarket Market from which the account's debt will be repaid * @param borrower Account which is being liquidated * @param repayAmount Amount of debt to be repaid * @return (seizeAmount, repayAmount) * @dev RESTRICTION: Trusted liquidator only */ function liquidateUnsafeLoan( IMToken seizeMarket, IMToken repayMarket, address borrower, uint256 repayAmount ) external returns (uint256, uint256); /** * @notice Accrues interest for repay and seize markets * @param seizeMarket Market from which the account's collateral will be seized * @param repayMarket Market from which the account's debt will be repaid */ function accrue(IMToken seizeMarket, IMToken repayMarket) external; /** * @notice Calculates account states: total balances, seize amount, new collateral and borrow state * @param account_ The address of the borrower * @param marketAddresses An array with addresses of markets where the debtor is in * @param seizeMarket Market from which the account's collateral will be seized * @param repayMarket Market from which the account's debt will be repaid * @param repayAmount Amount of debt to be repaid * @return accountState Struct that contains all balance parameters */ function calculateLiquidationAmounts( address account_, IMToken[] memory marketAddresses, IMToken seizeMarket, IMToken repayMarket, uint256 repayAmount ) external view returns (AccountLiquidationAmounts memory); /** * @notice Sets a new value for healthyFactorLimit * @dev RESTRICTION: Timelock only */ function setHealthyFactorLimit(uint256 newValue_) external; }
Compiler Settings
{"outputSelection":{"*":{"*":["*"],"":["*"]}},"optimizer":{"runs":200,"enabled":true},"metadata":{"useLiteralContent":true},"libraries":{}}
Contract ABI
[{"type":"error","name":"Empty","inputs":[]},{"type":"event","name":"EIP712DomainChanged","inputs":[],"anonymous":false},{"type":"event","name":"Initialized","inputs":[{"type":"uint8","name":"version","internalType":"uint8","indexed":false}],"anonymous":false},{"type":"event","name":"ProposalCanceled","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ProposalCreated","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256","indexed":false},{"type":"address","name":"proposer","internalType":"address","indexed":false},{"type":"address[]","name":"targets","internalType":"address[]","indexed":false},{"type":"uint256[]","name":"values","internalType":"uint256[]","indexed":false},{"type":"string[]","name":"signatures","internalType":"string[]","indexed":false},{"type":"bytes[]","name":"calldatas","internalType":"bytes[]","indexed":false},{"type":"uint256","name":"voteStart","internalType":"uint256","indexed":false},{"type":"uint256","name":"voteEnd","internalType":"uint256","indexed":false},{"type":"string","name":"description","internalType":"string","indexed":false}],"anonymous":false},{"type":"event","name":"ProposalExecuted","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ProposalQueued","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256","indexed":false},{"type":"uint256","name":"eta","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ProposalThresholdSet","inputs":[{"type":"uint256","name":"oldProposalThreshold","internalType":"uint256","indexed":false},{"type":"uint256","name":"newProposalThreshold","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"QuorumNumeratorUpdated","inputs":[{"type":"uint256","name":"oldQuorumNumerator","internalType":"uint256","indexed":false},{"type":"uint256","name":"newQuorumNumerator","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"TimelockChange","inputs":[{"type":"address","name":"oldTimelock","internalType":"address","indexed":false},{"type":"address","name":"newTimelock","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"VoteCast","inputs":[{"type":"address","name":"voter","internalType":"address","indexed":true},{"type":"uint256","name":"proposalId","internalType":"uint256","indexed":false},{"type":"uint8","name":"support","internalType":"uint8","indexed":false},{"type":"uint256","name":"weight","internalType":"uint256","indexed":false},{"type":"string","name":"reason","internalType":"string","indexed":false}],"anonymous":false},{"type":"event","name":"VoteCastWithParams","inputs":[{"type":"address","name":"voter","internalType":"address","indexed":true},{"type":"uint256","name":"proposalId","internalType":"uint256","indexed":false},{"type":"uint8","name":"support","internalType":"uint8","indexed":false},{"type":"uint256","name":"weight","internalType":"uint256","indexed":false},{"type":"string","name":"reason","internalType":"string","indexed":false},{"type":"bytes","name":"params","internalType":"bytes","indexed":false}],"anonymous":false},{"type":"event","name":"VotingDelaySet","inputs":[{"type":"uint256","name":"oldVotingDelay","internalType":"uint256","indexed":false},{"type":"uint256","name":"newVotingDelay","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"VotingPeriodSet","inputs":[{"type":"uint256","name":"oldVotingPeriod","internalType":"uint256","indexed":false},{"type":"uint256","name":"newVotingPeriod","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"BALLOT_TYPEHASH","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"CANCELLER_ROLE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"CLOCK_MODE","inputs":[]},{"type":"function","stateMutability":"pure","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"COUNTING_MODE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"EXTENDED_BALLOT_TYPEHASH","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"PROPOSER_ROLE","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"cancel","inputs":[{"type":"address[]","name":"targets","internalType":"address[]"},{"type":"uint256[]","name":"values","internalType":"uint256[]"},{"type":"bytes[]","name":"calldatas","internalType":"bytes[]"},{"type":"bytes32","name":"descriptionHash","internalType":"bytes32"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"castVote","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"},{"type":"uint8","name":"support","internalType":"uint8"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"castVoteBySig","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"},{"type":"uint8","name":"support","internalType":"uint8"},{"type":"uint8","name":"v","internalType":"uint8"},{"type":"bytes32","name":"r","internalType":"bytes32"},{"type":"bytes32","name":"s","internalType":"bytes32"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"castVoteWithReason","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"},{"type":"uint8","name":"support","internalType":"uint8"},{"type":"string","name":"reason","internalType":"string"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"castVoteWithReasonAndParams","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"},{"type":"uint8","name":"support","internalType":"uint8"},{"type":"string","name":"reason","internalType":"string"},{"type":"bytes","name":"params","internalType":"bytes"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"castVoteWithReasonAndParamsBySig","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"},{"type":"uint8","name":"support","internalType":"uint8"},{"type":"string","name":"reason","internalType":"string"},{"type":"bytes","name":"params","internalType":"bytes"},{"type":"uint8","name":"v","internalType":"uint8"},{"type":"bytes32","name":"r","internalType":"bytes32"},{"type":"bytes32","name":"s","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint48","name":"","internalType":"uint48"}],"name":"clock","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes1","name":"fields","internalType":"bytes1"},{"type":"string","name":"name","internalType":"string"},{"type":"string","name":"version","internalType":"string"},{"type":"uint256","name":"chainId","internalType":"uint256"},{"type":"address","name":"verifyingContract","internalType":"address"},{"type":"bytes32","name":"salt","internalType":"bytes32"},{"type":"uint256[]","name":"extensions","internalType":"uint256[]"}],"name":"eip712Domain","inputs":[]},{"type":"function","stateMutability":"payable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"execute","inputs":[{"type":"address[]","name":"targets","internalType":"address[]"},{"type":"uint256[]","name":"values","internalType":"uint256[]"},{"type":"bytes[]","name":"calldatas","internalType":"bytes[]"},{"type":"bytes32","name":"descriptionHash","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"getVotes","inputs":[{"type":"address","name":"account","internalType":"address"},{"type":"uint256","name":"timepoint","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"getVotesWithParams","inputs":[{"type":"address","name":"account","internalType":"address"},{"type":"uint256","name":"timepoint","internalType":"uint256"},{"type":"bytes","name":"params","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"hasVoted","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"pure","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"hashProposal","inputs":[{"type":"address[]","name":"targets","internalType":"address[]"},{"type":"uint256[]","name":"values","internalType":"uint256[]"},{"type":"bytes[]","name":"calldatas","internalType":"bytes[]"},{"type":"bytes32","name":"descriptionHash","internalType":"bytes32"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initialize","inputs":[{"type":"address","name":"_token","internalType":"contract IVotesUpgradeable"},{"type":"address","name":"_timelock","internalType":"contract TimelockControllerUpgradeable"},{"type":"uint256","name":"initialVotingDelay","internalType":"uint256"},{"type":"uint256","name":"initialVotingPeriod","internalType":"uint256"},{"type":"uint256","name":"initialProposalThreshold","internalType":"uint256"},{"type":"uint256","name":"quorumNumeratorValue","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"name","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bytes4","name":"","internalType":"bytes4"}],"name":"onERC1155BatchReceived","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"address","name":"","internalType":"address"},{"type":"uint256[]","name":"","internalType":"uint256[]"},{"type":"uint256[]","name":"","internalType":"uint256[]"},{"type":"bytes","name":"","internalType":"bytes"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bytes4","name":"","internalType":"bytes4"}],"name":"onERC1155Received","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"address","name":"","internalType":"address"},{"type":"uint256","name":"","internalType":"uint256"},{"type":"uint256","name":"","internalType":"uint256"},{"type":"bytes","name":"","internalType":"bytes"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bytes4","name":"","internalType":"bytes4"}],"name":"onERC721Received","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"address","name":"","internalType":"address"},{"type":"uint256","name":"","internalType":"uint256"},{"type":"bytes","name":"","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"proposalDeadline","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"proposalEta","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"proposalProposer","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"proposalSnapshot","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"proposalThreshold","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"againstVotes","internalType":"uint256"},{"type":"uint256","name":"forVotes","internalType":"uint256"},{"type":"uint256","name":"abstainVotes","internalType":"uint256"}],"name":"proposalVotes","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"propose","inputs":[{"type":"address[]","name":"targets","internalType":"address[]"},{"type":"uint256[]","name":"values","internalType":"uint256[]"},{"type":"bytes[]","name":"calldatas","internalType":"bytes[]"},{"type":"string","name":"description","internalType":"string"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"queue","inputs":[{"type":"address[]","name":"targets","internalType":"address[]"},{"type":"uint256[]","name":"values","internalType":"uint256[]"},{"type":"bytes[]","name":"calldatas","internalType":"bytes[]"},{"type":"bytes32","name":"descriptionHash","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"quorum","inputs":[{"type":"uint256","name":"blockNumber","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"quorumDenominator","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"quorumNumerator","inputs":[{"type":"uint256","name":"timepoint","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"quorumNumerator","inputs":[]},{"type":"function","stateMutability":"payable","outputs":[],"name":"relay","inputs":[{"type":"address","name":"target","internalType":"address"},{"type":"uint256","name":"value","internalType":"uint256"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setProposalThreshold","inputs":[{"type":"uint256","name":"newProposalThreshold","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setVotingDelay","inputs":[{"type":"uint256","name":"newVotingDelay","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setVotingPeriod","inputs":[{"type":"uint256","name":"newVotingPeriod","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint8","name":"","internalType":"enum IGovernorUpgradeable.ProposalState"}],"name":"state","inputs":[{"type":"uint256","name":"proposalId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"supportsInterface","inputs":[{"type":"bytes4","name":"interfaceId","internalType":"bytes4"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"timelock","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IERC5805Upgradeable"}],"name":"token","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"updateQuorumNumerator","inputs":[{"type":"uint256","name":"newQuorumNumerator","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"updateTimelock","inputs":[{"type":"address","name":"newTimelock","internalType":"contract TimelockControllerUpgradeable"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"version","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"votingDelay","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"votingPeriod","inputs":[]},{"type":"receive","stateMutability":"payable"}]
Contract Creation Code
0x60806040523480156200001157600080fd5b506200001c62000022565b620000e3565b600054610100900460ff16156200008f5760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff90811614620000e1576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b614ec380620000f36000396000f3fe6080604052600436106102b25760003560e01c80637d5e81e211610175578063bc197c81116100dc578063deaaa7cc11610095578063ece40cc11161006f578063ece40cc114610a1f578063f23a6e6114610a3f578063f8ce560a14610a6b578063fc0c546a14610a8b57600080fd5b8063deaaa7cc146109ab578063ea0217cf146109df578063eb9019d4146109ff57600080fd5b8063bc197c81146108ae578063c01f9e37146108da578063c28bc2fa14610913578063c59057e414610926578063d33219b414610946578063dd4e2ba51461096557600080fd5b80639a802a6d1161012e5780639a802a6d146107f0578063a7713a7014610810578063a890c91014610825578063ab58fb8e14610845578063b08e51c014610865578063b58131b01461089957600080fd5b80637d5e81e21461071457806384b0196e1461073457806386489ba91461075c5780638f61f4f51461077c57806391ddadf4146107b057806397c3d334146107dc57600080fd5b80633bccf4fd1161021957806354fd4d50116101d257806354fd4d501461064a57806356781388146106745780635f398a141461069457806360c4247f146106b457806370b0f660146106d45780637b3c71d3146106f457600080fd5b80633bccf4fd146105275780633e4f49e6146105475780634385963214610574578063452115d6146105bf5780634bf5d7e9146105df578063544ffc9c146105f457600080fd5b8063150b7a021161026b578063150b7a0214610431578063160cbed7146104755780632656227d146104955780632d63f693146104a85780632fe3e261146104de5780633932abb11461051257600080fd5b806301ffc9a71461032257806302a251a314610357578063034201811461037a57806306f3f9e61461039a57806306fdde03146103ba578063143489d0146103dc57600080fd5b3661031d57306102c0610aac565b6001600160a01b03161461031b5760405162461bcd60e51b815260206004820152601f60248201527f476f7665726e6f723a206d7573742073656e6420746f206578656375746f720060448201526064015b60405180910390fd5b005b600080fd5b34801561032e57600080fd5b5061034261033d366004613d88565b610ac6565b60405190151581526020015b60405180910390f35b34801561036357600080fd5b5061036c610ad7565b60405190815260200161034e565b34801561038657600080fd5b5061036c610395366004613ed6565b610ae3565b3480156103a657600080fd5b5061031b6103b5366004613f7c565b610bdb565b3480156103c657600080fd5b506103cf610c65565b60405161034e9190613fe5565b3480156103e857600080fd5b506104196103f7366004613f7c565b600090815260fe6020526040902054600160401b90046001600160a01b031690565b6040516001600160a01b03909116815260200161034e565b34801561043d57600080fd5b5061045c61044c36600461400d565b630a85bd0160e11b949350505050565b6040516001600160e01b0319909116815260200161034e565b34801561048157600080fd5b5061036c6104903660046141e4565b610cf7565b61036c6104a33660046141e4565b610efc565b3480156104b457600080fd5b5061036c6104c3366004613f7c565b600090815260fe60205260409020546001600160401b031690565b3480156104ea57600080fd5b5061036c7fb3b3f3b703cd84ce352197dcff232b1b5d3cfb2025ce47cf04742d0651f1af8881565b34801561051e57600080fd5b5061036c610fee565b34801561053357600080fd5b5061036c610542366004614273565b610ffa565b34801561055357600080fd5b50610567610562366004613f7c565b611070565b60405161034e91906142d7565b34801561058057600080fd5b5061034261058f3660046142ff565b6000828152610161602090815260408083206001600160a01b038516845260030190915290205460ff1692915050565b3480156105cb57600080fd5b5061036c6105da3660046141e4565b61107b565b3480156105eb57600080fd5b506103cf611174565b34801561060057600080fd5b5061062f61060f366004613f7c565b600090815261016160205260409020805460018201546002909201549092565b6040805193845260208401929092529082015260600161034e565b34801561065657600080fd5b506040805180820190915260018152603160f81b60208201526103cf565b34801561068057600080fd5b5061036c61068f36600461432f565b611221565b3480156106a057600080fd5b5061036c6106af36600461435b565b61124a565b3480156106c057600080fd5b5061036c6106cf366004613f7c565b611294565b3480156106e057600080fd5b5061031b6106ef366004613f7c565b611349565b34801561070057600080fd5b5061036c61070f3660046143de565b6113d0565b34801561072057600080fd5b5061036c61072f366004614437565b611418565b34801561074057600080fd5b50610749611605565b60405161034e9796959493929190614526565b34801561076857600080fd5b5061031b610777366004614588565b6116a3565b34801561078857600080fd5b5061036c7fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc181565b3480156107bc57600080fd5b506107c561180c565b60405165ffffffffffff909116815260200161034e565b3480156107e857600080fd5b50606461036c565b3480156107fc57600080fd5b5061036c61080b3660046145e1565b611895565b34801561081c57600080fd5b5061036c6118ac565b34801561083157600080fd5b5061031b610840366004614639565b6118d9565b34801561085157600080fd5b5061036c610860366004613f7c565b611960565b34801561087157600080fd5b5061036c7ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f78381565b3480156108a557600080fd5b5061036c6119fc565b3480156108ba57600080fd5b5061045c6108c9366004614656565b63bc197c8160e01b95945050505050565b3480156108e657600080fd5b5061036c6108f5366004613f7c565b600090815260fe60205260409020600101546001600160401b031690565b61031b6109213660046146e9565b611a08565b34801561093257600080fd5b5061036c6109413660046141e4565b611b0e565b34801561095257600080fd5b506101f8546001600160a01b0316610419565b34801561097157600080fd5b506040805180820190915260208082527f737570706f72743d627261766f2671756f72756d3d666f722c6162737461696e908201526103cf565b3480156109b757600080fd5b5061036c7f150214d74d59b7d1e90c73fc22ef3d991dd0a76b046543d4d80ab92d2a50328f81565b3480156109eb57600080fd5b5061031b6109fa366004613f7c565b611b48565b348015610a0b57600080fd5b5061036c610a1a36600461472c565b611bcf565b348015610a2b57600080fd5b5061031b610a3a366004613f7c565b611bf0565b348015610a4b57600080fd5b5061045c610a5a366004614758565b63f23a6e6160e01b95945050505050565b348015610a7757600080fd5b5061036c610a86366004613f7c565b611c77565b348015610a9757600080fd5b5061019354610419906001600160a01b031681565b6000610ac16101f8546001600160a01b031690565b905090565b6000610ad182611c82565b92915050565b6000610ac16101305490565b600080610b87610b7f7fb3b3f3b703cd84ce352197dcff232b1b5d3cfb2025ce47cf04742d0651f1af888c8c8c8c604051610b1f9291906147c0565b60405180910390208b80519060200120604051602001610b64959493929190948552602085019390935260ff9190911660408401526060830152608082015260a00190565b60405160208183030381529060405280519060200120611ca7565b868686611cd4565b9050610bcd8a828b8b8b8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152508d9250611cf2915050565b9a9950505050505050505050565b610be3610aac565b6001600160a01b0316336001600160a01b031614610c135760405162461bcd60e51b8152600401610312906147d0565b30610c1c610aac565b6001600160a01b031614610c595760008036604051610c3c9291906147c0565b604051809103902090505b80610c5260ff611e47565b03610c4757505b610c6281611ec6565b50565b606060fd8054610c7490614807565b80601f0160208091040260200160405190810160405280929190818152602001828054610ca090614807565b8015610ced5780601f10610cc257610100808354040283529160200191610ced565b820191906000526020600020905b815481529060010190602001808311610cd057829003601f168201915b5050505050905090565b600080610d0686868686611b0e565b90506004610d1382611070565b6007811115610d2457610d246142c1565b14610d415760405162461bcd60e51b815260040161031290614841565b6101f8546040805163793d064960e11b815290516000926001600160a01b03169163f27a0c929160048083019260209291908290030181865afa158015610d8c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610db09190614882565b6101f85460405163b1c5f42760e01b81529192506001600160a01b03169063b1c5f42790610deb908a908a908a906000908b9060040161492c565b602060405180830381865afa158015610e08573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e2c9190614882565b60008381526101f96020526040808220929092556101f85491516308f2a0bb60e41b81526001600160a01b0390921691638f2a0bb091610e79918b918b918b91908b90899060040161497a565b600060405180830381600087803b158015610e9357600080fd5b505af1158015610ea7573d6000803e3d6000fd5b505050507f9a2e42fd6722813d69113e7d0079d3d940171428df7373df9c7f7617cfda2892828242610ed991906149e8565b604080519283526020830191909152015b60405180910390a15095945050505050565b600080610f0b86868686611b0e565b90506000610f1882611070565b90506004816007811115610f2e57610f2e6142c1565b1480610f4b57506005816007811115610f4957610f496142c1565b145b610f675760405162461bcd60e51b815260040161031290614841565b600082815260fe602052604090819020600201805460ff19166001179055517f712ae1383f79ac853f8d882153778e0260ef8f03b504e2866e0593e04d2b291f90610fb59084815260200190565b60405180910390a1610fca8288888888612037565b610fd782888888886120d9565b610fe482888888886120e6565b5095945050505050565b6000610ac161012f5490565b604080517f150214d74d59b7d1e90c73fc22ef3d991dd0a76b046543d4d80ab92d2a50328f602082015290810186905260ff85166060820152600090819061104890610b7f90608001610b64565b90506110658782886040518060200160405280600081525061211f565b979650505050505050565b6000610ad182612195565b6000806110916101f8546001600160a01b031690565b604051632474521560e21b81527ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f78360048201523360248201529091506001600160a01b038216906391d1485490604401602060405180830381865afa1580156110fe573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061112291906149fb565b604051806040016040528060048152602001632298981960e11b8152509061115d5760405162461bcd60e51b81526004016103129190613fe5565b5061116a868686866122e2565b9695505050505050565b6101935460408051634bf5d7e960e01b815290516060926001600160a01b031691634bf5d7e99160048083019260009291908290030181865afa9250505080156111e057506040513d6000823e601f3d908101601f191682016040526111dd9190810190614a1d565b60015b61121c575060408051808201909152601d81527f6d6f64653d626c6f636b6e756d6265722666726f6d3d64656661756c74000000602082015290565b919050565b6000803390506112428482856040518060200160405280600081525061211f565b949350505050565b60008033905061106587828888888080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152508a9250611cf2915050565b6101c7546000908082036112ad5750506101c654919050565b60006101c76112bd600184614a8a565b815481106112cd576112cd614a9d565b60009182526020918290206040805180820190915291015463ffffffff8116808352600160201b9091046001600160e01b0316928201929092529150841061132357602001516001600160e01b03169392505050565b61133861132f856122f0565b6101c790612359565b6001600160e01b0316949350505050565b611351610aac565b6001600160a01b0316336001600160a01b0316146113815760405162461bcd60e51b8152600401610312906147d0565b3061138a610aac565b6001600160a01b0316146113c757600080366040516113aa9291906147c0565b604051809103902090505b806113c060ff611e47565b036113b557505b610c628161240c565b60008033905061116a86828787878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061211f92505050565b60008061142e6101f8546001600160a01b031690565b604051632474521560e21b81527fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc160048201523360248201529091506001600160a01b038216906391d1485490604401602060405180830381865afa15801561149b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114bf91906149fb565b806115545750604051632474521560e21b81527fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc16004820152600060248201526001600160a01b038216906391d1485490604401602060405180830381865afa158015611530573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061155491906149fb565b604051806040016040528060048152602001632298981960e11b8152509061158f5760405162461bcd60e51b81526004016103129190613fe5565b5061019360009054906101000a90046001600160a01b03166001600160a01b03166360c22cdd6040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156115e157600080fd5b505af11580156115f5573d6000803e3d6000fd5b5050505061116a8686868661244f565b6000606080600080600060606065546000801b1480156116255750606654155b6116695760405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b6044820152606401610312565b611671612828565b611679612837565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b600054610100900460ff16158080156116c35750600054600160ff909116105b806116dd5750303b1580156116dd575060005460ff166001145b6117405760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610312565b6000805460ff191660011790558015611763576000805461ff0019166101001790555b61178f6040518060400160405280600b81526020016a26b73a23b7bb32b93737b960a91b815250612846565b61179a85858561289d565b6117a26128d4565b6117ab876128fd565b6117b48261292d565b6117bd8661295d565b8015611803576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b50505050505050565b6000610ac17316700900000000000000000000000000000100016001600160a01b03166333d5ac9b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611863573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118879190614ab3565b6001600160401b031661298d565b60006118a28484846129f4565b90505b9392505050565b6101c754600090156118d1576118c36101c7612a6b565b6001600160e01b0316905090565b506101c65490565b6118e1610aac565b6001600160a01b0316336001600160a01b0316146119115760405162461bcd60e51b8152600401610312906147d0565b3061191a610aac565b6001600160a01b031614611957576000803660405161193a9291906147c0565b604051809103902090505b8061195060ff611e47565b0361194557505b610c6281612a9b565b6101f85460008281526101f9602052604080822054905163d45c443560e01b81526004810191909152909182916001600160a01b039091169063d45c443590602401602060405180830381865afa1580156119bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119e39190614882565b9050806001146119f357806118a5565b60009392505050565b6000610ac16101315490565b611a10610aac565b6001600160a01b0316336001600160a01b031614611a405760405162461bcd60e51b8152600401610312906147d0565b30611a49610aac565b6001600160a01b031614611a865760008036604051611a699291906147c0565b604051809103902090505b80611a7f60ff611e47565b03611a7457505b600080856001600160a01b0316858585604051611aa49291906147c0565b60006040518083038185875af1925050503d8060008114611ae1576040519150601f19603f3d011682016040523d82523d6000602084013e611ae6565b606091505b50915091506118038282604051806060016040528060288152602001614e6660289139612b06565b600084848484604051602001611b279493929190614adc565b60408051601f19818403018152919052805160209091012095945050505050565b611b50610aac565b6001600160a01b0316336001600160a01b031614611b805760405162461bcd60e51b8152600401610312906147d0565b30611b89610aac565b6001600160a01b031614611bc65760008036604051611ba99291906147c0565b604051809103902090505b80611bbf60ff611e47565b03611bb457505b610c6281612b1f565b60006118a58383611beb60408051602081019091526000815290565b6129f4565b611bf8610aac565b6001600160a01b0316336001600160a01b031614611c285760405162461bcd60e51b8152600401610312906147d0565b30611c31610aac565b6001600160a01b031614611c6e5760008036604051611c519291906147c0565b604051809103902090505b80611c6760ff611e47565b03611c5c57505b610c6281612bc2565b6000610ad182612c05565b60006001600160e01b03198216636e665ced60e01b1480610ad15750610ad182612c94565b6000610ad1611cb4612d30565b8360405161190160f01b8152600281019290925260228201526042902090565b6000806000611ce587878787612d3a565b91509150610fe481612dfe565b600085815260fe602052604081206001611d0b88611070565b6007811115611d1c57611d1c6142c1565b14611d755760405162461bcd60e51b815260206004820152602360248201527f476f7665726e6f723a20766f7465206e6f742063757272656e746c792061637460448201526269766560e81b6064820152608401610312565b8054600090611d8f9088906001600160401b0316866129f4565b9050611d9e8888888488612f48565b8351600003611df357866001600160a01b03167fb8e138887d0aa13bab447e82de9d5c1777041ecd21ca36ba824ff1e6c07ddda489888489604051611de69493929190614b27565b60405180910390a2611065565b866001600160a01b03167fe2babfbac5889a709b63bb7f598b324e08bc5a4fb9ec647fb3cbc9ec07eb87128988848989604051611e34959493929190614b4f565b60405180910390a2979650505050505050565b6000611e628254600f81810b600160801b909204900b131590565b15611e8057604051631ed9509560e11b815260040160405180910390fd5b508054600f0b6000818152600180840160205260408220805492905583546fffffffffffffffffffffffffffffffff191692016001600160801b03169190911790915590565b6064811115611f495760405162461bcd60e51b815260206004820152604360248201527f476f7665726e6f72566f74657351756f72756d4672616374696f6e3a2071756f60448201527f72756d4e756d657261746f72206f7665722071756f72756d44656e6f6d696e616064820152623a37b960e91b608482015260a401610312565b6000611f536118ac565b90508015801590611f6557506101c754155b15611fca5760408051808201909152600081526101c79060208101611f89846130c3565b6001600160e01b039081169091528254600181018455600093845260209384902083519490930151909116600160201b0263ffffffff909316929092179101555b611ff8611fe5611fd861180c565b65ffffffffffff166122f0565b611fee846130c3565b6101c7919061312c565b505060408051828152602081018490527f0553476bf02ef2726e8ce5ced78d63e26e602e4a2257b1f559418e24b4633997910160405180910390a15050565b30612040610aac565b6001600160a01b0316146120d25760005b84518110156120d057306001600160a01b031685828151811061207657612076614a9d565b60200260200101516001600160a01b0316036120c0576120c08382815181106120a1576120a1614a9d565b60200260200101518051906020012060ff61314790919063ffffffff16565b6120c981614b95565b9050612051565b505b5050505050565b6120d28585858585613183565b306120ef610aac565b6001600160a01b0316146120d25760ff54600f81810b600160801b909204900b13156120d257600060ff556120d2565b610193546040516329cfb1f960e01b81526001600160a01b03858116600483015260009216906329cfb1f990602401600060405180830381600087803b15801561216857600080fd5b505af115801561217c573d6000803e3d6000fd5b5050505061218c858585856131f8565b95945050505050565b6000806121a18361321b565b905060048160078111156121b7576121b76142c1565b146121c25792915050565b60008381526101f96020526040902054806121de575092915050565b6101f854604051632ab0f52960e01b8152600481018390526001600160a01b0390911690632ab0f52990602401602060405180830381865afa158015612228573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061224c91906149fb565b1561225b575060079392505050565b6101f854604051632c258a9f60e11b8152600481018390526001600160a01b039091169063584b153e90602401602060405180830381865afa1580156122a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122c991906149fb565b156122d8575060059392505050565b5060029392505050565b600061218c8585858561335c565b600063ffffffff8211156123555760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203360448201526532206269747360d01b6064820152608401610312565b5090565b8154600090818160058111156123b657600061237484613412565b61237e9085614a8a565b60008881526020902090915081015463ffffffff90811690871610156123a6578091506123b4565b6123b18160016149e8565b92505b505b60006123c4878785856134fa565b905080156123ff576123e9876123db600184614a8a565b600091825260209091200190565b54600160201b90046001600160e01b0316611065565b6000979650505050505050565b61012f5460408051918252602082018390527fc565b045403dc03c2eea82b81a0465edad9e2e7fc4d97e11421c209da93d7a93910160405180910390a161012f55565b60003361245c8184613558565b6124a85760405162461bcd60e51b815260206004820152601d60248201527f476f7665726e6f723a2070726f706f73657220726573747269637465640000006044820152606401610312565b60006124b261180c565b65ffffffffffff1690506124c46119fc565b6124d383610a1a600185614a8a565b101561253b5760405162461bcd60e51b815260206004820152603160248201527f476f7665726e6f723a2070726f706f73657220766f7465732062656c6f7720706044820152701c9bdc1bdcd85b081d1a1c995cda1bdb19607a1b6064820152608401610312565b60006125508888888880519060200120611b0e565b905086518851146125735760405162461bcd60e51b815260040161031290614bae565b85518851146125945760405162461bcd60e51b815260040161031290614bae565b60008851116125e55760405162461bcd60e51b815260206004820152601860248201527f476f7665726e6f723a20656d7074792070726f706f73616c00000000000000006044820152606401610312565b600081815260fe60205260409020546001600160401b0316156126545760405162461bcd60e51b815260206004820152602160248201527f476f7665726e6f723a2070726f706f73616c20616c72656164792065786973746044820152607360f81b6064820152608401610312565b600061265e610fee565b61266890846149e8565b90506000612674610ad7565b61267e90836149e8565b90506040518060e0016040528061269484613649565b6001600160401b031681526001600160a01b0387166020820152600060408201526060016126c183613649565b6001600160401b039081168252600060208084018290526040808501839052606094850183905288835260fe8252918290208551815492870151878501519186166001600160e01b031990941693909317600160401b6001600160a01b039094168402176001600160e01b0316600160e01b60e09290921c91909102178155938501516080860151908416921c0217600183015560a08301516002909201805460c09094015161ffff1990941692151561ff00191692909217610100931515939093029290921790558a517f7d84a6263ae0d98d3329bd7b46bb4e8d6f98cd35a7adb45c274c8b7fd5ebd5e091859188918e918e918111156127c5576127c5613e0b565b6040519080825280602002602001820160405280156127f857816020015b60608152602001906001900390816127e35790505b508d88888f60405161281299989796959493929190614bef565b60405180910390a1509098975050505050505050565b606060678054610c7490614807565b606060688054610c7490614807565b600054610100900460ff1661286d5760405162461bcd60e51b815260040161031290614cc6565b6128948161288f6040805180820190915260018152603160f81b602082015290565b6136b1565b610c6281613700565b600054610100900460ff166128c45760405162461bcd60e51b815260040161031290614cc6565b6128cf838383613737565b505050565b600054610100900460ff166128fb5760405162461bcd60e51b815260040161031290614cc6565b565b600054610100900460ff166129245760405162461bcd60e51b815260040161031290614cc6565b610c6281613779565b600054610100900460ff166129545760405162461bcd60e51b815260040161031290614cc6565b610c62816137c3565b600054610100900460ff166129845760405162461bcd60e51b815260040161031290614cc6565b610c62816137ea565b600065ffffffffffff8211156123555760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203460448201526538206269747360d01b6064820152608401610312565b61019354604051630748d63560e31b81526001600160a01b038581166004830152602482018590526000921690633a46b1a890604401602060405180830381865afa158015612a47573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118a29190614882565b805460009080156119f357612a85836123db600184614a8a565b54600160201b90046001600160e01b03166118a5565b6101f854604080516001600160a01b03928316815291831660208301527f08f74ea46ef7894f65eabfb5e6e695de773a000b47c529ab559178069b226401910160405180910390a16101f880546001600160a01b0319166001600160a01b0392909216919091179055565b60608315612b155750816118a5565b6118a58383613811565b60008111612b7f5760405162461bcd60e51b815260206004820152602760248201527f476f7665726e6f7253657474696e67733a20766f74696e6720706572696f6420604482015266746f6f206c6f7760c81b6064820152608401610312565b6101305460408051918252602082018390527f7e3f7f0708a84de9203036abaa450dccc85ad5ff52f78c170f3edb55cf5e8828910160405180910390a161013055565b6101315460408051918252602082018390527fccb45da8d5717e6c4544694297c4ba5cf151d455c9bb0ed4fc7a38411bc05461910160405180910390a161013155565b60006064612c1283611294565b61019354604051632394e7a360e21b8152600481018690526001600160a01b0390911690638e539e8c90602401602060405180830381865afa158015612c5c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c809190614882565b612c8a9190614d11565b610ad19190614d3e565b600063288ace0360e11b6318df743f60e31b63bf26d89760e01b6379dd796f60e01b6001600160e01b03198616821480612cda57506001600160e01b0319868116908216145b80612cf157506001600160e01b0319868116908516145b80612d0c57506001600160e01b03198616630271189760e51b145b8061116a57506301ffc9a760e01b6001600160e01b03198716149695505050505050565b6000610ac161383b565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0831115612d715750600090506003612df5565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa158015612dc5573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116612dee57600060019250925050612df5565b9150600090505b94509492505050565b6000816004811115612e1257612e126142c1565b03612e1a5750565b6001816004811115612e2e57612e2e6142c1565b03612e7b5760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401610312565b6002816004811115612e8f57612e8f6142c1565b03612edc5760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401610312565b6003816004811115612ef057612ef06142c1565b03610c625760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401610312565b6000858152610161602090815260408083206001600160a01b0388168452600381019092529091205460ff1615612fd15760405162461bcd60e51b815260206004820152602760248201527f476f7665726e6f72566f74696e6753696d706c653a20766f746520616c726561604482015266191e4818d85cdd60ca1b6064820152608401610312565b6001600160a01b03851660009081526003820160205260409020805460ff1916600117905560ff841661301d578281600001600082825461301291906149e8565b909155506120d09050565b60001960ff85160161303d578281600101600082825461301291906149e8565b60011960ff85160161305d578281600201600082825461301291906149e8565b60405162461bcd60e51b815260206004820152603560248201527f476f7665726e6f72566f74696e6753696d706c653a20696e76616c69642076616044820152746c756520666f7220656e756d20566f74655479706560581b6064820152608401610312565b60006001600160e01b038211156123555760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20326044820152663234206269747360c81b6064820152608401610312565b60008061313a8585856138af565b915091505b935093915050565b8154600160801b90819004600f0b6000818152600180860160205260409091209390935583546001600160801b03908116939091011602179055565b6101f85460405163e38335e560e01b81526001600160a01b039091169063e38335e59034906131bf90889088908890600090899060040161492c565b6000604051808303818588803b1580156131d857600080fd5b505af11580156131ec573d6000803e3d6000fd5b50505050505050505050565b600061218c8585858561321660408051602081019091526000815290565b611cf2565b600081815260fe60205260408120600281015460ff161561323f5750600792915050565b6002810154610100900460ff161561325a5750600292915050565b600083815260fe60205260408120546001600160401b0316908190036132c25760405162461bcd60e51b815260206004820152601d60248201527f476f7665726e6f723a20756e6b6e6f776e2070726f706f73616c2069640000006044820152606401610312565b60006132cc61180c565b65ffffffffffff1690508082106132e857506000949350505050565b600085815260fe60205260409020600101546001600160401b03168181106133165750600195945050505050565b61331f86613a4e565b801561333f57506000868152610161602052604090208054600190910154115b156133505750600495945050505050565b50600395945050505050565b60008061336b86868686613a9b565b60008181526101f960205260409020549091501561218c576101f85460008281526101f960205260409081902054905163c4d252f560e01b81526001600160a01b039092169163c4d252f5916133c79160040190815260200190565b600060405180830381600087803b1580156133e157600080fd5b505af11580156133f5573d6000803e3d6000fd5b50505060008281526101f960205260408120555095945050505050565b60008160000361342457506000919050565b6000600161343184613ba7565b901c6001901b9050600181848161344a5761344a614d28565b048201901c9050600181848161346257613462614d28565b048201901c9050600181848161347a5761347a614d28565b048201901c9050600181848161349257613492614d28565b048201901c905060018184816134aa576134aa614d28565b048201901c905060018184816134c2576134c2614d28565b048201901c905060018184816134da576134da614d28565b048201901c90506118a5818285816134f4576134f4614d28565b04613c3b565b60005b818310156135505760006135118484613c51565b60008781526020902090915063ffffffff86169082015463ffffffff16111561353c5780925061354a565b6135478160016149e8565b93505b506134fd565b509392505050565b80516000906034811015613570576001915050610ad1565b82810160131901516001600160a01b031981166b046e0e4dee0dee6cae47a60f60a31b146135a357600192505050610ad1565b6000806135b1602885614a8a565b90505b83811015613628576000806135e88884815181106135d4576135d4614a9d565b01602001516001600160f81b031916613c6c565b91509150816136005760019650505050505050610ad1565b8060ff166004856001600160a01b0316901b17935050508061362190614b95565b90506135b4565b50856001600160a01b0316816001600160a01b031614935050505092915050565b60006001600160401b038211156123555760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203660448201526534206269747360d01b6064820152608401610312565b600054610100900460ff166136d85760405162461bcd60e51b815260040161031290614cc6565b60676136e48382614da6565b5060686136f18282614da6565b50506000606581905560665550565b600054610100900460ff166137275760405162461bcd60e51b815260040161031290614cc6565b60fd6137338282614da6565b5050565b600054610100900460ff1661375e5760405162461bcd60e51b815260040161031290614cc6565b6137678361240c565b61377082612b1f565b6128cf81612bc2565b600054610100900460ff166137a05760405162461bcd60e51b815260040161031290614cc6565b61019380546001600160a01b0319166001600160a01b0392909216919091179055565b600054610100900460ff16610c595760405162461bcd60e51b815260040161031290614cc6565b600054610100900460ff166119575760405162461bcd60e51b815260040161031290614cc6565b8151156138215781518083602001fd5b8060405162461bcd60e51b81526004016103129190613fe5565b60007f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f613866613cfe565b61386e613d57565b60408051602081019490945283019190915260608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b8254600090819080156139f55760006138cd876123db600185614a8a565b60408051808201909152905463ffffffff808216808452600160201b9092046001600160e01b03166020840152919250908716101561394e5760405162461bcd60e51b815260206004820152601b60248201527f436865636b706f696e743a2064656372656173696e67206b65797300000000006044820152606401610312565b805163ffffffff808816911603613996578461396f886123db600186614a8a565b80546001600160e01b0392909216600160201b0263ffffffff9092169190911790556139e5565b6040805180820190915263ffffffff80881682526001600160e01b0380881660208085019182528b54600181018d5560008d81529190912094519151909216600160201b029216919091179101555b60200151925083915061313f9050565b50506040805180820190915263ffffffff80851682526001600160e01b0380851660208085019182528854600181018a5560008a815291822095519251909316600160201b02919093161792019190915590508161313f565b60008181526101616020526040812060028101546001820154613a7191906149e8565b600084815260fe6020526040902054613a92906001600160401b0316611c77565b11159392505050565b600080613aaa86868686611b0e565b90506000613ab782611070565b90506002816007811115613acd57613acd6142c1565b14158015613aed57506006816007811115613aea57613aea6142c1565b14155b8015613b0b57506007816007811115613b0857613b086142c1565b14155b613b575760405162461bcd60e51b815260206004820152601d60248201527f476f7665726e6f723a2070726f706f73616c206e6f74206163746976650000006044820152606401610312565b600082815260fe602052604090819020600201805461ff001916610100179055517f789cf55be980739dad1d0699b93b58e806b51c9d96619bfa8fe0a28abaa7b30c90610eea9084815260200190565b600080608083901c15613bbc57608092831c92015b604083901c15613bce57604092831c92015b602083901c15613be057602092831c92015b601083901c15613bf257601092831c92015b600883901c15613c0457600892831c92015b600483901c15613c1657600492831c92015b600283901c15613c2857600292831c92015b600183901c15610ad15760010192915050565b6000818310613c4a57816118a5565b5090919050565b6000613c606002848418614d3e565b6118a5908484166149e8565b60008060f883901c602f81118015613c875750603a8160ff16105b15613c9c57600194602f199091019350915050565b8060ff166040108015613cb2575060478160ff16105b15613cc7576001946036199091019350915050565b8060ff166060108015613cdd575060678160ff16105b15613cf2576001946056199091019350915050565b50600093849350915050565b600080613d09612828565b805190915015613d20578051602090910120919050565b6065548015613d2f5792915050565b7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4709250505090565b600080613d62612837565b805190915015613d79578051602090910120919050565b6066548015613d2f5792915050565b600060208284031215613d9a57600080fd5b81356001600160e01b0319811681146118a557600080fd5b803560ff8116811461121c57600080fd5b60008083601f840112613dd557600080fd5b5081356001600160401b03811115613dec57600080fd5b602083019150836020828501011115613e0457600080fd5b9250929050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715613e4957613e49613e0b565b604052919050565b60006001600160401b03821115613e6a57613e6a613e0b565b50601f01601f191660200190565b6000613e8b613e8684613e51565b613e21565b9050828152838383011115613e9f57600080fd5b828260208301376000602084830101529392505050565b600082601f830112613ec757600080fd5b6118a583833560208501613e78565b60008060008060008060008060e0898b031215613ef257600080fd5b88359750613f0260208a01613db2565b965060408901356001600160401b0380821115613f1e57600080fd5b613f2a8c838d01613dc3565b909850965060608b0135915080821115613f4357600080fd5b50613f508b828c01613eb6565b945050613f5f60808a01613db2565b925060a0890135915060c089013590509295985092959890939650565b600060208284031215613f8e57600080fd5b5035919050565b60005b83811015613fb0578181015183820152602001613f98565b50506000910152565b60008151808452613fd1816020860160208601613f95565b601f01601f19169290920160200192915050565b6020815260006118a56020830184613fb9565b6001600160a01b0381168114610c6257600080fd5b6000806000806080858703121561402357600080fd5b843561402e81613ff8565b9350602085013561403e81613ff8565b92506040850135915060608501356001600160401b0381111561406057600080fd5b61406c87828801613eb6565b91505092959194509250565b60006001600160401b0382111561409157614091613e0b565b5060051b60200190565b600082601f8301126140ac57600080fd5b813560206140bc613e8683614078565b82815260059290921b840181019181810190868411156140db57600080fd5b8286015b848110156140ff5780356140f281613ff8565b83529183019183016140df565b509695505050505050565b600082601f83011261411b57600080fd5b8135602061412b613e8683614078565b82815260059290921b8401810191818101908684111561414a57600080fd5b8286015b848110156140ff578035835291830191830161414e565b600082601f83011261417657600080fd5b81356020614186613e8683614078565b82815260059290921b840181019181810190868411156141a557600080fd5b8286015b848110156140ff5780356001600160401b038111156141c85760008081fd5b6141d68986838b0101613eb6565b8452509183019183016141a9565b600080600080608085870312156141fa57600080fd5b84356001600160401b038082111561421157600080fd5b61421d8883890161409b565b9550602087013591508082111561423357600080fd5b61423f8883890161410a565b9450604087013591508082111561425557600080fd5b5061426287828801614165565b949793965093946060013593505050565b600080600080600060a0868803121561428b57600080fd5b8535945061429b60208701613db2565b93506142a960408701613db2565b94979396509394606081013594506080013592915050565b634e487b7160e01b600052602160045260246000fd5b60208101600883106142f957634e487b7160e01b600052602160045260246000fd5b91905290565b6000806040838503121561431257600080fd5b82359150602083013561432481613ff8565b809150509250929050565b6000806040838503121561434257600080fd5b8235915061435260208401613db2565b90509250929050565b60008060008060006080868803121561437357600080fd5b8535945061438360208701613db2565b935060408601356001600160401b038082111561439f57600080fd5b6143ab89838a01613dc3565b909550935060608801359150808211156143c457600080fd5b506143d188828901613eb6565b9150509295509295909350565b600080600080606085870312156143f457600080fd5b8435935061440460208601613db2565b925060408501356001600160401b0381111561441f57600080fd5b61442b87828801613dc3565b95989497509550505050565b6000806000806080858703121561444d57600080fd5b84356001600160401b038082111561446457600080fd5b6144708883890161409b565b9550602087013591508082111561448657600080fd5b6144928883890161410a565b945060408701359150808211156144a857600080fd5b6144b488838901614165565b935060608701359150808211156144ca57600080fd5b508501601f810187136144dc57600080fd5b61406c87823560208401613e78565b600081518084526020808501945080840160005b8381101561451b578151875295820195908201906001016144ff565b509495945050505050565b60ff60f81b8816815260e06020820152600061454560e0830189613fb9565b82810360408401526145578189613fb9565b606084018890526001600160a01b038716608085015260a0840186905283810360c08501529050610bcd81856144eb565b60008060008060008060c087890312156145a157600080fd5b86356145ac81613ff8565b955060208701356145bc81613ff8565b95989597505050506040840135936060810135936080820135935060a0909101359150565b6000806000606084860312156145f657600080fd5b833561460181613ff8565b92506020840135915060408401356001600160401b0381111561462357600080fd5b61462f86828701613eb6565b9150509250925092565b60006020828403121561464b57600080fd5b81356118a581613ff8565b600080600080600060a0868803121561466e57600080fd5b853561467981613ff8565b9450602086013561468981613ff8565b935060408601356001600160401b03808211156146a557600080fd5b6146b189838a0161410a565b945060608801359150808211156146c757600080fd5b6146d389838a0161410a565b935060808801359150808211156143c457600080fd5b600080600080606085870312156146ff57600080fd5b843561470a81613ff8565b93506020850135925060408501356001600160401b0381111561441f57600080fd5b6000806040838503121561473f57600080fd5b823561474a81613ff8565b946020939093013593505050565b600080600080600060a0868803121561477057600080fd5b853561477b81613ff8565b9450602086013561478b81613ff8565b9350604086013592506060860135915060808601356001600160401b038111156147b457600080fd5b6143d188828901613eb6565b8183823760009101908152919050565b60208082526018908201527f476f7665726e6f723a206f6e6c79476f7665726e616e63650000000000000000604082015260600190565b600181811c9082168061481b57607f821691505b60208210810361483b57634e487b7160e01b600052602260045260246000fd5b50919050565b60208082526021908201527f476f7665726e6f723a2070726f706f73616c206e6f74207375636365737366756040820152601b60fa1b606082015260800190565b60006020828403121561489457600080fd5b5051919050565b600081518084526020808501945080840160005b8381101561451b5781516001600160a01b0316875295820195908201906001016148af565b600082825180855260208086019550808260051b84010181860160005b8481101561491f57601f1986840301895261490d838351613fb9565b988401989250908301906001016148f1565b5090979650505050505050565b60a08152600061493f60a083018861489b565b828103602084015261495181886144eb565b9050828103604084015261496581876148d4565b60608401959095525050608001529392505050565b60c08152600061498d60c083018961489b565b828103602084015261499f81896144eb565b905082810360408401526149b381886148d4565b60608401969096525050608081019290925260a0909101529392505050565b634e487b7160e01b600052601160045260246000fd5b80820180821115610ad157610ad16149d2565b600060208284031215614a0d57600080fd5b815180151581146118a557600080fd5b600060208284031215614a2f57600080fd5b81516001600160401b03811115614a4557600080fd5b8201601f81018413614a5657600080fd5b8051614a64613e8682613e51565b818152856020838501011115614a7957600080fd5b61218c826020830160208601613f95565b81810381811115610ad157610ad16149d2565b634e487b7160e01b600052603260045260246000fd5b600060208284031215614ac557600080fd5b81516001600160401b03811681146118a557600080fd5b608081526000614aef608083018761489b565b8281036020840152614b0181876144eb565b90508281036040840152614b1581866148d4565b91505082606083015295945050505050565b84815260ff8416602082015282604082015260806060820152600061116a6080830184613fb9565b85815260ff8516602082015283604082015260a060608201526000614b7760a0830185613fb9565b8281036080840152614b898185613fb9565b98975050505050505050565b600060018201614ba757614ba76149d2565b5060010190565b60208082526021908201527f476f7665726e6f723a20696e76616c69642070726f706f73616c206c656e67746040820152600d60fb1b606082015260800190565b60006101208b8352602060018060a01b038c1681850152816040850152614c188285018c61489b565b91508382036060850152614c2c828b6144eb565b915083820360808501528189518084528284019150828160051b850101838c0160005b83811015614c7d57601f19878403018552614c6b838351613fb9565b94860194925090850190600101614c4f565b505086810360a0880152614c91818c6148d4565b9450505050508560c08401528460e0840152828103610100840152614cb68185613fb9565b9c9b505050505050505050505050565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b8082028115828204841417610ad157610ad16149d2565b634e487b7160e01b600052601260045260246000fd5b600082614d5b57634e487b7160e01b600052601260045260246000fd5b500490565b601f8211156128cf57600081815260208120601f850160051c81016020861015614d875750805b601f850160051c820191505b818110156120d057828155600101614d93565b81516001600160401b03811115614dbf57614dbf613e0b565b614dd381614dcd8454614807565b84614d60565b602080601f831160018114614e085760008415614df05750858301515b600019600386901b1c1916600185901b1785556120d0565b600085815260208120601f198616915b82811015614e3757888601518255948401946001909101908401614e18565b5085821015614e555787850151600019600388901b60f8161c191681555b5050505050600190811b0190555056fe476f7665726e6f723a2072656c617920726576657274656420776974686f7574206d657373616765a2646970667358221220909a271346e4315b690b0a6a2c16e591688ebafe433a43ba63a295dc9c45d0bd64736f6c63430008110033
Deployed ByteCode
0x6080604052600436106102b25760003560e01c80637d5e81e211610175578063bc197c81116100dc578063deaaa7cc11610095578063ece40cc11161006f578063ece40cc114610a1f578063f23a6e6114610a3f578063f8ce560a14610a6b578063fc0c546a14610a8b57600080fd5b8063deaaa7cc146109ab578063ea0217cf146109df578063eb9019d4146109ff57600080fd5b8063bc197c81146108ae578063c01f9e37146108da578063c28bc2fa14610913578063c59057e414610926578063d33219b414610946578063dd4e2ba51461096557600080fd5b80639a802a6d1161012e5780639a802a6d146107f0578063a7713a7014610810578063a890c91014610825578063ab58fb8e14610845578063b08e51c014610865578063b58131b01461089957600080fd5b80637d5e81e21461071457806384b0196e1461073457806386489ba91461075c5780638f61f4f51461077c57806391ddadf4146107b057806397c3d334146107dc57600080fd5b80633bccf4fd1161021957806354fd4d50116101d257806354fd4d501461064a57806356781388146106745780635f398a141461069457806360c4247f146106b457806370b0f660146106d45780637b3c71d3146106f457600080fd5b80633bccf4fd146105275780633e4f49e6146105475780634385963214610574578063452115d6146105bf5780634bf5d7e9146105df578063544ffc9c146105f457600080fd5b8063150b7a021161026b578063150b7a0214610431578063160cbed7146104755780632656227d146104955780632d63f693146104a85780632fe3e261146104de5780633932abb11461051257600080fd5b806301ffc9a71461032257806302a251a314610357578063034201811461037a57806306f3f9e61461039a57806306fdde03146103ba578063143489d0146103dc57600080fd5b3661031d57306102c0610aac565b6001600160a01b03161461031b5760405162461bcd60e51b815260206004820152601f60248201527f476f7665726e6f723a206d7573742073656e6420746f206578656375746f720060448201526064015b60405180910390fd5b005b600080fd5b34801561032e57600080fd5b5061034261033d366004613d88565b610ac6565b60405190151581526020015b60405180910390f35b34801561036357600080fd5b5061036c610ad7565b60405190815260200161034e565b34801561038657600080fd5b5061036c610395366004613ed6565b610ae3565b3480156103a657600080fd5b5061031b6103b5366004613f7c565b610bdb565b3480156103c657600080fd5b506103cf610c65565b60405161034e9190613fe5565b3480156103e857600080fd5b506104196103f7366004613f7c565b600090815260fe6020526040902054600160401b90046001600160a01b031690565b6040516001600160a01b03909116815260200161034e565b34801561043d57600080fd5b5061045c61044c36600461400d565b630a85bd0160e11b949350505050565b6040516001600160e01b0319909116815260200161034e565b34801561048157600080fd5b5061036c6104903660046141e4565b610cf7565b61036c6104a33660046141e4565b610efc565b3480156104b457600080fd5b5061036c6104c3366004613f7c565b600090815260fe60205260409020546001600160401b031690565b3480156104ea57600080fd5b5061036c7fb3b3f3b703cd84ce352197dcff232b1b5d3cfb2025ce47cf04742d0651f1af8881565b34801561051e57600080fd5b5061036c610fee565b34801561053357600080fd5b5061036c610542366004614273565b610ffa565b34801561055357600080fd5b50610567610562366004613f7c565b611070565b60405161034e91906142d7565b34801561058057600080fd5b5061034261058f3660046142ff565b6000828152610161602090815260408083206001600160a01b038516845260030190915290205460ff1692915050565b3480156105cb57600080fd5b5061036c6105da3660046141e4565b61107b565b3480156105eb57600080fd5b506103cf611174565b34801561060057600080fd5b5061062f61060f366004613f7c565b600090815261016160205260409020805460018201546002909201549092565b6040805193845260208401929092529082015260600161034e565b34801561065657600080fd5b506040805180820190915260018152603160f81b60208201526103cf565b34801561068057600080fd5b5061036c61068f36600461432f565b611221565b3480156106a057600080fd5b5061036c6106af36600461435b565b61124a565b3480156106c057600080fd5b5061036c6106cf366004613f7c565b611294565b3480156106e057600080fd5b5061031b6106ef366004613f7c565b611349565b34801561070057600080fd5b5061036c61070f3660046143de565b6113d0565b34801561072057600080fd5b5061036c61072f366004614437565b611418565b34801561074057600080fd5b50610749611605565b60405161034e9796959493929190614526565b34801561076857600080fd5b5061031b610777366004614588565b6116a3565b34801561078857600080fd5b5061036c7fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc181565b3480156107bc57600080fd5b506107c561180c565b60405165ffffffffffff909116815260200161034e565b3480156107e857600080fd5b50606461036c565b3480156107fc57600080fd5b5061036c61080b3660046145e1565b611895565b34801561081c57600080fd5b5061036c6118ac565b34801561083157600080fd5b5061031b610840366004614639565b6118d9565b34801561085157600080fd5b5061036c610860366004613f7c565b611960565b34801561087157600080fd5b5061036c7ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f78381565b3480156108a557600080fd5b5061036c6119fc565b3480156108ba57600080fd5b5061045c6108c9366004614656565b63bc197c8160e01b95945050505050565b3480156108e657600080fd5b5061036c6108f5366004613f7c565b600090815260fe60205260409020600101546001600160401b031690565b61031b6109213660046146e9565b611a08565b34801561093257600080fd5b5061036c6109413660046141e4565b611b0e565b34801561095257600080fd5b506101f8546001600160a01b0316610419565b34801561097157600080fd5b506040805180820190915260208082527f737570706f72743d627261766f2671756f72756d3d666f722c6162737461696e908201526103cf565b3480156109b757600080fd5b5061036c7f150214d74d59b7d1e90c73fc22ef3d991dd0a76b046543d4d80ab92d2a50328f81565b3480156109eb57600080fd5b5061031b6109fa366004613f7c565b611b48565b348015610a0b57600080fd5b5061036c610a1a36600461472c565b611bcf565b348015610a2b57600080fd5b5061031b610a3a366004613f7c565b611bf0565b348015610a4b57600080fd5b5061045c610a5a366004614758565b63f23a6e6160e01b95945050505050565b348015610a7757600080fd5b5061036c610a86366004613f7c565b611c77565b348015610a9757600080fd5b5061019354610419906001600160a01b031681565b6000610ac16101f8546001600160a01b031690565b905090565b6000610ad182611c82565b92915050565b6000610ac16101305490565b600080610b87610b7f7fb3b3f3b703cd84ce352197dcff232b1b5d3cfb2025ce47cf04742d0651f1af888c8c8c8c604051610b1f9291906147c0565b60405180910390208b80519060200120604051602001610b64959493929190948552602085019390935260ff9190911660408401526060830152608082015260a00190565b60405160208183030381529060405280519060200120611ca7565b868686611cd4565b9050610bcd8a828b8b8b8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152508d9250611cf2915050565b9a9950505050505050505050565b610be3610aac565b6001600160a01b0316336001600160a01b031614610c135760405162461bcd60e51b8152600401610312906147d0565b30610c1c610aac565b6001600160a01b031614610c595760008036604051610c3c9291906147c0565b604051809103902090505b80610c5260ff611e47565b03610c4757505b610c6281611ec6565b50565b606060fd8054610c7490614807565b80601f0160208091040260200160405190810160405280929190818152602001828054610ca090614807565b8015610ced5780601f10610cc257610100808354040283529160200191610ced565b820191906000526020600020905b815481529060010190602001808311610cd057829003601f168201915b5050505050905090565b600080610d0686868686611b0e565b90506004610d1382611070565b6007811115610d2457610d246142c1565b14610d415760405162461bcd60e51b815260040161031290614841565b6101f8546040805163793d064960e11b815290516000926001600160a01b03169163f27a0c929160048083019260209291908290030181865afa158015610d8c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610db09190614882565b6101f85460405163b1c5f42760e01b81529192506001600160a01b03169063b1c5f42790610deb908a908a908a906000908b9060040161492c565b602060405180830381865afa158015610e08573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e2c9190614882565b60008381526101f96020526040808220929092556101f85491516308f2a0bb60e41b81526001600160a01b0390921691638f2a0bb091610e79918b918b918b91908b90899060040161497a565b600060405180830381600087803b158015610e9357600080fd5b505af1158015610ea7573d6000803e3d6000fd5b505050507f9a2e42fd6722813d69113e7d0079d3d940171428df7373df9c7f7617cfda2892828242610ed991906149e8565b604080519283526020830191909152015b60405180910390a15095945050505050565b600080610f0b86868686611b0e565b90506000610f1882611070565b90506004816007811115610f2e57610f2e6142c1565b1480610f4b57506005816007811115610f4957610f496142c1565b145b610f675760405162461bcd60e51b815260040161031290614841565b600082815260fe602052604090819020600201805460ff19166001179055517f712ae1383f79ac853f8d882153778e0260ef8f03b504e2866e0593e04d2b291f90610fb59084815260200190565b60405180910390a1610fca8288888888612037565b610fd782888888886120d9565b610fe482888888886120e6565b5095945050505050565b6000610ac161012f5490565b604080517f150214d74d59b7d1e90c73fc22ef3d991dd0a76b046543d4d80ab92d2a50328f602082015290810186905260ff85166060820152600090819061104890610b7f90608001610b64565b90506110658782886040518060200160405280600081525061211f565b979650505050505050565b6000610ad182612195565b6000806110916101f8546001600160a01b031690565b604051632474521560e21b81527ffd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f78360048201523360248201529091506001600160a01b038216906391d1485490604401602060405180830381865afa1580156110fe573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061112291906149fb565b604051806040016040528060048152602001632298981960e11b8152509061115d5760405162461bcd60e51b81526004016103129190613fe5565b5061116a868686866122e2565b9695505050505050565b6101935460408051634bf5d7e960e01b815290516060926001600160a01b031691634bf5d7e99160048083019260009291908290030181865afa9250505080156111e057506040513d6000823e601f3d908101601f191682016040526111dd9190810190614a1d565b60015b61121c575060408051808201909152601d81527f6d6f64653d626c6f636b6e756d6265722666726f6d3d64656661756c74000000602082015290565b919050565b6000803390506112428482856040518060200160405280600081525061211f565b949350505050565b60008033905061106587828888888080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152508a9250611cf2915050565b6101c7546000908082036112ad5750506101c654919050565b60006101c76112bd600184614a8a565b815481106112cd576112cd614a9d565b60009182526020918290206040805180820190915291015463ffffffff8116808352600160201b9091046001600160e01b0316928201929092529150841061132357602001516001600160e01b03169392505050565b61133861132f856122f0565b6101c790612359565b6001600160e01b0316949350505050565b611351610aac565b6001600160a01b0316336001600160a01b0316146113815760405162461bcd60e51b8152600401610312906147d0565b3061138a610aac565b6001600160a01b0316146113c757600080366040516113aa9291906147c0565b604051809103902090505b806113c060ff611e47565b036113b557505b610c628161240c565b60008033905061116a86828787878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061211f92505050565b60008061142e6101f8546001600160a01b031690565b604051632474521560e21b81527fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc160048201523360248201529091506001600160a01b038216906391d1485490604401602060405180830381865afa15801561149b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114bf91906149fb565b806115545750604051632474521560e21b81527fb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc16004820152600060248201526001600160a01b038216906391d1485490604401602060405180830381865afa158015611530573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061155491906149fb565b604051806040016040528060048152602001632298981960e11b8152509061158f5760405162461bcd60e51b81526004016103129190613fe5565b5061019360009054906101000a90046001600160a01b03166001600160a01b03166360c22cdd6040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156115e157600080fd5b505af11580156115f5573d6000803e3d6000fd5b5050505061116a8686868661244f565b6000606080600080600060606065546000801b1480156116255750606654155b6116695760405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b6044820152606401610312565b611671612828565b611679612837565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b600054610100900460ff16158080156116c35750600054600160ff909116105b806116dd5750303b1580156116dd575060005460ff166001145b6117405760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610312565b6000805460ff191660011790558015611763576000805461ff0019166101001790555b61178f6040518060400160405280600b81526020016a26b73a23b7bb32b93737b960a91b815250612846565b61179a85858561289d565b6117a26128d4565b6117ab876128fd565b6117b48261292d565b6117bd8661295d565b8015611803576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b50505050505050565b6000610ac17316700900000000000000000000000000000100016001600160a01b03166333d5ac9b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611863573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118879190614ab3565b6001600160401b031661298d565b60006118a28484846129f4565b90505b9392505050565b6101c754600090156118d1576118c36101c7612a6b565b6001600160e01b0316905090565b506101c65490565b6118e1610aac565b6001600160a01b0316336001600160a01b0316146119115760405162461bcd60e51b8152600401610312906147d0565b3061191a610aac565b6001600160a01b031614611957576000803660405161193a9291906147c0565b604051809103902090505b8061195060ff611e47565b0361194557505b610c6281612a9b565b6101f85460008281526101f9602052604080822054905163d45c443560e01b81526004810191909152909182916001600160a01b039091169063d45c443590602401602060405180830381865afa1580156119bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119e39190614882565b9050806001146119f357806118a5565b60009392505050565b6000610ac16101315490565b611a10610aac565b6001600160a01b0316336001600160a01b031614611a405760405162461bcd60e51b8152600401610312906147d0565b30611a49610aac565b6001600160a01b031614611a865760008036604051611a699291906147c0565b604051809103902090505b80611a7f60ff611e47565b03611a7457505b600080856001600160a01b0316858585604051611aa49291906147c0565b60006040518083038185875af1925050503d8060008114611ae1576040519150601f19603f3d011682016040523d82523d6000602084013e611ae6565b606091505b50915091506118038282604051806060016040528060288152602001614e6660289139612b06565b600084848484604051602001611b279493929190614adc565b60408051601f19818403018152919052805160209091012095945050505050565b611b50610aac565b6001600160a01b0316336001600160a01b031614611b805760405162461bcd60e51b8152600401610312906147d0565b30611b89610aac565b6001600160a01b031614611bc65760008036604051611ba99291906147c0565b604051809103902090505b80611bbf60ff611e47565b03611bb457505b610c6281612b1f565b60006118a58383611beb60408051602081019091526000815290565b6129f4565b611bf8610aac565b6001600160a01b0316336001600160a01b031614611c285760405162461bcd60e51b8152600401610312906147d0565b30611c31610aac565b6001600160a01b031614611c6e5760008036604051611c519291906147c0565b604051809103902090505b80611c6760ff611e47565b03611c5c57505b610c6281612bc2565b6000610ad182612c05565b60006001600160e01b03198216636e665ced60e01b1480610ad15750610ad182612c94565b6000610ad1611cb4612d30565b8360405161190160f01b8152600281019290925260228201526042902090565b6000806000611ce587878787612d3a565b91509150610fe481612dfe565b600085815260fe602052604081206001611d0b88611070565b6007811115611d1c57611d1c6142c1565b14611d755760405162461bcd60e51b815260206004820152602360248201527f476f7665726e6f723a20766f7465206e6f742063757272656e746c792061637460448201526269766560e81b6064820152608401610312565b8054600090611d8f9088906001600160401b0316866129f4565b9050611d9e8888888488612f48565b8351600003611df357866001600160a01b03167fb8e138887d0aa13bab447e82de9d5c1777041ecd21ca36ba824ff1e6c07ddda489888489604051611de69493929190614b27565b60405180910390a2611065565b866001600160a01b03167fe2babfbac5889a709b63bb7f598b324e08bc5a4fb9ec647fb3cbc9ec07eb87128988848989604051611e34959493929190614b4f565b60405180910390a2979650505050505050565b6000611e628254600f81810b600160801b909204900b131590565b15611e8057604051631ed9509560e11b815260040160405180910390fd5b508054600f0b6000818152600180840160205260408220805492905583546fffffffffffffffffffffffffffffffff191692016001600160801b03169190911790915590565b6064811115611f495760405162461bcd60e51b815260206004820152604360248201527f476f7665726e6f72566f74657351756f72756d4672616374696f6e3a2071756f60448201527f72756d4e756d657261746f72206f7665722071756f72756d44656e6f6d696e616064820152623a37b960e91b608482015260a401610312565b6000611f536118ac565b90508015801590611f6557506101c754155b15611fca5760408051808201909152600081526101c79060208101611f89846130c3565b6001600160e01b039081169091528254600181018455600093845260209384902083519490930151909116600160201b0263ffffffff909316929092179101555b611ff8611fe5611fd861180c565b65ffffffffffff166122f0565b611fee846130c3565b6101c7919061312c565b505060408051828152602081018490527f0553476bf02ef2726e8ce5ced78d63e26e602e4a2257b1f559418e24b4633997910160405180910390a15050565b30612040610aac565b6001600160a01b0316146120d25760005b84518110156120d057306001600160a01b031685828151811061207657612076614a9d565b60200260200101516001600160a01b0316036120c0576120c08382815181106120a1576120a1614a9d565b60200260200101518051906020012060ff61314790919063ffffffff16565b6120c981614b95565b9050612051565b505b5050505050565b6120d28585858585613183565b306120ef610aac565b6001600160a01b0316146120d25760ff54600f81810b600160801b909204900b13156120d257600060ff556120d2565b610193546040516329cfb1f960e01b81526001600160a01b03858116600483015260009216906329cfb1f990602401600060405180830381600087803b15801561216857600080fd5b505af115801561217c573d6000803e3d6000fd5b5050505061218c858585856131f8565b95945050505050565b6000806121a18361321b565b905060048160078111156121b7576121b76142c1565b146121c25792915050565b60008381526101f96020526040902054806121de575092915050565b6101f854604051632ab0f52960e01b8152600481018390526001600160a01b0390911690632ab0f52990602401602060405180830381865afa158015612228573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061224c91906149fb565b1561225b575060079392505050565b6101f854604051632c258a9f60e11b8152600481018390526001600160a01b039091169063584b153e90602401602060405180830381865afa1580156122a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122c991906149fb565b156122d8575060059392505050565b5060029392505050565b600061218c8585858561335c565b600063ffffffff8211156123555760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203360448201526532206269747360d01b6064820152608401610312565b5090565b8154600090818160058111156123b657600061237484613412565b61237e9085614a8a565b60008881526020902090915081015463ffffffff90811690871610156123a6578091506123b4565b6123b18160016149e8565b92505b505b60006123c4878785856134fa565b905080156123ff576123e9876123db600184614a8a565b600091825260209091200190565b54600160201b90046001600160e01b0316611065565b6000979650505050505050565b61012f5460408051918252602082018390527fc565b045403dc03c2eea82b81a0465edad9e2e7fc4d97e11421c209da93d7a93910160405180910390a161012f55565b60003361245c8184613558565b6124a85760405162461bcd60e51b815260206004820152601d60248201527f476f7665726e6f723a2070726f706f73657220726573747269637465640000006044820152606401610312565b60006124b261180c565b65ffffffffffff1690506124c46119fc565b6124d383610a1a600185614a8a565b101561253b5760405162461bcd60e51b815260206004820152603160248201527f476f7665726e6f723a2070726f706f73657220766f7465732062656c6f7720706044820152701c9bdc1bdcd85b081d1a1c995cda1bdb19607a1b6064820152608401610312565b60006125508888888880519060200120611b0e565b905086518851146125735760405162461bcd60e51b815260040161031290614bae565b85518851146125945760405162461bcd60e51b815260040161031290614bae565b60008851116125e55760405162461bcd60e51b815260206004820152601860248201527f476f7665726e6f723a20656d7074792070726f706f73616c00000000000000006044820152606401610312565b600081815260fe60205260409020546001600160401b0316156126545760405162461bcd60e51b815260206004820152602160248201527f476f7665726e6f723a2070726f706f73616c20616c72656164792065786973746044820152607360f81b6064820152608401610312565b600061265e610fee565b61266890846149e8565b90506000612674610ad7565b61267e90836149e8565b90506040518060e0016040528061269484613649565b6001600160401b031681526001600160a01b0387166020820152600060408201526060016126c183613649565b6001600160401b039081168252600060208084018290526040808501839052606094850183905288835260fe8252918290208551815492870151878501519186166001600160e01b031990941693909317600160401b6001600160a01b039094168402176001600160e01b0316600160e01b60e09290921c91909102178155938501516080860151908416921c0217600183015560a08301516002909201805460c09094015161ffff1990941692151561ff00191692909217610100931515939093029290921790558a517f7d84a6263ae0d98d3329bd7b46bb4e8d6f98cd35a7adb45c274c8b7fd5ebd5e091859188918e918e918111156127c5576127c5613e0b565b6040519080825280602002602001820160405280156127f857816020015b60608152602001906001900390816127e35790505b508d88888f60405161281299989796959493929190614bef565b60405180910390a1509098975050505050505050565b606060678054610c7490614807565b606060688054610c7490614807565b600054610100900460ff1661286d5760405162461bcd60e51b815260040161031290614cc6565b6128948161288f6040805180820190915260018152603160f81b602082015290565b6136b1565b610c6281613700565b600054610100900460ff166128c45760405162461bcd60e51b815260040161031290614cc6565b6128cf838383613737565b505050565b600054610100900460ff166128fb5760405162461bcd60e51b815260040161031290614cc6565b565b600054610100900460ff166129245760405162461bcd60e51b815260040161031290614cc6565b610c6281613779565b600054610100900460ff166129545760405162461bcd60e51b815260040161031290614cc6565b610c62816137c3565b600054610100900460ff166129845760405162461bcd60e51b815260040161031290614cc6565b610c62816137ea565b600065ffffffffffff8211156123555760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203460448201526538206269747360d01b6064820152608401610312565b61019354604051630748d63560e31b81526001600160a01b038581166004830152602482018590526000921690633a46b1a890604401602060405180830381865afa158015612a47573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118a29190614882565b805460009080156119f357612a85836123db600184614a8a565b54600160201b90046001600160e01b03166118a5565b6101f854604080516001600160a01b03928316815291831660208301527f08f74ea46ef7894f65eabfb5e6e695de773a000b47c529ab559178069b226401910160405180910390a16101f880546001600160a01b0319166001600160a01b0392909216919091179055565b60608315612b155750816118a5565b6118a58383613811565b60008111612b7f5760405162461bcd60e51b815260206004820152602760248201527f476f7665726e6f7253657474696e67733a20766f74696e6720706572696f6420604482015266746f6f206c6f7760c81b6064820152608401610312565b6101305460408051918252602082018390527f7e3f7f0708a84de9203036abaa450dccc85ad5ff52f78c170f3edb55cf5e8828910160405180910390a161013055565b6101315460408051918252602082018390527fccb45da8d5717e6c4544694297c4ba5cf151d455c9bb0ed4fc7a38411bc05461910160405180910390a161013155565b60006064612c1283611294565b61019354604051632394e7a360e21b8152600481018690526001600160a01b0390911690638e539e8c90602401602060405180830381865afa158015612c5c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c809190614882565b612c8a9190614d11565b610ad19190614d3e565b600063288ace0360e11b6318df743f60e31b63bf26d89760e01b6379dd796f60e01b6001600160e01b03198616821480612cda57506001600160e01b0319868116908216145b80612cf157506001600160e01b0319868116908516145b80612d0c57506001600160e01b03198616630271189760e51b145b8061116a57506301ffc9a760e01b6001600160e01b03198716149695505050505050565b6000610ac161383b565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0831115612d715750600090506003612df5565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa158015612dc5573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116612dee57600060019250925050612df5565b9150600090505b94509492505050565b6000816004811115612e1257612e126142c1565b03612e1a5750565b6001816004811115612e2e57612e2e6142c1565b03612e7b5760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401610312565b6002816004811115612e8f57612e8f6142c1565b03612edc5760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401610312565b6003816004811115612ef057612ef06142c1565b03610c625760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401610312565b6000858152610161602090815260408083206001600160a01b0388168452600381019092529091205460ff1615612fd15760405162461bcd60e51b815260206004820152602760248201527f476f7665726e6f72566f74696e6753696d706c653a20766f746520616c726561604482015266191e4818d85cdd60ca1b6064820152608401610312565b6001600160a01b03851660009081526003820160205260409020805460ff1916600117905560ff841661301d578281600001600082825461301291906149e8565b909155506120d09050565b60001960ff85160161303d578281600101600082825461301291906149e8565b60011960ff85160161305d578281600201600082825461301291906149e8565b60405162461bcd60e51b815260206004820152603560248201527f476f7665726e6f72566f74696e6753696d706c653a20696e76616c69642076616044820152746c756520666f7220656e756d20566f74655479706560581b6064820152608401610312565b60006001600160e01b038211156123555760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20326044820152663234206269747360c81b6064820152608401610312565b60008061313a8585856138af565b915091505b935093915050565b8154600160801b90819004600f0b6000818152600180860160205260409091209390935583546001600160801b03908116939091011602179055565b6101f85460405163e38335e560e01b81526001600160a01b039091169063e38335e59034906131bf90889088908890600090899060040161492c565b6000604051808303818588803b1580156131d857600080fd5b505af11580156131ec573d6000803e3d6000fd5b50505050505050505050565b600061218c8585858561321660408051602081019091526000815290565b611cf2565b600081815260fe60205260408120600281015460ff161561323f5750600792915050565b6002810154610100900460ff161561325a5750600292915050565b600083815260fe60205260408120546001600160401b0316908190036132c25760405162461bcd60e51b815260206004820152601d60248201527f476f7665726e6f723a20756e6b6e6f776e2070726f706f73616c2069640000006044820152606401610312565b60006132cc61180c565b65ffffffffffff1690508082106132e857506000949350505050565b600085815260fe60205260409020600101546001600160401b03168181106133165750600195945050505050565b61331f86613a4e565b801561333f57506000868152610161602052604090208054600190910154115b156133505750600495945050505050565b50600395945050505050565b60008061336b86868686613a9b565b60008181526101f960205260409020549091501561218c576101f85460008281526101f960205260409081902054905163c4d252f560e01b81526001600160a01b039092169163c4d252f5916133c79160040190815260200190565b600060405180830381600087803b1580156133e157600080fd5b505af11580156133f5573d6000803e3d6000fd5b50505060008281526101f960205260408120555095945050505050565b60008160000361342457506000919050565b6000600161343184613ba7565b901c6001901b9050600181848161344a5761344a614d28565b048201901c9050600181848161346257613462614d28565b048201901c9050600181848161347a5761347a614d28565b048201901c9050600181848161349257613492614d28565b048201901c905060018184816134aa576134aa614d28565b048201901c905060018184816134c2576134c2614d28565b048201901c905060018184816134da576134da614d28565b048201901c90506118a5818285816134f4576134f4614d28565b04613c3b565b60005b818310156135505760006135118484613c51565b60008781526020902090915063ffffffff86169082015463ffffffff16111561353c5780925061354a565b6135478160016149e8565b93505b506134fd565b509392505050565b80516000906034811015613570576001915050610ad1565b82810160131901516001600160a01b031981166b046e0e4dee0dee6cae47a60f60a31b146135a357600192505050610ad1565b6000806135b1602885614a8a565b90505b83811015613628576000806135e88884815181106135d4576135d4614a9d565b01602001516001600160f81b031916613c6c565b91509150816136005760019650505050505050610ad1565b8060ff166004856001600160a01b0316901b17935050508061362190614b95565b90506135b4565b50856001600160a01b0316816001600160a01b031614935050505092915050565b60006001600160401b038211156123555760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203660448201526534206269747360d01b6064820152608401610312565b600054610100900460ff166136d85760405162461bcd60e51b815260040161031290614cc6565b60676136e48382614da6565b5060686136f18282614da6565b50506000606581905560665550565b600054610100900460ff166137275760405162461bcd60e51b815260040161031290614cc6565b60fd6137338282614da6565b5050565b600054610100900460ff1661375e5760405162461bcd60e51b815260040161031290614cc6565b6137678361240c565b61377082612b1f565b6128cf81612bc2565b600054610100900460ff166137a05760405162461bcd60e51b815260040161031290614cc6565b61019380546001600160a01b0319166001600160a01b0392909216919091179055565b600054610100900460ff16610c595760405162461bcd60e51b815260040161031290614cc6565b600054610100900460ff166119575760405162461bcd60e51b815260040161031290614cc6565b8151156138215781518083602001fd5b8060405162461bcd60e51b81526004016103129190613fe5565b60007f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f613866613cfe565b61386e613d57565b60408051602081019490945283019190915260608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b8254600090819080156139f55760006138cd876123db600185614a8a565b60408051808201909152905463ffffffff808216808452600160201b9092046001600160e01b03166020840152919250908716101561394e5760405162461bcd60e51b815260206004820152601b60248201527f436865636b706f696e743a2064656372656173696e67206b65797300000000006044820152606401610312565b805163ffffffff808816911603613996578461396f886123db600186614a8a565b80546001600160e01b0392909216600160201b0263ffffffff9092169190911790556139e5565b6040805180820190915263ffffffff80881682526001600160e01b0380881660208085019182528b54600181018d5560008d81529190912094519151909216600160201b029216919091179101555b60200151925083915061313f9050565b50506040805180820190915263ffffffff80851682526001600160e01b0380851660208085019182528854600181018a5560008a815291822095519251909316600160201b02919093161792019190915590508161313f565b60008181526101616020526040812060028101546001820154613a7191906149e8565b600084815260fe6020526040902054613a92906001600160401b0316611c77565b11159392505050565b600080613aaa86868686611b0e565b90506000613ab782611070565b90506002816007811115613acd57613acd6142c1565b14158015613aed57506006816007811115613aea57613aea6142c1565b14155b8015613b0b57506007816007811115613b0857613b086142c1565b14155b613b575760405162461bcd60e51b815260206004820152601d60248201527f476f7665726e6f723a2070726f706f73616c206e6f74206163746976650000006044820152606401610312565b600082815260fe602052604090819020600201805461ff001916610100179055517f789cf55be980739dad1d0699b93b58e806b51c9d96619bfa8fe0a28abaa7b30c90610eea9084815260200190565b600080608083901c15613bbc57608092831c92015b604083901c15613bce57604092831c92015b602083901c15613be057602092831c92015b601083901c15613bf257601092831c92015b600883901c15613c0457600892831c92015b600483901c15613c1657600492831c92015b600283901c15613c2857600292831c92015b600183901c15610ad15760010192915050565b6000818310613c4a57816118a5565b5090919050565b6000613c606002848418614d3e565b6118a5908484166149e8565b60008060f883901c602f81118015613c875750603a8160ff16105b15613c9c57600194602f199091019350915050565b8060ff166040108015613cb2575060478160ff16105b15613cc7576001946036199091019350915050565b8060ff166060108015613cdd575060678160ff16105b15613cf2576001946056199091019350915050565b50600093849350915050565b600080613d09612828565b805190915015613d20578051602090910120919050565b6065548015613d2f5792915050565b7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4709250505090565b600080613d62612837565b805190915015613d79578051602090910120919050565b6066548015613d2f5792915050565b600060208284031215613d9a57600080fd5b81356001600160e01b0319811681146118a557600080fd5b803560ff8116811461121c57600080fd5b60008083601f840112613dd557600080fd5b5081356001600160401b03811115613dec57600080fd5b602083019150836020828501011115613e0457600080fd5b9250929050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b0381118282101715613e4957613e49613e0b565b604052919050565b60006001600160401b03821115613e6a57613e6a613e0b565b50601f01601f191660200190565b6000613e8b613e8684613e51565b613e21565b9050828152838383011115613e9f57600080fd5b828260208301376000602084830101529392505050565b600082601f830112613ec757600080fd5b6118a583833560208501613e78565b60008060008060008060008060e0898b031215613ef257600080fd5b88359750613f0260208a01613db2565b965060408901356001600160401b0380821115613f1e57600080fd5b613f2a8c838d01613dc3565b909850965060608b0135915080821115613f4357600080fd5b50613f508b828c01613eb6565b945050613f5f60808a01613db2565b925060a0890135915060c089013590509295985092959890939650565b600060208284031215613f8e57600080fd5b5035919050565b60005b83811015613fb0578181015183820152602001613f98565b50506000910152565b60008151808452613fd1816020860160208601613f95565b601f01601f19169290920160200192915050565b6020815260006118a56020830184613fb9565b6001600160a01b0381168114610c6257600080fd5b6000806000806080858703121561402357600080fd5b843561402e81613ff8565b9350602085013561403e81613ff8565b92506040850135915060608501356001600160401b0381111561406057600080fd5b61406c87828801613eb6565b91505092959194509250565b60006001600160401b0382111561409157614091613e0b565b5060051b60200190565b600082601f8301126140ac57600080fd5b813560206140bc613e8683614078565b82815260059290921b840181019181810190868411156140db57600080fd5b8286015b848110156140ff5780356140f281613ff8565b83529183019183016140df565b509695505050505050565b600082601f83011261411b57600080fd5b8135602061412b613e8683614078565b82815260059290921b8401810191818101908684111561414a57600080fd5b8286015b848110156140ff578035835291830191830161414e565b600082601f83011261417657600080fd5b81356020614186613e8683614078565b82815260059290921b840181019181810190868411156141a557600080fd5b8286015b848110156140ff5780356001600160401b038111156141c85760008081fd5b6141d68986838b0101613eb6565b8452509183019183016141a9565b600080600080608085870312156141fa57600080fd5b84356001600160401b038082111561421157600080fd5b61421d8883890161409b565b9550602087013591508082111561423357600080fd5b61423f8883890161410a565b9450604087013591508082111561425557600080fd5b5061426287828801614165565b949793965093946060013593505050565b600080600080600060a0868803121561428b57600080fd5b8535945061429b60208701613db2565b93506142a960408701613db2565b94979396509394606081013594506080013592915050565b634e487b7160e01b600052602160045260246000fd5b60208101600883106142f957634e487b7160e01b600052602160045260246000fd5b91905290565b6000806040838503121561431257600080fd5b82359150602083013561432481613ff8565b809150509250929050565b6000806040838503121561434257600080fd5b8235915061435260208401613db2565b90509250929050565b60008060008060006080868803121561437357600080fd5b8535945061438360208701613db2565b935060408601356001600160401b038082111561439f57600080fd5b6143ab89838a01613dc3565b909550935060608801359150808211156143c457600080fd5b506143d188828901613eb6565b9150509295509295909350565b600080600080606085870312156143f457600080fd5b8435935061440460208601613db2565b925060408501356001600160401b0381111561441f57600080fd5b61442b87828801613dc3565b95989497509550505050565b6000806000806080858703121561444d57600080fd5b84356001600160401b038082111561446457600080fd5b6144708883890161409b565b9550602087013591508082111561448657600080fd5b6144928883890161410a565b945060408701359150808211156144a857600080fd5b6144b488838901614165565b935060608701359150808211156144ca57600080fd5b508501601f810187136144dc57600080fd5b61406c87823560208401613e78565b600081518084526020808501945080840160005b8381101561451b578151875295820195908201906001016144ff565b509495945050505050565b60ff60f81b8816815260e06020820152600061454560e0830189613fb9565b82810360408401526145578189613fb9565b606084018890526001600160a01b038716608085015260a0840186905283810360c08501529050610bcd81856144eb565b60008060008060008060c087890312156145a157600080fd5b86356145ac81613ff8565b955060208701356145bc81613ff8565b95989597505050506040840135936060810135936080820135935060a0909101359150565b6000806000606084860312156145f657600080fd5b833561460181613ff8565b92506020840135915060408401356001600160401b0381111561462357600080fd5b61462f86828701613eb6565b9150509250925092565b60006020828403121561464b57600080fd5b81356118a581613ff8565b600080600080600060a0868803121561466e57600080fd5b853561467981613ff8565b9450602086013561468981613ff8565b935060408601356001600160401b03808211156146a557600080fd5b6146b189838a0161410a565b945060608801359150808211156146c757600080fd5b6146d389838a0161410a565b935060808801359150808211156143c457600080fd5b600080600080606085870312156146ff57600080fd5b843561470a81613ff8565b93506020850135925060408501356001600160401b0381111561441f57600080fd5b6000806040838503121561473f57600080fd5b823561474a81613ff8565b946020939093013593505050565b600080600080600060a0868803121561477057600080fd5b853561477b81613ff8565b9450602086013561478b81613ff8565b9350604086013592506060860135915060808601356001600160401b038111156147b457600080fd5b6143d188828901613eb6565b8183823760009101908152919050565b60208082526018908201527f476f7665726e6f723a206f6e6c79476f7665726e616e63650000000000000000604082015260600190565b600181811c9082168061481b57607f821691505b60208210810361483b57634e487b7160e01b600052602260045260246000fd5b50919050565b60208082526021908201527f476f7665726e6f723a2070726f706f73616c206e6f74207375636365737366756040820152601b60fa1b606082015260800190565b60006020828403121561489457600080fd5b5051919050565b600081518084526020808501945080840160005b8381101561451b5781516001600160a01b0316875295820195908201906001016148af565b600082825180855260208086019550808260051b84010181860160005b8481101561491f57601f1986840301895261490d838351613fb9565b988401989250908301906001016148f1565b5090979650505050505050565b60a08152600061493f60a083018861489b565b828103602084015261495181886144eb565b9050828103604084015261496581876148d4565b60608401959095525050608001529392505050565b60c08152600061498d60c083018961489b565b828103602084015261499f81896144eb565b905082810360408401526149b381886148d4565b60608401969096525050608081019290925260a0909101529392505050565b634e487b7160e01b600052601160045260246000fd5b80820180821115610ad157610ad16149d2565b600060208284031215614a0d57600080fd5b815180151581146118a557600080fd5b600060208284031215614a2f57600080fd5b81516001600160401b03811115614a4557600080fd5b8201601f81018413614a5657600080fd5b8051614a64613e8682613e51565b818152856020838501011115614a7957600080fd5b61218c826020830160208601613f95565b81810381811115610ad157610ad16149d2565b634e487b7160e01b600052603260045260246000fd5b600060208284031215614ac557600080fd5b81516001600160401b03811681146118a557600080fd5b608081526000614aef608083018761489b565b8281036020840152614b0181876144eb565b90508281036040840152614b1581866148d4565b91505082606083015295945050505050565b84815260ff8416602082015282604082015260806060820152600061116a6080830184613fb9565b85815260ff8516602082015283604082015260a060608201526000614b7760a0830185613fb9565b8281036080840152614b898185613fb9565b98975050505050505050565b600060018201614ba757614ba76149d2565b5060010190565b60208082526021908201527f476f7665726e6f723a20696e76616c69642070726f706f73616c206c656e67746040820152600d60fb1b606082015260800190565b60006101208b8352602060018060a01b038c1681850152816040850152614c188285018c61489b565b91508382036060850152614c2c828b6144eb565b915083820360808501528189518084528284019150828160051b850101838c0160005b83811015614c7d57601f19878403018552614c6b838351613fb9565b94860194925090850190600101614c4f565b505086810360a0880152614c91818c6148d4565b9450505050508560c08401528460e0840152828103610100840152614cb68185613fb9565b9c9b505050505050505050505050565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b8082028115828204841417610ad157610ad16149d2565b634e487b7160e01b600052601260045260246000fd5b600082614d5b57634e487b7160e01b600052601260045260246000fd5b500490565b601f8211156128cf57600081815260208120601f850160051c81016020861015614d875750805b601f850160051c820191505b818110156120d057828155600101614d93565b81516001600160401b03811115614dbf57614dbf613e0b565b614dd381614dcd8454614807565b84614d60565b602080601f831160018114614e085760008415614df05750858301515b600019600386901b1c1916600185901b1785556120d0565b600085815260208120601f198616915b82811015614e3757888601518255948401946001909101908401614e18565b5085821015614e555787850151600019600388901b60f8161c191681555b5050505050600190811b0190555056fe476f7665726e6f723a2072656c617920726576657274656420776974686f7574206d657373616765a2646970667358221220909a271346e4315b690b0a6a2c16e591688ebafe433a43ba63a295dc9c45d0bd64736f6c63430008110033