Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
- Contract name:
- RewardsHubCooldown_Taiko
- Optimization enabled
- true
- Compiler version
- v0.8.17+commit.8df45f5f
- Optimization runs
- 200
- EVM Version
- default
- Verified at
- 2024-06-02T10:52:36.414063Z
contracts/multichain/taiko/RewardsHubCooldown_Taiko.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "../../libraries/ErrorCodes.sol";
import "./interfaces/IRewardsHubCooldown_Taiko.sol";
import "./RewardsHubLight_Taiko.sol";
contract RewardsHubCooldown_Taiko is IRewardsHubCooldown_Taiko, RewardsHubLight_Taiko {
using SafeCast for uint256;
using SafeERC20Upgradeable for IMntMirror;
// // // // // // Cooldown logic
/// @dev Charge length
uint256 public constant CHARGE_LENGTH = 30 days;
/// @dev The number of charges that can be made by user. Length of cooldown period.
uint256 public numberOfCharges;
/// @dev The share of total available amount that can be charged during one period.
uint256 public chargeShare;
/// @dev The time when cooldown period starts.
uint32 public cooldownStartTimestamp;
/// @dev Contatins counters of charges made by user.
mapping(address => uint256) public charges;
// // // // // // Overrides
/// @inheritdoc IRewardsHubCooldown_Taiko
function withdraw(uint256 amount)
external
virtual
override(IRewardsHubCooldown_Taiko, IRewardsHubLight, RewardsHubLight)
checkPaused(WITHDRAW_OP)
{
if (isCooldownActive()) {
cooldownWithdraw(msg.sender);
} else {
uint256 balance = balances[msg.sender];
if (amount == type(uint256).max) amount = balance;
require(amount <= balance, ErrorCodes.INCORRECT_AMOUNT);
balances[msg.sender] = balance - amount;
emit Withdraw(msg.sender, amount);
mnt.safeTransfer(msg.sender, amount);
if (amount > 0) {
buyback().updateBuybackAndVotingWeights(msg.sender);
}
}
}
/// @inheritdoc IRewardsHubCooldown_Taiko
function availableBalanceOfCooldown(address account) external view virtual returns (uint256) {
if (!isCooldownActive()) return 0;
uint256 availableCharges = getAvailableCharges(account);
return calculateAvailableBalanceOfCooldown(availableCharges, balances[account]);
}
// // // // Admin functions
/// @inheritdoc IRewardsHubCooldown_Taiko
function setNumberOfCharges(uint256 newNumberOfCharges) external onlyRole(TIMELOCK) {
require(newNumberOfCharges > numberOfCharges, ErrorCodes.RH_INCORRECT_NUMBER_OF_CHARGES);
numberOfCharges = newNumberOfCharges;
emit NumberOfChargesUpdated(newNumberOfCharges);
}
/// @inheritdoc IRewardsHubCooldown_Taiko
function setChargeShare(uint256 newChargeShare) external onlyRole(TIMELOCK) {
require(newChargeShare > 0 && newChargeShare <= 1e18, ErrorCodes.RH_INCORRECT_CHARGE_SHARE);
chargeShare = newChargeShare;
emit ChargeShareUpdated(newChargeShare);
}
/// @inheritdoc IRewardsHubCooldown_Taiko
function setCooldownStartTimestamp(uint32 startTimestamp) external onlyRole(TIMELOCK) {
require(cooldownStartTimestamp == 0, ErrorCodes.RH_COOLDOWN_START_ALREADY_SET);
require(startTimestamp >= getTimestamp(), ErrorCodes.RH_INCORRECT_COOLDOWN_START);
cooldownStartTimestamp = startTimestamp;
emit CooldownStartTimestampSet(startTimestamp);
}
// // // // Cooldown logic
/// @inheritdoc IRewardsHubCooldown_Taiko
function getCooldownEndTimestamp() public view virtual returns (uint32) {
return cooldownStartTimestamp + (CHARGE_LENGTH * numberOfCharges).toUint32();
}
/// @inheritdoc IRewardsHubCooldown_Taiko
function isCooldownFinished() public view virtual returns (bool) {
return isCooldownConfigured() && getTimestamp() >= getCooldownEndTimestamp();
}
/// @inheritdoc IRewardsHubCooldown_Taiko
function isCooldownConfigured() public view virtual returns (bool) {
return numberOfCharges > 0 && chargeShare > 0 && cooldownStartTimestamp > 0;
}
/// @inheritdoc IRewardsHubCooldown_Taiko
function isCooldownActive() public view virtual returns (bool) {
return cooldownStartTimestamp <= getTimestamp() && getTimestamp() < getCooldownEndTimestamp();
}
/// @inheritdoc IRewardsHubCooldown_Taiko
function getAvailableCharges(address account) public view virtual returns (uint256) {
if (!isCooldownActive()) return 0;
uint256 timeDelta = getTimestamp() - cooldownStartTimestamp;
uint256 chargesUnlocked = timeDelta / CHARGE_LENGTH;
return chargesUnlocked - charges[account];
}
function calculateAvailableBalanceOfCooldown(uint256 availableCharges, uint256 balance)
internal
view
virtual
returns (uint256)
{
if (availableCharges == 0) return 0;
uint256 share = chargeShare;
uint256 amount = 0;
for (uint256 i = 0; i < availableCharges; i++) {
uint256 chargeAmount = (balance * share) / EXP_SCALE;
balance -= chargeAmount;
amount += chargeAmount;
}
return amount;
}
function cooldownWithdraw(address account) internal virtual {
uint256 balance = balances[account];
uint256 availableCharges = getAvailableCharges(account);
uint256 amount = calculateAvailableBalanceOfCooldown(availableCharges, balance);
balances[account] -= amount;
charges[account] += availableCharges;
emit Withdraw(account, amount);
mnt.safeTransfer(account, amount);
if (amount > 0) {
buyback().updateBuybackAndVotingWeights(account);
}
}
function getTimestamp() internal view virtual returns (uint32) {
return block.timestamp.toUint32();
}
}
@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);
}
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 = 0x1670000000000000000000000000000000010001;
}
@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));
}
}
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);
}
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;
}
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/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/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
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;
}
contracts/RewardsHubLight.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./interfaces/IBDSystem.sol";
import "./interfaces/IEmissionBooster.sol";
import "./interfaces/IMntMirror.sol";
import "./interfaces/IMToken.sol";
import "./libraries/ErrorCodes.sol";
import "./libraries/PauseControl.sol";
import "./InterconnectorLeaf.sol";
contract RewardsHubLight is
IRewardsHubLight,
Initializable,
ReentrancyGuard,
AccessControl,
PauseControl,
InterconnectorLeaf
{
using SafeCast for uint256;
using SafeERC20Upgradeable for IMntMirror;
struct IndexState {
uint224 index;
uint32 block; // block number of the last index update
}
/// @dev The right part is the keccak-256 hash of "GATEKEEPER"
bytes32 public constant GATEKEEPER = bytes32(0x20162831d2f54c3e11eebafebfeda495d4c52c67b1708251179ec91fb76dd3b2);
/// @dev Value is the Keccak-256 hash of "TIMELOCK"
bytes32 public constant TIMELOCK = bytes32(0xaefebe170cbaff0af052a32795af0e1b8afff9850f946ad2869be14f35534371);
uint256 internal constant EXP_SCALE = 1e18;
uint256 internal constant DOUBLE_SCALE = 1e36;
/// @notice The initial MNT index for a market
uint224 internal constant MNT_INITIAL_INDEX = 1e36;
IMntMirror public mnt;
IEmissionBooster public emissionBooster;
IBDSystem public bdSystem;
/// @dev Contains amounts of regular rewards for individual accounts.
mapping(address => uint256) public balances;
// // // // // // MNT emissions
/// @dev The rate at which MNT is distributed to the corresponding supply market (per block)
mapping(IMToken => uint256) public mntSupplyEmissionRate;
/// @dev The rate at which MNT is distributed to the corresponding borrow market (per block)
mapping(IMToken => uint256) public mntBorrowEmissionRate;
/// @dev The MNT market supply state for each market
mapping(IMToken => IndexState) public mntSupplyState;
/// @dev The MNT market borrow state for each market
mapping(IMToken => IndexState) public mntBorrowState;
/// @dev The MNT supply index and block number for each market
/// for each supplier as of the last time they accrued MNT
mapping(IMToken => mapping(address => IndexState)) public mntSupplierState;
/// @dev The MNT borrow index and block number for each market
/// for each supplier as of the last time they accrued MNT
mapping(IMToken => mapping(address => IndexState)) public mntBorrowerState;
/**
* @notice Initialise RewardsHub contract
* @param admin_ admin address
* @param mnt_ Mnt contract address
* @param emissionBooster_ EmissionBooster contract address
* @param bdSystem_ BDSystem contract address
*/
function initialize(
address admin_,
IMntMirror mnt_,
IEmissionBooster emissionBooster_,
IBDSystem bdSystem_
) public virtual initializer {
_grantRole(DEFAULT_ADMIN_ROLE, admin_);
_grantRole(GATEKEEPER, admin_);
_grantRole(TIMELOCK, admin_);
mnt = mnt_;
emissionBooster = emissionBooster_;
bdSystem = bdSystem_;
}
// // // // Getters
/// @inheritdoc IRewardsHubLight
function totalBalanceOf(address account) external view virtual returns (uint256) {
return balances[account];
}
/// @inheritdoc IRewardsHubLight
function availableBalanceOf(address account) external view virtual returns (uint256) {
return balances[account];
}
// // // // MNT emissions
/// @inheritdoc IRewardsHubLight
function initMarket(IMToken mToken) external virtual {
require(msg.sender == address(supervisor()), ErrorCodes.UNAUTHORIZED);
require(
mntSupplyState[mToken].index == 0 && mntBorrowState[mToken].index == 0,
ErrorCodes.MARKET_ALREADY_LISTED
);
// Initialize MNT emission indexes of the market
uint32 currentBlock = getBlockNumber();
mntSupplyState[mToken] = IndexState({index: MNT_INITIAL_INDEX, block: currentBlock});
mntBorrowState[mToken] = IndexState({index: MNT_INITIAL_INDEX, block: currentBlock});
}
/**
* @dev Calculates the new state of the market.
* @param state The block number the index was last updated at and the market's last updated mntBorrowIndex
* or mntSupplyIndex in this block
* @param emissionRate MNT rate that each market currently receives (supply or borrow)
* @param totalBalance Total market balance (totalSupply or totalBorrow)
* Note: this method doesn't return anything, it only mutates memory variable `state`.
*/
function calculateUpdatedMarketState(
IndexState memory state,
uint256 emissionRate,
uint256 totalBalance
) internal view virtual {
uint256 blockNumber = getBlockNumber();
if (emissionRate > 0) {
uint256 deltaBlocks = blockNumber - state.block;
uint256 mntAccrued_ = deltaBlocks * emissionRate;
uint256 ratio = totalBalance > 0 ? (mntAccrued_ * DOUBLE_SCALE) / totalBalance : 0;
// index = lastUpdatedIndex + deltaBlocks * emissionRate / amount
state.index += ratio.toUint224();
}
state.block = uint32(blockNumber);
}
/**
* @dev Gets current market state (the block number and MNT supply index)
* @param mToken The market whose MNT supply index to get
*/
function getUpdatedMntSupplyIndex(IMToken mToken) internal view virtual returns (IndexState memory supplyState) {
supplyState = mntSupplyState[mToken];
require(supplyState.index >= MNT_INITIAL_INDEX, ErrorCodes.MARKET_NOT_LISTED);
calculateUpdatedMarketState(supplyState, mntSupplyEmissionRate[mToken], mToken.totalSupply());
return supplyState;
}
/**
* @dev Gets current market state (the block number and MNT supply index)
* @param mToken The market whose MNT supply index to get
*/
function getUpdatedMntBorrowIndex(IMToken mToken, uint224 marketBorrowIndex)
internal
view
virtual
returns (IndexState memory borrowState)
{
borrowState = mntBorrowState[mToken];
require(borrowState.index >= MNT_INITIAL_INDEX, ErrorCodes.MARKET_NOT_LISTED);
uint256 borrowAmount = (mToken.totalBorrows() * EXP_SCALE) / marketBorrowIndex;
calculateUpdatedMarketState(borrowState, mntBorrowEmissionRate[mToken], borrowAmount);
return borrowState;
}
/**
* @dev Accrue MNT to the market by updating the MNT supply index.
* Index is a cumulative sum of the MNT per mToken accrued.
* @param mToken The market whose MNT supply index to update
*/
function updateMntSupplyIndex(IMToken mToken) internal virtual {
uint32 lastUpdatedBlock = mntSupplyState[mToken].block;
if (lastUpdatedBlock == getBlockNumber()) return;
if (emissionBooster.isEmissionBoostingEnabled()) {
uint224 lastUpdatedIndex = mntSupplyState[mToken].index;
IndexState memory currentState = getUpdatedMntSupplyIndex(mToken);
mntSupplyState[mToken] = currentState;
// slither-disable-next-line reentrancy-no-eth,reentrancy-benign,reentrancy-events
emissionBooster.updateSupplyIndexesHistory(mToken, lastUpdatedBlock, lastUpdatedIndex, currentState.index);
} else {
mntSupplyState[mToken] = getUpdatedMntSupplyIndex(mToken);
}
}
/**
* @dev Accrue MNT to the market by updating the MNT borrow index.
* Index is a cumulative sum of the MNT per mToken accrued.
* @param mToken The market whose MNT borrow index to update
* @param marketBorrowIndex The market's last updated BorrowIndex
*/
function updateMntBorrowIndex(IMToken mToken, uint224 marketBorrowIndex) internal virtual {
uint32 lastUpdatedBlock = mntBorrowState[mToken].block;
if (lastUpdatedBlock == getBlockNumber()) return;
if (emissionBooster.isEmissionBoostingEnabled()) {
uint224 lastUpdatedIndex = mntBorrowState[mToken].index;
IndexState memory currentState = getUpdatedMntBorrowIndex(mToken, marketBorrowIndex);
mntBorrowState[mToken] = currentState;
// slither-disable-next-line reentrancy-no-eth,reentrancy-benign,reentrancy-events
emissionBooster.updateBorrowIndexesHistory(mToken, lastUpdatedBlock, lastUpdatedIndex, currentState.index);
} else {
mntBorrowState[mToken] = getUpdatedMntBorrowIndex(mToken, marketBorrowIndex);
}
}
/// @inheritdoc IRewardsHubLight
function updateAndGetMntIndexes(IMToken market) external virtual returns (uint224, uint224) {
IndexState memory supplyState = getUpdatedMntSupplyIndex(market);
mntSupplyState[market] = supplyState;
uint224 borrowIndex = market.borrowIndex().toUint224();
IndexState memory borrowState = getUpdatedMntBorrowIndex(market, borrowIndex);
mntBorrowState[market] = borrowState;
return (supplyState.index, borrowState.index);
}
struct EmissionsDistributionVars {
address account;
address representative;
uint256 representativeBonus;
uint256 liquidityProviderBoost;
uint256 accruedMnt;
}
/// @dev Basically EmissionsDistributionVars constructor
function initDistribution(address account)
internal
view
virtual
checkPaused(DISTRIBUTION_OP)
returns (EmissionsDistributionVars memory vars)
{
vars.account = account;
(
vars.liquidityProviderBoost,
vars.representativeBonus,
,
// ^^^ skips endBlock
vars.representative
) = bdSystem.providerToAgreement(account);
}
/// @dev Accrues MNT emissions of account per market and saves result to EmissionsDistributionVars
function updateDistributionState(
EmissionsDistributionVars memory vars,
IMToken mToken,
uint256 accountBalance,
uint224 currentMntIndex,
IndexState storage accountIndex,
bool isSupply
) internal virtual {
uint32 currentBlock = getBlockNumber();
uint224 lastAccountIndex = accountIndex.index;
uint32 lastUpdateBlock = accountIndex.block;
if (lastAccountIndex == 0 && currentMntIndex >= MNT_INITIAL_INDEX) {
// Covers the case where users interacted with market before its state index was set.
// Rewards the user with MNT accrued from the start of when account rewards were first
// set for the market.
lastAccountIndex = MNT_INITIAL_INDEX;
lastUpdateBlock = currentBlock;
}
// Update supplier's index and block to the current index and block since we are distributing accrued MNT
accountIndex.index = currentMntIndex;
accountIndex.block = currentBlock;
if (currentMntIndex == lastAccountIndex) return;
uint256 deltaIndex = currentMntIndex - lastAccountIndex;
if (vars.representative != address(0)) {
// Calc change in the cumulative sum of the MNT per mToken accrued (with considering BD system boosts)
deltaIndex += (deltaIndex * vars.liquidityProviderBoost) / EXP_SCALE;
} else {
// Calc change in the cumulative sum of the MNT per mToken accrued (with considering NFT emission boost).
// NFT emission boost doesn't work with liquidity provider emission boost at the same time.
deltaIndex += emissionBooster.calculateEmissionBoost(
mToken,
vars.account,
lastAccountIndex,
lastUpdateBlock,
currentMntIndex,
isSupply
);
}
uint256 accruedMnt = (accountBalance * deltaIndex) / DOUBLE_SCALE;
vars.accruedMnt += accruedMnt;
if (isSupply) emit DistributedSupplierMnt(mToken, vars.account, accruedMnt, currentMntIndex);
else emit DistributedBorrowerMnt(mToken, vars.account, accruedMnt, currentMntIndex);
}
/// @dev Accumulate accrued MNT to user balance and its BDR representative if they have any.
/// Also updates buyback and voting weights for user
function payoutDistributionState(EmissionsDistributionVars memory vars) internal virtual {
if (vars.accruedMnt == 0) return;
balances[vars.account] += vars.accruedMnt;
emit EmissionRewardAccrued(vars.account, vars.accruedMnt);
if (vars.representative != address(0)) {
uint256 repReward = (vars.accruedMnt * vars.representativeBonus) / EXP_SCALE;
balances[vars.representative] += repReward;
emit RepresentativeRewardAccrued(vars.representative, vars.account, repReward);
}
// Use relaxed update so it could skip if buyback update is paused
buyback().updateBuybackAndVotingWeightsRelaxed(vars.account);
}
/// @inheritdoc IRewardsHubLight
function distributeSupplierMnt(IMToken mToken, address account) external virtual {
updateMntSupplyIndex(mToken);
EmissionsDistributionVars memory vars = initDistribution(account);
uint256 supplyAmount = mToken.balanceOf(account);
updateDistributionState(
vars,
mToken,
supplyAmount,
mntSupplyState[mToken].index,
mntSupplierState[mToken][account],
true
);
payoutDistributionState(vars);
}
/// @inheritdoc IRewardsHubLight
function distributeBorrowerMnt(IMToken mToken, address account) external virtual {
uint224 borrowIndex = mToken.borrowIndex().toUint224();
updateMntBorrowIndex(mToken, borrowIndex);
EmissionsDistributionVars memory vars = initDistribution(account);
uint256 borrowAmount = (mToken.borrowBalanceStored(account) * EXP_SCALE) / borrowIndex;
updateDistributionState(
vars,
mToken,
borrowAmount,
mntBorrowState[mToken].index,
mntBorrowerState[mToken][account],
false
);
payoutDistributionState(vars);
}
/// @inheritdoc IRewardsHubLight
function distributeAllMnt(address account) external virtual nonReentrant {
return distributeAccountMnt(account, supervisor().getAllMarkets(), true, true);
}
/// @inheritdoc IRewardsHubLight
function distributeMnt(
address[] calldata accounts,
IMToken[] calldata mTokens,
bool borrowers,
bool suppliers
) external virtual nonReentrant {
ISupervisor cachedSupervisor = supervisor();
for (uint256 i = 0; i < mTokens.length; i++) {
require(cachedSupervisor.isMarketListed(mTokens[i]), ErrorCodes.MARKET_NOT_LISTED);
}
for (uint256 i = 0; i < accounts.length; i++) {
distributeAccountMnt(accounts[i], mTokens, borrowers, suppliers);
}
}
function distributeAccountMnt(
address account,
IMToken[] memory mTokens,
bool borrowers,
bool suppliers
) internal virtual {
EmissionsDistributionVars memory vars = initDistribution(account);
for (uint256 i = 0; i < mTokens.length; i++) {
IMToken mToken = mTokens[i];
if (borrowers) {
uint256 accountBorrowUnderlying = mToken.borrowBalanceStored(account);
if (accountBorrowUnderlying > 0) {
uint224 borrowIndex = mToken.borrowIndex().toUint224();
updateMntBorrowIndex(mToken, borrowIndex);
updateDistributionState(
vars,
mToken,
(accountBorrowUnderlying * EXP_SCALE) / borrowIndex,
mntBorrowState[mToken].index,
mntBorrowerState[mToken][account],
false
);
}
}
if (suppliers) {
uint256 accountSupplyWrap = mToken.balanceOf(account);
if (accountSupplyWrap > 0) {
updateMntSupplyIndex(mToken);
updateDistributionState(
vars,
mToken,
accountSupplyWrap,
mntSupplyState[mToken].index,
mntSupplierState[mToken][account],
true
);
}
}
}
payoutDistributionState(vars);
}
// // // // Rewards accrual
/// @inheritdoc IRewardsHubLight
function accrueBuybackReward(address account, uint256 amount) external virtual {
require(msg.sender == address(buyback()), ErrorCodes.UNAUTHORIZED);
balances[account] += amount;
emit BuybackRewardAccrued(account, amount);
// Do not update weights because they should be checked in Buyback after this call.
}
// // // // Withdrawal
/// @inheritdoc IRewardsHubLight
function withdraw(uint256 amount) external virtual checkPaused(WITHDRAW_OP) {
uint256 balance = balances[msg.sender];
if (amount == type(uint256).max) amount = balance;
require(amount <= balance, ErrorCodes.INCORRECT_AMOUNT);
balances[msg.sender] = balance - amount;
emit Withdraw(msg.sender, amount);
mnt.safeTransfer(msg.sender, amount);
if (amount > 0) {
buyback().updateBuybackAndVotingWeights(msg.sender);
}
}
/// @inheritdoc IRewardsHubLight
function grant(address recipient, uint256 amount) external virtual onlyRole(DEFAULT_ADMIN_ROLE) {
require(amount > 0, ErrorCodes.INCORRECT_AMOUNT);
uint256 balance = mnt.balanceOf(address(this));
require(balance >= amount, ErrorCodes.INSUFFICIENT_MNT_FOR_GRANT);
emit MntGranted(recipient, amount);
mnt.safeTransfer(recipient, amount);
}
// // // // Admin zone
/// @inheritdoc IRewardsHubLight
function setMntEmissionRates(
IMToken mToken,
uint256 newMntSupplyEmissionRate,
uint256 newMntBorrowEmissionRate
) external onlyRole(TIMELOCK) {
require(supervisor().isMarketListed(mToken), ErrorCodes.MARKET_NOT_LISTED);
if (mntSupplyEmissionRate[mToken] != newMntSupplyEmissionRate) {
// Supply emission rate updated so let's update supply state to ensure that
// 1. MNT accrued properly for the old emission rate.
// 2. MNT accrued at the new speed starts after this block.
updateMntSupplyIndex(mToken);
// Update emission rate and emit event
mntSupplyEmissionRate[mToken] = newMntSupplyEmissionRate;
emit MntSupplyEmissionRateUpdated(mToken, newMntSupplyEmissionRate);
}
if (mntBorrowEmissionRate[mToken] != newMntBorrowEmissionRate) {
// Borrow emission rate updated so let's update borrow state to ensure that
// 1. MNT accrued properly for the old emission rate.
// 2. MNT accrued at the new speed starts after this block.
uint224 borrowIndex = mToken.borrowIndex().toUint224();
updateMntBorrowIndex(mToken, borrowIndex);
// Update emission rate and emit event
mntBorrowEmissionRate[mToken] = newMntBorrowEmissionRate;
emit MntBorrowEmissionRateUpdated(mToken, newMntBorrowEmissionRate);
}
}
// // // // Pause control
bytes32 internal constant DISTRIBUTION_OP = "MntDistribution";
bytes32 internal constant WITHDRAW_OP = "Withdraw";
function validatePause(address) internal view virtual override {
require(hasRole(GATEKEEPER, msg.sender), ErrorCodes.UNAUTHORIZED);
}
function validateUnpause(address) internal view virtual override {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), ErrorCodes.UNAUTHORIZED);
}
// // // // Utils
function getBlockNumber() internal view virtual returns (uint32) {
return uint32(block.number);
}
function supervisor() internal view virtual returns (ISupervisor) {
return getInterconnector().supervisor();
}
function buyback() internal view virtual returns (IBuyback) {
return getInterconnector().buyback();
}
}
@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);
}
}
}
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/multichain/taiko/interfaces/IRewardsHubLight_Taiko.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;
import "../../../interfaces/IRewardsHubLight.sol";
import "./IIncentiveEmissionHub.sol";
interface IRewardsHubLight_Taiko is IRewardsHubLight {
event IncentiveEmissionHubUpdated(IIncentiveEmissionHub newIncentiveEmissionHub);
/**
* @notice Sets a new value for incentiveEmissionHub
* @dev RESTRICTION: Admin only
*/
function setIncentiveEmissionHub(IIncentiveEmissionHub newIncentiveEmissionHub) external;
}
@openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```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 AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_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 ",
Strings.toHexString(account),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* 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());
}
}
}
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;
}
contracts/layerZero/interfaces/oft/IOFTCore.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.9;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Interface of the IOFT core standard
*/
interface IOFTCore is IERC165 {
/**
* @dev estimate send token `_tokenId` to (`_dstChainId`, `_toAddress`)
* _dstChainId - L0 defined chain id to send tokens too
* _toAddress - dynamic bytes array which contains the address to whom you are sending tokens to on the dstChain
* _amount - amount of the tokens to transfer
* _useZro - indicates to use zro to pay L0 fees
* _adapterParam - flexible bytes array to indicate messaging adapter services in L0
*/
function estimateSendFee(
uint16 _dstChainId,
bytes calldata _toAddress,
uint256 _amount,
bool _useZro,
bytes calldata _adapterParams
) external view returns (uint256 nativeFee, uint256 zroFee);
/**
* @dev send `_amount` amount of token to (`_dstChainId`, `_toAddress`) from `_from`
* `_from` the owner of token
* `_dstChainId` the destination chain identifier
* `_toAddress` can be any size depending on the `dstChainId`.
* `_amount` the quantity of tokens in wei
* `_refundAddress` the address LayerZero refunds if too much message fee is sent
* `_zroPaymentAddress` set to address(0x0) if not paying in ZRO (LayerZero Token)
* `_adapterParams` is a flexible bytes array to indicate messaging adapter services
*/
function sendFrom(
address _from,
uint16 _dstChainId,
bytes calldata _toAddress,
uint256 _amount,
address payable _refundAddress,
address _zroPaymentAddress,
bytes calldata _adapterParams
) external payable;
/**
* @dev returns the circulating amount of tokens on current chain
*/
function circulatingSupply() external view returns (uint256);
/**
* @dev returns the address of the ERC20 token
*/
function token() external view returns (address);
/**
* @dev Emitted when `_amount` tokens are moved from the `_sender` to (`_dstChainId`, `_toAddress`)
* `_nonce` is the outbound nonce
*/
event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes _toAddress, uint256 _amount);
/**
* @dev Emitted when `_amount` tokens are received from `_srcChainId` into the `_toAddress` on the local chain.
* `_nonce` is the inbound nonce.
*/
event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint256 _amount);
event SetUseCustomAdapterParams(bool _useCustomAdapterParams);
}
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());
}
}
@openzeppelin/contracts/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/Address.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since 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) || (!Address.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;
}
}
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/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/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);
}
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/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/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/multichain/taiko/interfaces/IIncentiveEmissionHub.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;
import "../../../interfaces/IRewardsHubLight.sol";
interface IIncentiveEmissionHub {
event RewardWithdraw(address account, uint256 amount);
event RewardGranted(address recipient, uint256 amount);
event RewardAssigned(address recipient, uint256 amount);
event SupplyCoefficientUpdated(IMToken market, uint256 newSupplyCoefficient);
event BorrowCoefficientUpdated(IMToken market, uint256 newBorrowCoefficient);
event NewIncentiveToken(address newIncentiveToken);
/**
* @notice Gets the address of incentive token contract
*/
function token() external view returns (IERC20);
/**
* @notice Gets the address of rewardsHub contract
*/
function rewardsHub() external view returns (IRewardsHubLight);
/**
* @notice Gets the reward coefficient for exact market and supply operation
*/
function rewardSupplyCoefficient(IMToken market) external view returns (uint256);
/**
* @notice Gets the reward coefficient for exact market and borrow operation
*/
function rewardBorrowCoefficient(IMToken market) external view returns (uint256);
/**
* @notice Gets keccak-256 hash of gatekeeper
*/
function GATEKEEPER() external view returns (bytes32);
/**
* @notice Converts base rewards to incentive rewards using rewardCoefficient wrt market and operation type
*/
function calculateIncentiveRewards(
IMToken market,
uint256 accruedBaseReward,
bool isSupply
) external view returns (uint256);
/**
* @notice Accumulates accrued rewards to user balance
* @dev RESTRICTION: rewardsHub only
*/
function assignRewards(address account, uint256 rewardsAmount) external;
/**
* @notice Sets a new coefficient to convert supplier basic rewards from exact market
* @dev RESTRICTION: Admin only
*/
function setRewardSupplyCoefficient(IMToken market, uint256 newSupplyCoefficient) external;
/**
* @notice Sets a new coefficient to convert borrower basic rewards from exact market
* @dev RESTRICTION: Admin only
*/
function setRewardBorrowCoefficient(IMToken market, uint256 newBorrowCoefficient) external;
/**
* @notice Transfers available part of rewards to the sender.
* This will decrease accounts buyback and voting weights.
*/
function withdraw(uint256 amount) external;
/**
* @notice Grants specific amount of tokens to the recipient address
* @dev RESTRICTION: Admin only
*/
function grant(address recipient, uint256 amount) external;
/**
* @notice Sets incentive token address if it was set to zero during deployment
* @dev RESTRICTION: Admin only
*/
function setIncentiveToken(IERC20 newIncentiveToken) external;
}
contracts/multichain/taiko/RewardsHubLight_Taiko.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;
import "../../RewardsHubLight.sol";
import "./libraries/TaikoContracts.sol";
import "./interfaces/IRewardsHubLight_Taiko.sol";
import "./interfaces/ITaikoL2_L1BlockNumber.sol";
contract RewardsHubLight_Taiko is IRewardsHubLight_Taiko, RewardsHubLight {
using SafeCast for uint64;
using SafeCast for uint256;
IIncentiveEmissionHub public incentiveEmissionHub;
struct EmissionsDistributionVarsExtended {
EmissionsDistributionVars basicEmission;
IncentiveEmissionVars incentiveEmission;
}
struct IncentiveEmissionVars {
uint256 taikoRewardTokenAmount;
}
/// @dev Returns block number from L1 network.
/// Note! Block number from L1 returns with the delay
function getBlockNumber() internal view virtual override returns (uint32 bn) {
return ITaikoL2_L1BlockNumber(TaikoContracts.TaikoL2).lastSyncedBlock().toUint32();
}
/// @dev Basically EmissionsDistributionVarsExtended constructor
function initDistributionExtended(address account)
internal
view
virtual
checkPaused(DISTRIBUTION_OP)
returns (EmissionsDistributionVarsExtended memory vars)
{
vars.basicEmission = initDistribution(account);
}
/// @inheritdoc IRewardsHubLight
function distributeSupplierMnt(IMToken mToken, address account)
external
virtual
override(IRewardsHubLight, RewardsHubLight)
{
updateMntSupplyIndex(mToken);
EmissionsDistributionVarsExtended memory vars = initDistributionExtended(account);
uint256 supplyAmount = mToken.balanceOf(account);
updateDistributionState(
vars,
mToken,
supplyAmount,
mntSupplyState[mToken].index,
mntSupplierState[mToken][account],
true
);
payoutDistributionState(vars.basicEmission, vars.incentiveEmission);
}
/// @inheritdoc IRewardsHubLight
function distributeBorrowerMnt(IMToken mToken, address account)
external
virtual
override(IRewardsHubLight, RewardsHubLight)
{
uint224 borrowIndex = mToken.borrowIndex().toUint224();
updateMntBorrowIndex(mToken, borrowIndex);
EmissionsDistributionVarsExtended memory vars = initDistributionExtended(account);
uint256 borrowAmount = (mToken.borrowBalanceStored(account) * EXP_SCALE) / borrowIndex;
updateDistributionState(
vars,
mToken,
borrowAmount,
mntBorrowState[mToken].index,
mntBorrowerState[mToken][account],
false
);
payoutDistributionState(vars.basicEmission, vars.incentiveEmission);
}
function distributeAccountMnt(
address account,
IMToken[] memory mTokens,
bool borrowers,
bool suppliers
) internal virtual override {
EmissionsDistributionVarsExtended memory vars = initDistributionExtended(account);
for (uint256 i = 0; i < mTokens.length; i++) {
IMToken mToken = mTokens[i];
if (borrowers) {
uint256 accountBorrowUnderlying = mToken.borrowBalanceStored(account);
if (accountBorrowUnderlying > 0) {
uint224 borrowIndex = mToken.borrowIndex().toUint224();
updateMntBorrowIndex(mToken, borrowIndex);
updateDistributionState(
vars,
mToken,
(accountBorrowUnderlying * EXP_SCALE) / borrowIndex,
mntBorrowState[mToken].index,
mntBorrowerState[mToken][account],
false
);
}
}
if (suppliers) {
uint256 accountSupplyWrap = mToken.balanceOf(account);
if (accountSupplyWrap > 0) {
updateMntSupplyIndex(mToken);
updateDistributionState(
vars,
mToken,
accountSupplyWrap,
mntSupplyState[mToken].index,
mntSupplierState[mToken][account],
true
);
}
}
}
payoutDistributionState(vars.basicEmission, vars.incentiveEmission);
}
/// @dev This function is intentionally hard disabled to prevent the execution of an unexpected or outdated version.
function updateDistributionState(
EmissionsDistributionVars memory,
IMToken,
uint256,
uint224,
IndexState storage,
bool
) internal pure virtual override {
require(false, "UNEXPECTED VERSION OF FUNCTION USED");
}
function updateDistributionState(
EmissionsDistributionVarsExtended memory vars,
IMToken mToken,
uint256 accountBalance,
uint224 currentMntIndex,
IndexState storage accountIndex,
bool isSupply
) internal virtual {
uint32 currentBlock = getBlockNumber();
uint224 lastAccountIndex = accountIndex.index;
uint32 lastUpdateBlock = accountIndex.block;
if (lastAccountIndex == 0 && currentMntIndex >= MNT_INITIAL_INDEX) {
// Covers the case where users interacted with market before its state index was set.
// Rewards the user with MNT accrued from the start of when account rewards were first
// set for the market.
lastAccountIndex = MNT_INITIAL_INDEX;
lastUpdateBlock = currentBlock;
}
// Update supplier's index and block to the current index and block since we are distributing accrued MNT
accountIndex.index = currentMntIndex;
accountIndex.block = currentBlock;
if (currentMntIndex == lastAccountIndex) return;
uint256 deltaIndex = currentMntIndex - lastAccountIndex;
if (vars.basicEmission.representative != address(0)) {
// Calc change in the cumulative sum of the MNT per mToken accrued (with considering BD system boosts)
deltaIndex += (deltaIndex * vars.basicEmission.liquidityProviderBoost) / EXP_SCALE;
} else {
// Calc change in the cumulative sum of the MNT per mToken accrued (with considering NFT emission boost).
// NFT emission boost doesn't work with liquidity provider emission boost at the same time.
deltaIndex += emissionBooster.calculateEmissionBoost(
mToken,
vars.basicEmission.account,
lastAccountIndex,
lastUpdateBlock,
currentMntIndex,
isSupply
);
}
uint256 accruedMnt = (accountBalance * deltaIndex) / DOUBLE_SCALE;
vars.basicEmission.accruedMnt += accruedMnt;
accrueAdditionalRewards(mToken, accruedMnt, isSupply, vars.incentiveEmission);
if (isSupply) emit DistributedSupplierMnt(mToken, vars.basicEmission.account, accruedMnt, currentMntIndex);
else emit DistributedBorrowerMnt(mToken, vars.basicEmission.account, accruedMnt, currentMntIndex);
}
/// @dev This function is intentionally hard disabled to prevent the execution of an unexpected or outdated version.
function payoutDistributionState(EmissionsDistributionVars memory) internal pure virtual override {
require(false, "UNEXPECTED VERSION OF FUNCTION USED");
}
function payoutDistributionState(
EmissionsDistributionVars memory vars,
IncentiveEmissionVars memory incentivizeVars
) internal virtual {
if (vars.accruedMnt == 0) return;
balances[vars.account] += vars.accruedMnt;
emit EmissionRewardAccrued(vars.account, vars.accruedMnt);
if (vars.representative != address(0)) {
uint256 repReward = (vars.accruedMnt * vars.representativeBonus) / EXP_SCALE;
balances[vars.representative] += repReward;
emit RepresentativeRewardAccrued(vars.representative, vars.account, repReward);
}
assignAdditionalRewards(vars.account, incentivizeVars.taikoRewardTokenAmount);
// Use relaxed update so it could skip if buyback update is paused
buyback().updateBuybackAndVotingWeightsRelaxed(vars.account);
}
/// @dev Accrue incentive rewards with regards to amount of base reward tokens
function accrueAdditionalRewards(
IMToken market,
uint256 baseRewardTokensAccrued,
bool isSupply,
IncentiveEmissionVars memory incentivizeVars
) internal view virtual {
if (address(incentiveEmissionHub) != address(0) && baseRewardTokensAccrued > 0) {
incentivizeVars.taikoRewardTokenAmount += incentiveEmissionHub.calculateIncentiveRewards(
market,
baseRewardTokensAccrued,
isSupply
);
}
}
/// @dev Accumulate accrued incentive rewards to user balance
function assignAdditionalRewards(address account, uint256 rewardsAmount) internal virtual {
if (address(incentiveEmissionHub) != address(0) && rewardsAmount > 0) {
incentiveEmissionHub.assignRewards(account, rewardsAmount);
}
}
/// @inheritdoc IRewardsHubLight_Taiko
function setIncentiveEmissionHub(IIncentiveEmissionHub newIncentiveEmissionHub)
external
virtual
onlyRole(DEFAULT_ADMIN_ROLE)
{
incentiveEmissionHub = newIncentiveEmissionHub;
emit IncentiveEmissionHubUpdated(newIncentiveEmissionHub);
}
}
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/libraries/PauseControl.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;
import "./ErrorCodes.sol";
abstract contract PauseControl {
event OperationPaused(bytes32 op, address subject);
event OperationUnpaused(bytes32 op, address subject);
mapping(address => mapping(bytes32 => bool)) internal pausedOps;
function validatePause(address subject) internal view virtual;
function validateUnpause(address subject) internal view virtual;
function isOperationPaused(bytes32 op, address subject) public view returns (bool) {
return pausedOps[subject][op];
}
function pauseOperation(bytes32 op, address subject) external virtual {
validatePause(subject);
require(!isOperationPaused(op, subject));
pausedOps[subject][op] = true;
emit OperationPaused(op, subject);
}
function unpauseOperation(bytes32 op, address subject) external virtual {
validateUnpause(subject);
require(isOperationPaused(op, subject));
pausedOps[subject][op] = false;
emit OperationUnpaused(op, subject);
}
modifier checkPausedSubject(bytes32 op, address subject) {
require(!isOperationPaused(op, subject), ErrorCodes.OPERATION_PAUSED);
_;
}
modifier checkPaused(bytes32 op) {
require(!isOperationPaused(op, address(0)), ErrorCodes.OPERATION_PAUSED);
_;
}
}
contracts/interfaces/IMntMirror.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.9;
import "./IMnt.sol";
import "../layerZero/interfaces/oft/IOFTCore.sol";
interface IMntMirror is IOFTCore, IMnt {}
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/interfaces/IRewardsHubCooldown_Taiko.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;
import "./IRewardsHubLight_Taiko.sol";
interface IRewardsHubCooldown_Taiko is IRewardsHubLight_Taiko {
event NumberOfChargesUpdated(uint256 newNumberOfCharges);
event ChargeShareUpdated(uint256 newChargeShare);
event CooldownStartTimestampSet(uint32 startTimestamp);
/**
* @notice Gets length of charge period
*/
function CHARGE_LENGTH() external view returns (uint256);
/**
* @notice Gets max number of charges for cooldown period
*/
function numberOfCharges() external view returns (uint256);
/**
* @notice Gets hare of total available amount that can be charged during one period
*/
function chargeShare() external view returns (uint256);
/**
* @notice Gets timestamp of cooldown start
*/
function cooldownStartTimestamp() external view returns (uint32);
/***
* @notice Gets timestamp of cooldown end
*/
function getCooldownEndTimestamp() external view returns (uint32);
/**
* @notice Gets cooldown logic status
*/
function isCooldownActive() external view returns (bool);
/**
* @notice Gets cooldown logic status (is finished)
*/
function isCooldownFinished() external view returns (bool);
/**
* @notice Gets cooldown logic status (is configured)
*/
function isCooldownConfigured() external view returns (bool);
/**
* @notice Gets number of charges made by user
*/
function charges(address user) external view returns (uint256);
/**
* @notice Gets number of currently available charges for the user
* @param account user's account
*/
function getAvailableCharges(address account) external view returns (uint256);
/**
* @notice If cooldown period is active withdraw is allowed only if user has enough charges
* Each charge give user right to withdraw chargeShare of his total available balance,
* in this case amount parameter is ignored
* If cooldown is not active, user can withdraw any amount
* @param amount amount to withdraw
*/
function withdraw(uint256 amount) external;
/**
* @notice If cooldown period is active, this function returns amount that user can withdraw right now
* If cooldown is not active, user balance is returned
* @param account user's account
*/
function availableBalanceOfCooldown(address account) external view returns (uint256);
/**
* @notice Set number of charges for cooldown period
* @param newNumberOfCharges number of charges for cooldown period
* @dev RESTRICTION Timelock only
*/
function setNumberOfCharges(uint256 newNumberOfCharges) external;
/**
* @notice Set share of total available amount that can be charged during one period
* @param newChargeShare share of total available amount that can be charged during one period
* @dev RESTRICTION Timelock only
*/
function setChargeShare(uint256 newChargeShare) external;
/**
* @notice Set coooldown start timestamp
* @param timestamp coooldown start timestamp
* @dev RESTRICTION Timelock only
*/
function setCooldownStartTimestamp(uint32 timestamp) external;
}
@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/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/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);
}
}
}
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/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/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/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}
@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
@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;
}
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":"event","name":"BuybackRewardAccrued","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ChargeShareUpdated","inputs":[{"type":"uint256","name":"newChargeShare","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"CooldownStartTimestampSet","inputs":[{"type":"uint32","name":"startTimestamp","internalType":"uint32","indexed":false}],"anonymous":false},{"type":"event","name":"DistributedBorrowerMnt","inputs":[{"type":"address","name":"mToken","internalType":"contract IMToken","indexed":false},{"type":"address","name":"borrower","internalType":"address","indexed":false},{"type":"uint256","name":"mntDelta","internalType":"uint256","indexed":false},{"type":"uint256","name":"mntBorrowIndex","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"DistributedSupplierMnt","inputs":[{"type":"address","name":"mToken","internalType":"contract IMToken","indexed":false},{"type":"address","name":"supplier","internalType":"address","indexed":false},{"type":"uint256","name":"mntDelta","internalType":"uint256","indexed":false},{"type":"uint256","name":"mntSupplyIndex","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"EmissionRewardAccrued","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"IncentiveEmissionHubUpdated","inputs":[{"type":"address","name":"newIncentiveEmissionHub","internalType":"contract IIncentiveEmissionHub","indexed":false}],"anonymous":false},{"type":"event","name":"Initialized","inputs":[{"type":"uint8","name":"version","internalType":"uint8","indexed":false}],"anonymous":false},{"type":"event","name":"LinkageRootSwitched","inputs":[{"type":"address","name":"newRoot","internalType":"contract ILinkageRoot","indexed":false},{"type":"address","name":"oldRoot","internalType":"contract ILinkageRoot","indexed":false}],"anonymous":false},{"type":"event","name":"MntBorrowEmissionRateUpdated","inputs":[{"type":"address","name":"mToken","internalType":"contract IMToken","indexed":false},{"type":"uint256","name":"newBorrowEmissionRate","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"MntGranted","inputs":[{"type":"address","name":"recipient","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"MntSupplyEmissionRateUpdated","inputs":[{"type":"address","name":"mToken","internalType":"contract IMToken","indexed":false},{"type":"uint256","name":"newSupplyEmissionRate","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"NumberOfChargesUpdated","inputs":[{"type":"uint256","name":"newNumberOfCharges","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"OperationPaused","inputs":[{"type":"bytes32","name":"op","internalType":"bytes32","indexed":false},{"type":"address","name":"subject","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"OperationUnpaused","inputs":[{"type":"bytes32","name":"op","internalType":"bytes32","indexed":false},{"type":"address","name":"subject","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"RepresentativeRewardAccrued","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false},{"type":"address","name":"provider","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"RoleAdminChanged","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"bytes32","name":"previousAdminRole","internalType":"bytes32","indexed":true},{"type":"bytes32","name":"newAdminRole","internalType":"bytes32","indexed":true}],"anonymous":false},{"type":"event","name":"RoleGranted","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"address","name":"sender","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"RoleRevoked","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"address","name":"sender","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"Withdraw","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"CHARGE_LENGTH","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"DEFAULT_ADMIN_ROLE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"GATEKEEPER","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"TIMELOCK","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"accrueBuybackReward","inputs":[{"type":"address","name":"account","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"availableBalanceOf","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"availableBalanceOfCooldown","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"balances","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IBDSystem"}],"name":"bdSystem","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"chargeShare","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"charges","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint32","name":"","internalType":"uint32"}],"name":"cooldownStartTimestamp","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"distributeAllMnt","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"distributeBorrowerMnt","inputs":[{"type":"address","name":"mToken","internalType":"contract IMToken"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"distributeMnt","inputs":[{"type":"address[]","name":"accounts","internalType":"address[]"},{"type":"address[]","name":"mTokens","internalType":"contract IMToken[]"},{"type":"bool","name":"borrowers","internalType":"bool"},{"type":"bool","name":"suppliers","internalType":"bool"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"distributeSupplierMnt","inputs":[{"type":"address","name":"mToken","internalType":"contract IMToken"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IEmissionBooster"}],"name":"emissionBooster","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"getAvailableCharges","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint32","name":"","internalType":"uint32"}],"name":"getCooldownEndTimestamp","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IInterconnector"}],"name":"getInterconnector","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"getRoleAdmin","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"grant","inputs":[{"type":"address","name":"recipient","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"grantRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"hasRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IIncentiveEmissionHub"}],"name":"incentiveEmissionHub","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initMarket","inputs":[{"type":"address","name":"mToken","internalType":"contract IMToken"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initialize","inputs":[{"type":"address","name":"admin_","internalType":"address"},{"type":"address","name":"mnt_","internalType":"contract IMntMirror"},{"type":"address","name":"emissionBooster_","internalType":"contract IEmissionBooster"},{"type":"address","name":"bdSystem_","internalType":"contract IBDSystem"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isCooldownActive","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isCooldownConfigured","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isCooldownFinished","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isOperationPaused","inputs":[{"type":"bytes32","name":"op","internalType":"bytes32"},{"type":"address","name":"subject","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IMntMirror"}],"name":"mnt","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"mntBorrowEmissionRate","inputs":[{"type":"address","name":"","internalType":"contract IMToken"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint224","name":"index","internalType":"uint224"},{"type":"uint32","name":"block","internalType":"uint32"}],"name":"mntBorrowState","inputs":[{"type":"address","name":"","internalType":"contract IMToken"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint224","name":"index","internalType":"uint224"},{"type":"uint32","name":"block","internalType":"uint32"}],"name":"mntBorrowerState","inputs":[{"type":"address","name":"","internalType":"contract IMToken"},{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint224","name":"index","internalType":"uint224"},{"type":"uint32","name":"block","internalType":"uint32"}],"name":"mntSupplierState","inputs":[{"type":"address","name":"","internalType":"contract IMToken"},{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"mntSupplyEmissionRate","inputs":[{"type":"address","name":"","internalType":"contract IMToken"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint224","name":"index","internalType":"uint224"},{"type":"uint32","name":"block","internalType":"uint32"}],"name":"mntSupplyState","inputs":[{"type":"address","name":"","internalType":"contract IMToken"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"numberOfCharges","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"pauseOperation","inputs":[{"type":"bytes32","name":"op","internalType":"bytes32"},{"type":"address","name":"subject","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"renounceRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"revokeRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setChargeShare","inputs":[{"type":"uint256","name":"newChargeShare","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setCooldownStartTimestamp","inputs":[{"type":"uint32","name":"startTimestamp","internalType":"uint32"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setIncentiveEmissionHub","inputs":[{"type":"address","name":"newIncentiveEmissionHub","internalType":"contract IIncentiveEmissionHub"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setMntEmissionRates","inputs":[{"type":"address","name":"mToken","internalType":"contract IMToken"},{"type":"uint256","name":"newMntSupplyEmissionRate","internalType":"uint256"},{"type":"uint256","name":"newMntBorrowEmissionRate","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setNumberOfCharges","inputs":[{"type":"uint256","name":"newNumberOfCharges","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"supportsInterface","inputs":[{"type":"bytes4","name":"interfaceId","internalType":"bytes4"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"switchLinkageRoot","inputs":[{"type":"address","name":"newRoot","internalType":"contract ILinkageRoot"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalBalanceOf","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"unpauseOperation","inputs":[{"type":"bytes32","name":"op","internalType":"bytes32"},{"type":"address","name":"subject","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint224","name":"","internalType":"uint224"},{"type":"uint224","name":"","internalType":"uint224"}],"name":"updateAndGetMntIndexes","inputs":[{"type":"address","name":"market","internalType":"contract IMToken"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"withdraw","inputs":[{"type":"uint256","name":"amount","internalType":"uint256"}]}]
Contract Creation Code
0x608060405234801561001057600080fd5b50600180556140c0806100246000396000f3fe608060405234801561001057600080fd5b50600436106103275760003560e01c80636370920e116101b8578063b5c68d9311610104578063d8a87f0b116100a2578063efc91bc91161007c578063efc91bc9146107e9578063f5417e45146107fc578063f8c8765e14610823578063fcd1af011461083657600080fd5b8063d8a87f0b146107a3578063ed761e00146107b6578063ee09dbee146107d657600080fd5b8063bf57d789116100de578063bf57d78914610727578063d291535c1461073a578063d547741f1461077d578063d57604991461079057600080fd5b8063b5c68d93146106fa578063b5cef4d41461070a578063bb3cb1161461071d57600080fd5b80639d68098f11610171578063a5397b7e1161014b578063a5397b7e1461065e578063a9f2373614610671578063abf074c4146106a4578063b02ebb23146106e757600080fd5b80639d68098f1461063a578063a217fddf14610643578063a433f84b1461064b57600080fd5b80636370920e146105635780636ab0faae146105765780637aadef8b146105d2578063804e5ab5146105e757806391d14854146105ef57806392db72391461060257600080fd5b806327e235e3116102775780633d25f199116102305780634b0ee02a1161020a5780634b0ee02a1461044c57806350c735071461053557806352703d6d146105485780635f276e8d1461055057600080fd5b80633d25f199146104fc5780633daecbb21461050f578063426be26d1461052257600080fd5b806327e235e3146104885780632e1a7d4d146104a85780632f2ff15d146104bb57806334a55611146104ce57806336568abe146104e15780633afcad14146104f457600080fd5b8063188f4deb116102e457806321c5e321116102be57806321c5e3211461040c578063248a9ca31461042957806325d998bb1461044c57806325dc7ff61461047557600080fd5b8063188f4deb146103e85780631c4c7843146103f15780631d1e61f0146103f957600080fd5b806301ffc9a71461032c57806308652973146103545780630993224b1461038257806311a259071461039757806314569daf146103c25780631646d214146103d5575b600080fd5b61033f61033a366004613993565b610856565b60405190151581526020015b60405180910390f35b6103746103623660046139d2565b60096020526000908152604090205481565b60405190815260200161034b565b6103956103903660046139ef565b61088d565b005b6005546103aa906001600160a01b031681565b6040516001600160a01b03909116815260200161034b565b6103956103d03660046139d2565b610911565b6103956103e3366004613a1f565b61099e565b61037460105481565b61033f610a6b565b610395610407366004613aa5565b610aae565b610414610c51565b60405163ffffffff909116815260200161034b565b610374610437366004613b3a565b60009081526002602052604090206001015490565b61037461045a3660046139d2565b6001600160a01b031660009081526007602052604090205490565b6103956104833660046139d2565b610c7f565b6103746104963660046139d2565b60076020526000908152604090205481565b6103956104b6366004613b3a565b610db3565b6103956104c93660046139ef565b610f57565b6103956104dc3660046139d2565b610f7c565b6103956104ef3660046139ef565b6110f7565b6103aa611171565b61037461050a3660046139d2565b6111a4565b61039561051d366004613b65565b6111f3565b600e546103aa906001600160a01b031681565b6103956105433660046139d2565b6112ea565b61033f611343565b61039561055e366004613b3a565b61136e565b610395610571366004613a1f565b6113fc565b6105ae6105843660046139d2565b600a602052600090815260409020546001600160e01b03811690600160e01b900463ffffffff1682565b604080516001600160e01b03909316835263ffffffff90911660208301520161034b565b61037460008051602061406b83398151915281565b61033f611554565b61033f6105fd3660046139ef565b611588565b6105ae6106103660046139d2565b600b602052600090815260409020546001600160e01b03811690600160e01b900463ffffffff1682565b610374600f5481565b610374600081565b61033f6106593660046139ef565b6115b3565b6006546103aa906001600160a01b031681565b61068461067f3660046139d2565b6115db565b604080516001600160e01b0393841681529290911660208301520161034b565b6105ae6106b2366004613b82565b600d6020908152600092835260408084209091529082529020546001600160e01b03811690600160e01b900463ffffffff1682565b6103956106f5366004613b3a565b6116e0565b6011546104149063ffffffff1681565b610395610718366004613b82565b611781565b61037462278d0081565b610395610735366004613bb0565b611864565b6105ae610748366004613b82565b600c6020908152600092835260408084209091529082529020546001600160e01b03811690600160e01b900463ffffffff1682565b61039561078b3660046139ef565b611a73565b61039561079e3660046139ef565b611a98565b6103746107b13660046139d2565b611b18565b6103746107c43660046139d2565b60086020526000908152604090205481565b6103956107e4366004613b82565b611b91565b6004546103aa906001600160a01b031681565b6103747f20162831d2f54c3e11eebafebfeda495d4c52c67b1708251179ec91fb76dd3b281565b610395610831366004613be5565b611ceb565b6103746108443660046139d2565b60126020526000908152604090205481565b60006001600160e01b03198216637965db0b60e01b148061088757506301ffc9a760e01b6001600160e01b03198316145b92915050565b61089681611e77565b6108a082826115b3565b6108a957600080fd5b6001600160a01b0381166000818152600360209081526040808320868452825291829020805460ff191690558151858152908101929092527fc0ce6ab7bb5f129a4695bdd24772a8a8247cefa36ebc156cad0994244c94dd4691015b60405180910390a15050565b610919611ebd565b61099281610925611f16565b6001600160a01b031663b0772d0b6040518163ffffffff1660e01b8152600401600060405180830381865afa158015610962573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261098a9190810190613c62565b600180611f81565b61099b60018055565b50565b6109a6612236565b6001600160a01b0316336001600160a01b031614604051806040016040528060048152602001632298981960e11b815250906109fe5760405162461bcd60e51b81526004016109f59190613d4b565b60405180910390fd5b506001600160a01b03821660009081526007602052604081208054839290610a27908490613d94565b9091555050604080516001600160a01b0384168152602081018390527f4b2e5f98f1e53b5e6fb32f5cd7740bd9dc3b85c37e5a19591b083132386411729101610905565b6000610a7561227d565b60115463ffffffff918216911611801590610aa95750610a93610c51565b63ffffffff16610aa161227d565b63ffffffff16105b905090565b610ab6611ebd565b6000610ac0611f16565b905060005b84811015610bb957816001600160a01b0316633d98a1e5878784818110610aee57610aee613da7565b9050602002016020810190610b0391906139d2565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602401602060405180830381865afa158015610b47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b6b9190613dbd565b60405180604001604052806004815260200163114c8c0d60e21b81525090610ba65760405162461bcd60e51b81526004016109f59190613d4b565b5080610bb181613dda565b915050610ac5565b5060005b86811015610c3e57610c2c888883818110610bda57610bda613da7565b9050602002016020810190610bef91906139d2565b878780806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250899250889150611f819050565b80610c3681613dda565b915050610bbd565b5050610c4960018055565b505050505050565b6000610c6c600f5462278d00610c679190613df3565b612284565b601154610aa9919063ffffffff16613e0a565b6040805180820190915260048152634533323960e01b60208201526001600160a01b038216610cc15760405162461bcd60e51b81526004016109f59190613d4b565b507fc34f336ef21a27e6cdbefdb1e201a57e5e6cb9d267e34fc3134d22f9decc8bbf80546001600160a01b039081169083168103610cfe57505050565b6001600160a01b0381161580610d1c57506001600160a01b03811633145b604051806040016040528060048152602001632298981960e11b81525090610d575760405162461bcd60e51b81526004016109f59190613d4b565b5081546001600160a01b0319166001600160a01b0384811691821784556040805192835290831660208301527f0a3a2d206ef02a769e7aaad7c9fb6d95dc9033159cd6ae7aaae65223fc321716910160405180910390a1505050565b67576974686472617760c01b610dca8160006115b3565b15604051806040016040528060048152602001634531303360e01b81525090610e065760405162461bcd60e51b81526004016109f59190613d4b565b50610e0f610a6b565b15610e2157610e1d336122ed565b5050565b3360009081526007602052604090205460018301610e3d578092505b6040805180820190915260048152634532333160e01b602082015281841115610e795760405162461bcd60e51b81526004016109f59190613d4b565b50610e848382613e27565b336000818152600760209081526040918290209390935580519182529181018590527f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364910160405180910390a1600454610ee8906001600160a01b03163385612448565b8215610f5257610ef6612236565b604051631af3bd6f60e31b81523360048201526001600160a01b03919091169063d79deb7890602401600060405180830381600087803b158015610f3957600080fd5b505af1158015610f4d573d6000803e3d6000fd5b505050505b505050565b600082815260026020526040902060010154610f728161249a565b610f5283836124a4565b610f84611f16565b6001600160a01b0316336001600160a01b031614604051806040016040528060048152602001632298981960e11b81525090610fd35760405162461bcd60e51b81526004016109f59190613d4b565b506001600160a01b0381166000908152600a60205260409020546001600160e01b031615801561102257506001600160a01b0381166000908152600b60205260409020546001600160e01b0316155b604051806040016040528060048152602001634534303360e01b8152509061105d5760405162461bcd60e51b81526004016109f59190613d4b565b50600061106861252a565b6040805180820182526a0c097ce7bc90715b34b9f160241b80825263ffffffff93841660208084018281526001600160a01b039098166000818152600a8352868120955199518816600160e01b9081026001600160e01b039b8c161790965586518088018852948552848301938452908152600b90915293909320905192519093160293169290921790915550565b6001600160a01b03811633146111675760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016109f5565b610e1d82826125b4565b6000610aa97fc34f336ef21a27e6cdbefdb1e201a57e5e6cb9d267e34fc3134d22f9decc8bbf546001600160a01b031690565b60006111ae610a6b565b6111ba57506000919050565b60006111c583611b18565b6001600160a01b0384166000908152600760205260409020549091506111ec90829061261b565b9392505050565b60008051602061406b83398151915261120b8161249a565b601154604080518082019091526004815263229a199b60e11b60208201529063ffffffff161561124e5760405162461bcd60e51b81526004016109f59190613d4b565b5061125761227d565b63ffffffff168263ffffffff161015604051806040016040528060048152602001634534333760e01b815250906112a15760405162461bcd60e51b81526004016109f59190613d4b565b506011805463ffffffff191663ffffffff84169081179091556040519081527f19370d6da74e619ec1197ec271047a0ec7007934190453ba506da8c79606f3e890602001610905565b60006112f58161249a565b600e80546001600160a01b0319166001600160a01b0384169081179091556040519081527fb87fe49f17bac2911ac2e2d820f97e91f0b20e39fe6f147d2e7c01b6c9de06b890602001610905565b600080600f5411801561135857506000601054115b8015610aa957505060115463ffffffff16151590565b60008051602061406b8339815191526113868161249a565b600f548211604051806040016040528060048152602001634534333960e01b815250906113c65760405162461bcd60e51b81526004016109f59190613d4b565b50600f8290556040518281527fe954ac3b1cf93cdb233d81606975d71ee5760ee91ef5f9119524cdfc1f0bd5ec90602001610905565b60006114078161249a565b6040805180820190915260048152634532333160e01b6020820152826114405760405162461bcd60e51b81526004016109f59190613d4b565b50600480546040516370a0823160e01b815230928101929092526000916001600160a01b03909116906370a0823190602401602060405180830381865afa15801561148f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114b39190613e3a565b905082811015604051806040016040528060048152602001632299981b60e11b815250906114f45760405162461bcd60e51b81526004016109f59190613d4b565b50604080516001600160a01b0386168152602081018590527fc0a044d864362b2fd8fe093346df0c0f1d224408ed9649da3f3e8f82ded0edf5910160405180910390a160045461154e906001600160a01b03168585612448565b50505050565b600061155e611343565b8015610aa9575061156d610c51565b63ffffffff1661157b61227d565b63ffffffff161015905090565b60009182526002602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6001600160a01b03166000908152600360209081526040808320938352929052205460ff1690565b60008060006115e984612692565b6001600160a01b0385166000818152600a6020908152604080832085518387015163ffffffff16600160e01b026001600160e01b03909116179055805163aa5af0fd60e01b81529051949550919361168c939263aa5af0fd9260048083019391928290030181865afa158015611663573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116879190613e3a565b6127c5565b9050600061169a868361282e565b6001600160a01b039096166000908152600b602090815260409091208751919097015163ffffffff16600160e01b026001600160e01b0382161790965550505193915050565b60008051602061406b8339815191526116f88161249a565b6000821180156117105750670de0b6b3a76400008211155b604051806040016040528060048152602001630453434360e41b8152509061174b5760405162461bcd60e51b81526004016109f59190613d4b565b5060108290556040518281527fffb6527714188301c85bfd9d63747580aca9f4871b10e613611ba7138ee3d84d90602001610905565b61178a82612985565b600061179582612b27565b6040516370a0823160e01b81526001600160a01b0384811660048301529192506000918516906370a0823190602401602060405180830381865afa1580156117e1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118059190613e3a565b6001600160a01b038086166000908152600a6020908152604080832054600c83528184209489168452939091529020919250611852918491879185916001600160e01b0316906001612b9b565b61154e82600001518360200151612e2d565b60008051602061406b83398151915261187c8161249a565b611884611f16565b604051633d98a1e560e01b81526001600160a01b0386811660048301529190911690633d98a1e590602401602060405180830381865afa1580156118cc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118f09190613dbd565b60405180604001604052806004815260200163114c8c0d60e21b8152509061192b5760405162461bcd60e51b81526004016109f59190613d4b565b506001600160a01b03841660009081526008602052604090205483146119a95761195484612985565b6001600160a01b038416600081815260086020908152604091829020869055815192835282018590527ff929aab734285ec10b2439f24d57ce096e5c09f5b8dc69f9c3d7ab1e46440863910160405180910390a15b6001600160a01b038416600090815260096020526040902054821461154e576000611a0b856001600160a01b031663aa5af0fd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611663573d6000803e3d6000fd5b9050611a178582613000565b6001600160a01b038516600081815260096020908152604091829020869055815192835282018590527fcd8642d7b68e8199d42d54190cebd93b2b282d5ee9e4a1b2eae44163b60cbf1791015b60405180910390a15050505050565b600082815260026020526040902060010154611a8e8161249a565b610f5283836125b4565b611aa1816131df565b611aab82826115b3565b15611ab557600080fd5b6001600160a01b0381166000818152600360209081526040808320868452825291829020805460ff191660011790558151858152908101929092527f073c51ddd8218684c2d74687bd6b4fd16aea280702c4cfb4744fe8a2a916a4539101610905565b6000611b22610a6b565b611b2e57506000919050565b60115460009063ffffffff16611b4261227d565b611b4c9190613e53565b63ffffffff1690506000611b6362278d0083613e70565b6001600160a01b038516600090815260126020526040902054909150611b899082613e27565b949350505050565b6000611bd4836001600160a01b031663aa5af0fd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611663573d6000803e3d6000fd5b9050611be08382613000565b6000611beb83612b27565b6040516395dd919360e01b81526001600160a01b0385811660048301529192506000916001600160e01b03851691670de0b6b3a7640000918816906395dd919390602401602060405180830381865afa158015611c4c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c709190613e3a565b611c7a9190613df3565b611c849190613e70565b6001600160a01b038087166000908152600b6020908152604080832054600d8352818420948a168452939091528120929350611cd2928592899286926001600160e01b039092169190612b9b565b611ce482600001518360200151612e2d565b5050505050565b600054610100900460ff1615808015611d0b5750600054600160ff909116105b80611d255750303b158015611d25575060005460ff166001145b611d885760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016109f5565b6000805460ff191660011790558015611dab576000805461ff0019166101001790555b611db66000866124a4565b611de07f20162831d2f54c3e11eebafebfeda495d4c52c67b1708251179ec91fb76dd3b2866124a4565b611df860008051602061406b833981519152866124a4565b600480546001600160a01b038087166001600160a01b0319928316179092556005805486841690831617905560068054928516929091169190911790558015611ce4576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb384740249890602001611a64565b611e82600033611588565b604051806040016040528060048152602001632298981960e11b81525090610e1d5760405162461bcd60e51b81526004016109f59190613d4b565b600260015403611f0f5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016109f5565b6002600155565b6000611f20611171565b6001600160a01b03166356e4b68b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f5d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aa99190613e92565b6000611f8c85612b27565b905060005b8451811015612223576000858281518110611fae57611fae613da7565b60200260200101519050841561213d576040516395dd919360e01b81526001600160a01b038881166004830152600091908316906395dd919390602401602060405180830381865afa158015612008573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061202c9190613e3a565b9050801561213b576000612077836001600160a01b031663aa5af0fd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611663573d6000803e3d6000fd5b90506120838382613000565b61213985846001600160e01b0384166120a4670de0b6b3a764000087613df3565b6120ae9190613e70565b600b6000886001600160a01b03166001600160a01b0316815260200190815260200160002060000160009054906101000a90046001600160e01b0316600d6000896001600160a01b03166001600160a01b0316815260200190815260200160002060008f6001600160a01b03166001600160a01b031681526020019081526020016000206000612b9b565b505b505b8315612210576040516370a0823160e01b81526001600160a01b038881166004830152600091908316906370a0823190602401602060405180830381865afa15801561218d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121b19190613e3a565b9050801561220e576121c282612985565b6001600160a01b038083166000908152600a6020908152604080832054600c8352818420948d16845293909152902061220e918691859185916001600160e01b03909116906001612b9b565b505b508061221b81613dda565b915050611f91565b50611ce481600001518260200151612e2d565b6000612240611171565b6001600160a01b031663f8ec69116040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f5d573d6000803e3d6000fd5b6000610aa9425b600063ffffffff8211156122e95760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203360448201526532206269747360d01b60648201526084016109f5565b5090565b6001600160a01b0381166000908152600760205260408120549061231083611b18565b9050600061231e828461261b565b6001600160a01b03851660009081526007602052604081208054929350839290919061234b908490613e27565b90915550506001600160a01b03841660009081526012602052604081208054849290612378908490613d94565b9091555050604080516001600160a01b0386168152602081018390527f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364910160405180910390a16004546123d6906001600160a01b03168583612448565b801561154e576123e4612236565b604051631af3bd6f60e31b81526001600160a01b038681166004830152919091169063d79deb78906024015b600060405180830381600087803b15801561242a57600080fd5b505af115801561243e573d6000803e3d6000fd5b5050505050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610f52908490613209565b61099b81336132de565b6124ae8282611588565b610e1d5760008281526002602090815260408083206001600160a01b03851684529091529020805460ff191660011790556124e63390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6000610aa97316700000000000000000000000000000000100016001600160a01b03166333d5ac9b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612581573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125a59190613eaf565b67ffffffffffffffff16612284565b6125be8282611588565b15610e1d5760008281526002602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b60008260000361262d57506000610887565b6010546000805b85811015612689576000670de0b6b3a76400006126518588613df3565b61265b9190613e70565b90506126678187613e27565b95506126738184613d94565b925050808061268190613dda565b915050612634565b50949350505050565b604080518082018252600080825260209182018190526001600160a01b0384168152600a82528290208251808401845290546001600160e01b038116808352600160e01b90910463ffffffff168284015283518085019094526004845263114c8c0d60e21b9284019290925291906a0c097ce7bc90715b34b9f160241b111561272e5760405162461bcd60e51b81526004016109f59190613d4b565b506127c08160086000856001600160a01b03166001600160a01b0316815260200190815260200160002054846001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612797573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127bb9190613e3a565b613337565b919050565b60006001600160e01b038211156122e95760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20326044820152663234206269747360c81b60648201526084016109f5565b604080518082018252600080825260209182018190526001600160a01b0385168152600b82528290208251808401845290546001600160e01b038116808352600160e01b90910463ffffffff168284015283518085019094526004845263114c8c0d60e21b9284019290925291906a0c097ce7bc90715b34b9f160241b11156128ca5760405162461bcd60e51b81526004016109f59190613d4b565b506000826001600160e01b0316670de0b6b3a7640000856001600160a01b03166347bd37186040518163ffffffff1660e01b8152600401602060405180830381865afa15801561291e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129429190613e3a565b61294c9190613df3565b6129569190613e70565b6001600160a01b03851660009081526009602052604090205490915061297e90839083613337565b5092915050565b6001600160a01b0381166000908152600a6020526040902054600160e01b900463ffffffff166129b361252a565b63ffffffff168163ffffffff16036129c9575050565b600560009054906101000a90046001600160a01b03166001600160a01b031663899acddf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a409190613dbd565b15612adb576001600160a01b0382166000908152600a60205260408120546001600160e01b031690612a7184612692565b6001600160a01b038086166000908152600a602090815260409182902084519185015163ffffffff16600160e01b026001600160e01b038316179055600554915163656fdaf360e01b815293945091169163656fdaf3916124109188918891889190600401613ed9565b612ae482612692565b6001600160a01b0383166000908152600a602090815260409091208251929091015163ffffffff16600160e01b026001600160e01b039092169190911790555050565b612b2f61391f565b6e26b73a2234b9ba3934b13aba34b7b760891b612b4d8160006115b3565b15604051806040016040528060048152602001634531303360e01b81525090612b895760405162461bcd60e51b81526004016109f59190613d4b565b50612b93836133e7565b825250919050565b6000612ba561252a565b83549091506001600160e01b03811690600160e01b900463ffffffff1681158015612be757506a0c097ce7bc90715b34b9f160241b6001600160e01b03871610155b15612c0057506a0c097ce7bc90715b34b9f160241b9050815b63ffffffff8316600160e01b026001600160e01b03808816918217875583169003612c2d57505050610c49565b6000612c398388613f11565b8a51602001516001600160e01b039190911691506001600160a01b031615612c9057895160600151670de0b6b3a764000090612c759083613df3565b612c7f9190613e70565b612c899082613d94565b9050612d40565b6005548a515160405163243e2cb560e21b81526001600160a01b038c8116600483015291821660248201526001600160e01b03808716604483015263ffffffff861660648301528a16608482015287151560a48201529116906390f8b2d49060c401602060405180830381865afa158015612d0f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d339190613e3a565b612d3d9082613d94565b90505b60006a0c097ce7bc90715b34b9f160241b612d5b838b613df3565b612d659190613e70565b9050808b60000151608001818151612d7d9190613d94565b91508181525050612d948a82888e602001516134dd565b8515612ddf578a51516040517f53165211eb309c92d4fedb907931978ef63a16e6b53f0fc5ab2b30bae8c82b1991612dd2918d919085908d90613f31565b60405180910390a1612e20565b8a51516040517ffe2416fcae87f2fcf0d5f947d4573f3cdeba0e9ad1638b22b341c3c64c58388091612e17918d919085908d90613f31565b60405180910390a15b5050505050505050505050565b8160800151600003612e3d575050565b608082015182516001600160a01b031660009081526007602052604081208054909190612e6b908490613d94565b909155505081516080830151604080516001600160a01b03909316835260208301919091527fd73d70a3c59aea6d9a85940fbe0f4cf07e6dcdbdb61dcdb552d2468f9ef9635b910160405180910390a160208201516001600160a01b031615612f90576000670de0b6b3a764000083604001518460800151612eed9190613df3565b612ef79190613e70565b9050806007600085602001516001600160a01b03166001600160a01b031681526020019081526020016000206000828254612f329190613d94565b90915550506020838101518451604080516001600160a01b03938416815292909116928201929092529081018290527f68ba76d0d38f1d7b74cb8c7020ef5f22d452ebb28a0d8c7706d10442a1b2ccbb9060600160405180910390a1505b81518151612f9e9190613591565b612fa6612236565b8251604051630c88b02b60e11b81526001600160a01b0391821660048201529116906319116056906024015b600060405180830381600087803b158015612fec57600080fd5b505af1158015610c49573d6000803e3d6000fd5b6001600160a01b0382166000908152600b6020526040902054600160e01b900463ffffffff1661302e61252a565b63ffffffff168163ffffffff160361304557505050565b600560009054906101000a90046001600160a01b03166001600160a01b031663899acddf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613098573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130bc9190613dbd565b15613191576001600160a01b0383166000908152600b60205260408120546001600160e01b0316906130ee858561282e565b6001600160a01b038087166000908152600b602090815260409182902084519185015163ffffffff16600160e01b026001600160e01b03831617905560055491516359e2a9f560e01b81529394509116916359e2a9f5916131589189918891889190600401613ed9565b600060405180830381600087803b15801561317257600080fd5b505af1158015613186573d6000803e3d6000fd5b505050505050505050565b61319b838361282e565b6001600160a01b0384166000908152600b602090815260409091208251929091015163ffffffff16600160e01b026001600160e01b03909216919091179055505050565b611e827f20162831d2f54c3e11eebafebfeda495d4c52c67b1708251179ec91fb76dd3b233611588565b600061325e826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166135e99092919063ffffffff16565b905080516000148061327f57508080602001905181019061327f9190613dbd565b610f525760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016109f5565b6132e88282611588565b610e1d576132f5816135f8565b61330083602061360a565b604051602001613311929190613f62565b60408051601f198184030181529082905262461bcd60e51b82526109f591600401613d4b565b600061334161252a565b63ffffffff16905082156133d4576000846020015163ffffffff16826133679190613e27565b905060006133758583613df3565b905060008085116133875760006133aa565b846133a06a0c097ce7bc90715b34b9f160241b84613df3565b6133aa9190613e70565b90506133b5816127c5565b875188906133c4908390613fd7565b6001600160e01b03169052505050505b63ffffffff166020909301929092525050565b6133ef613952565b6e26b73a2234b9ba3934b13aba34b7b760891b61340d8160006115b3565b15604051806040016040528060048152602001634531303360e01b815250906134495760405162461bcd60e51b81526004016109f59190613d4b565b506001600160a01b03838116808452600654604051631e7aaa9f60e11b8152600481019290925290911690633cf5553e90602401608060405180830381865afa15801561349a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134be9190613ff7565b6001600160a01b03166020860152506040840152606083015250919050565b600e546001600160a01b0316158015906134f75750600083115b1561154e57600e54604051630ad4c12360e41b81526001600160a01b0386811660048301526024820186905284151560448301529091169063ad4c123090606401602060405180830381865afa158015613555573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135799190613e3a565b81518290613588908390613d94565b90525050505050565b600e546001600160a01b0316158015906135ab5750600081115b15610e1d57600e5460405163a3b882fd60e01b81526001600160a01b038481166004830152602482018490529091169063a3b882fd90604401612fd2565b6060611b8984846000856137a6565b60606108876001600160a01b03831660145b60606000613619836002613df3565b613624906002613d94565b67ffffffffffffffff81111561363c5761363c613c41565b6040519080825280601f01601f191660200182016040528015613666576020820181803683370190505b509050600360fc1b8160008151811061368157613681613da7565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106136b0576136b0613da7565b60200101906001600160f81b031916908160001a90535060006136d4846002613df3565b6136df906001613d94565b90505b6001811115613757576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061371357613713613da7565b1a60f81b82828151811061372957613729613da7565b60200101906001600160f81b031916908160001a90535060049490941c9361375081614037565b90506136e2565b5083156111ec5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016109f5565b6060824710156138075760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016109f5565b600080866001600160a01b03168587604051613823919061404e565b60006040518083038185875af1925050503d8060008114613860576040519150601f19603f3d011682016040523d82523d6000602084013e613865565b606091505b509150915061387687838387613881565b979650505050505050565b606083156138f05782516000036138e9576001600160a01b0385163b6138e95760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016109f5565b5081611b89565b611b8983838151156139055781518083602001fd5b8060405162461bcd60e51b81526004016109f59190613d4b565b6040518060400160405280613932613952565b815260200161394d6040518060200160405280600081525090565b905290565b6040518060a0016040528060006001600160a01b0316815260200160006001600160a01b031681526020016000815260200160008152602001600081525090565b6000602082840312156139a557600080fd5b81356001600160e01b0319811681146111ec57600080fd5b6001600160a01b038116811461099b57600080fd5b6000602082840312156139e457600080fd5b81356111ec816139bd565b60008060408385031215613a0257600080fd5b823591506020830135613a14816139bd565b809150509250929050565b60008060408385031215613a3257600080fd5b8235613a3d816139bd565b946020939093013593505050565b60008083601f840112613a5d57600080fd5b50813567ffffffffffffffff811115613a7557600080fd5b6020830191508360208260051b8501011115613a9057600080fd5b9250929050565b801515811461099b57600080fd5b60008060008060008060808789031215613abe57600080fd5b863567ffffffffffffffff80821115613ad657600080fd5b613ae28a838b01613a4b565b90985096506020890135915080821115613afb57600080fd5b50613b0889828a01613a4b565b9095509350506040870135613b1c81613a97565b91506060870135613b2c81613a97565b809150509295509295509295565b600060208284031215613b4c57600080fd5b5035919050565b63ffffffff8116811461099b57600080fd5b600060208284031215613b7757600080fd5b81356111ec81613b53565b60008060408385031215613b9557600080fd5b8235613ba0816139bd565b91506020830135613a14816139bd565b600080600060608486031215613bc557600080fd5b8335613bd0816139bd565b95602085013595506040909401359392505050565b60008060008060808587031215613bfb57600080fd5b8435613c06816139bd565b93506020850135613c16816139bd565b92506040850135613c26816139bd565b91506060850135613c36816139bd565b939692955090935050565b634e487b7160e01b600052604160045260246000fd5b80516127c0816139bd565b60006020808385031215613c7557600080fd5b825167ffffffffffffffff80821115613c8d57600080fd5b818501915085601f830112613ca157600080fd5b815181811115613cb357613cb3613c41565b8060051b604051601f19603f83011681018181108582111715613cd857613cd8613c41565b604052918252848201925083810185019188831115613cf657600080fd5b938501935b82851015613d1b57613d0c85613c57565b84529385019392850192613cfb565b98975050505050505050565b60005b83811015613d42578181015183820152602001613d2a565b50506000910152565b6020815260008251806020840152613d6a816040850160208701613d27565b601f01601f19169190910160400192915050565b634e487b7160e01b600052601160045260246000fd5b8082018082111561088757610887613d7e565b634e487b7160e01b600052603260045260246000fd5b600060208284031215613dcf57600080fd5b81516111ec81613a97565b600060018201613dec57613dec613d7e565b5060010190565b808202811582820484141761088757610887613d7e565b63ffffffff81811683821601908082111561297e5761297e613d7e565b8181038181111561088757610887613d7e565b600060208284031215613e4c57600080fd5b5051919050565b63ffffffff82811682821603908082111561297e5761297e613d7e565b600082613e8d57634e487b7160e01b600052601260045260246000fd5b500490565b600060208284031215613ea457600080fd5b81516111ec816139bd565b600060208284031215613ec157600080fd5b815167ffffffffffffffff811681146111ec57600080fd5b6001600160a01b0394909416845263ffffffff9290921660208401526001600160e01b03908116604084015216606082015260800190565b6001600160e01b0382811682821603908082111561297e5761297e613d7e565b6001600160a01b03948516815292909316602083015260408201526001600160e01b03909116606082015260800190565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351613f9a816017850160208801613d27565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351613fcb816028840160208801613d27565b01602801949350505050565b6001600160e01b0381811683821601908082111561297e5761297e613d7e565b6000806000806080858703121561400d57600080fd5b8451935060208501519250604085015161402681613b53565b6060860151909250613c36816139bd565b60008161404657614046613d7e565b506000190190565b60008251614060818460208701613d27565b919091019291505056feaefebe170cbaff0af052a32795af0e1b8afff9850f946ad2869be14f35534371a26469706673582212206f6b79d44f371bb6d0c2dd3e83cd9773cc049c1ff4c8a8c937a4ae406e2c82cf64736f6c63430008110033
Deployed ByteCode
0x608060405234801561001057600080fd5b50600436106103275760003560e01c80636370920e116101b8578063b5c68d9311610104578063d8a87f0b116100a2578063efc91bc91161007c578063efc91bc9146107e9578063f5417e45146107fc578063f8c8765e14610823578063fcd1af011461083657600080fd5b8063d8a87f0b146107a3578063ed761e00146107b6578063ee09dbee146107d657600080fd5b8063bf57d789116100de578063bf57d78914610727578063d291535c1461073a578063d547741f1461077d578063d57604991461079057600080fd5b8063b5c68d93146106fa578063b5cef4d41461070a578063bb3cb1161461071d57600080fd5b80639d68098f11610171578063a5397b7e1161014b578063a5397b7e1461065e578063a9f2373614610671578063abf074c4146106a4578063b02ebb23146106e757600080fd5b80639d68098f1461063a578063a217fddf14610643578063a433f84b1461064b57600080fd5b80636370920e146105635780636ab0faae146105765780637aadef8b146105d2578063804e5ab5146105e757806391d14854146105ef57806392db72391461060257600080fd5b806327e235e3116102775780633d25f199116102305780634b0ee02a1161020a5780634b0ee02a1461044c57806350c735071461053557806352703d6d146105485780635f276e8d1461055057600080fd5b80633d25f199146104fc5780633daecbb21461050f578063426be26d1461052257600080fd5b806327e235e3146104885780632e1a7d4d146104a85780632f2ff15d146104bb57806334a55611146104ce57806336568abe146104e15780633afcad14146104f457600080fd5b8063188f4deb116102e457806321c5e321116102be57806321c5e3211461040c578063248a9ca31461042957806325d998bb1461044c57806325dc7ff61461047557600080fd5b8063188f4deb146103e85780631c4c7843146103f15780631d1e61f0146103f957600080fd5b806301ffc9a71461032c57806308652973146103545780630993224b1461038257806311a259071461039757806314569daf146103c25780631646d214146103d5575b600080fd5b61033f61033a366004613993565b610856565b60405190151581526020015b60405180910390f35b6103746103623660046139d2565b60096020526000908152604090205481565b60405190815260200161034b565b6103956103903660046139ef565b61088d565b005b6005546103aa906001600160a01b031681565b6040516001600160a01b03909116815260200161034b565b6103956103d03660046139d2565b610911565b6103956103e3366004613a1f565b61099e565b61037460105481565b61033f610a6b565b610395610407366004613aa5565b610aae565b610414610c51565b60405163ffffffff909116815260200161034b565b610374610437366004613b3a565b60009081526002602052604090206001015490565b61037461045a3660046139d2565b6001600160a01b031660009081526007602052604090205490565b6103956104833660046139d2565b610c7f565b6103746104963660046139d2565b60076020526000908152604090205481565b6103956104b6366004613b3a565b610db3565b6103956104c93660046139ef565b610f57565b6103956104dc3660046139d2565b610f7c565b6103956104ef3660046139ef565b6110f7565b6103aa611171565b61037461050a3660046139d2565b6111a4565b61039561051d366004613b65565b6111f3565b600e546103aa906001600160a01b031681565b6103956105433660046139d2565b6112ea565b61033f611343565b61039561055e366004613b3a565b61136e565b610395610571366004613a1f565b6113fc565b6105ae6105843660046139d2565b600a602052600090815260409020546001600160e01b03811690600160e01b900463ffffffff1682565b604080516001600160e01b03909316835263ffffffff90911660208301520161034b565b61037460008051602061406b83398151915281565b61033f611554565b61033f6105fd3660046139ef565b611588565b6105ae6106103660046139d2565b600b602052600090815260409020546001600160e01b03811690600160e01b900463ffffffff1682565b610374600f5481565b610374600081565b61033f6106593660046139ef565b6115b3565b6006546103aa906001600160a01b031681565b61068461067f3660046139d2565b6115db565b604080516001600160e01b0393841681529290911660208301520161034b565b6105ae6106b2366004613b82565b600d6020908152600092835260408084209091529082529020546001600160e01b03811690600160e01b900463ffffffff1682565b6103956106f5366004613b3a565b6116e0565b6011546104149063ffffffff1681565b610395610718366004613b82565b611781565b61037462278d0081565b610395610735366004613bb0565b611864565b6105ae610748366004613b82565b600c6020908152600092835260408084209091529082529020546001600160e01b03811690600160e01b900463ffffffff1682565b61039561078b3660046139ef565b611a73565b61039561079e3660046139ef565b611a98565b6103746107b13660046139d2565b611b18565b6103746107c43660046139d2565b60086020526000908152604090205481565b6103956107e4366004613b82565b611b91565b6004546103aa906001600160a01b031681565b6103747f20162831d2f54c3e11eebafebfeda495d4c52c67b1708251179ec91fb76dd3b281565b610395610831366004613be5565b611ceb565b6103746108443660046139d2565b60126020526000908152604090205481565b60006001600160e01b03198216637965db0b60e01b148061088757506301ffc9a760e01b6001600160e01b03198316145b92915050565b61089681611e77565b6108a082826115b3565b6108a957600080fd5b6001600160a01b0381166000818152600360209081526040808320868452825291829020805460ff191690558151858152908101929092527fc0ce6ab7bb5f129a4695bdd24772a8a8247cefa36ebc156cad0994244c94dd4691015b60405180910390a15050565b610919611ebd565b61099281610925611f16565b6001600160a01b031663b0772d0b6040518163ffffffff1660e01b8152600401600060405180830381865afa158015610962573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261098a9190810190613c62565b600180611f81565b61099b60018055565b50565b6109a6612236565b6001600160a01b0316336001600160a01b031614604051806040016040528060048152602001632298981960e11b815250906109fe5760405162461bcd60e51b81526004016109f59190613d4b565b60405180910390fd5b506001600160a01b03821660009081526007602052604081208054839290610a27908490613d94565b9091555050604080516001600160a01b0384168152602081018390527f4b2e5f98f1e53b5e6fb32f5cd7740bd9dc3b85c37e5a19591b083132386411729101610905565b6000610a7561227d565b60115463ffffffff918216911611801590610aa95750610a93610c51565b63ffffffff16610aa161227d565b63ffffffff16105b905090565b610ab6611ebd565b6000610ac0611f16565b905060005b84811015610bb957816001600160a01b0316633d98a1e5878784818110610aee57610aee613da7565b9050602002016020810190610b0391906139d2565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602401602060405180830381865afa158015610b47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b6b9190613dbd565b60405180604001604052806004815260200163114c8c0d60e21b81525090610ba65760405162461bcd60e51b81526004016109f59190613d4b565b5080610bb181613dda565b915050610ac5565b5060005b86811015610c3e57610c2c888883818110610bda57610bda613da7565b9050602002016020810190610bef91906139d2565b878780806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250899250889150611f819050565b80610c3681613dda565b915050610bbd565b5050610c4960018055565b505050505050565b6000610c6c600f5462278d00610c679190613df3565b612284565b601154610aa9919063ffffffff16613e0a565b6040805180820190915260048152634533323960e01b60208201526001600160a01b038216610cc15760405162461bcd60e51b81526004016109f59190613d4b565b507fc34f336ef21a27e6cdbefdb1e201a57e5e6cb9d267e34fc3134d22f9decc8bbf80546001600160a01b039081169083168103610cfe57505050565b6001600160a01b0381161580610d1c57506001600160a01b03811633145b604051806040016040528060048152602001632298981960e11b81525090610d575760405162461bcd60e51b81526004016109f59190613d4b565b5081546001600160a01b0319166001600160a01b0384811691821784556040805192835290831660208301527f0a3a2d206ef02a769e7aaad7c9fb6d95dc9033159cd6ae7aaae65223fc321716910160405180910390a1505050565b67576974686472617760c01b610dca8160006115b3565b15604051806040016040528060048152602001634531303360e01b81525090610e065760405162461bcd60e51b81526004016109f59190613d4b565b50610e0f610a6b565b15610e2157610e1d336122ed565b5050565b3360009081526007602052604090205460018301610e3d578092505b6040805180820190915260048152634532333160e01b602082015281841115610e795760405162461bcd60e51b81526004016109f59190613d4b565b50610e848382613e27565b336000818152600760209081526040918290209390935580519182529181018590527f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364910160405180910390a1600454610ee8906001600160a01b03163385612448565b8215610f5257610ef6612236565b604051631af3bd6f60e31b81523360048201526001600160a01b03919091169063d79deb7890602401600060405180830381600087803b158015610f3957600080fd5b505af1158015610f4d573d6000803e3d6000fd5b505050505b505050565b600082815260026020526040902060010154610f728161249a565b610f5283836124a4565b610f84611f16565b6001600160a01b0316336001600160a01b031614604051806040016040528060048152602001632298981960e11b81525090610fd35760405162461bcd60e51b81526004016109f59190613d4b565b506001600160a01b0381166000908152600a60205260409020546001600160e01b031615801561102257506001600160a01b0381166000908152600b60205260409020546001600160e01b0316155b604051806040016040528060048152602001634534303360e01b8152509061105d5760405162461bcd60e51b81526004016109f59190613d4b565b50600061106861252a565b6040805180820182526a0c097ce7bc90715b34b9f160241b80825263ffffffff93841660208084018281526001600160a01b039098166000818152600a8352868120955199518816600160e01b9081026001600160e01b039b8c161790965586518088018852948552848301938452908152600b90915293909320905192519093160293169290921790915550565b6001600160a01b03811633146111675760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016109f5565b610e1d82826125b4565b6000610aa97fc34f336ef21a27e6cdbefdb1e201a57e5e6cb9d267e34fc3134d22f9decc8bbf546001600160a01b031690565b60006111ae610a6b565b6111ba57506000919050565b60006111c583611b18565b6001600160a01b0384166000908152600760205260409020549091506111ec90829061261b565b9392505050565b60008051602061406b83398151915261120b8161249a565b601154604080518082019091526004815263229a199b60e11b60208201529063ffffffff161561124e5760405162461bcd60e51b81526004016109f59190613d4b565b5061125761227d565b63ffffffff168263ffffffff161015604051806040016040528060048152602001634534333760e01b815250906112a15760405162461bcd60e51b81526004016109f59190613d4b565b506011805463ffffffff191663ffffffff84169081179091556040519081527f19370d6da74e619ec1197ec271047a0ec7007934190453ba506da8c79606f3e890602001610905565b60006112f58161249a565b600e80546001600160a01b0319166001600160a01b0384169081179091556040519081527fb87fe49f17bac2911ac2e2d820f97e91f0b20e39fe6f147d2e7c01b6c9de06b890602001610905565b600080600f5411801561135857506000601054115b8015610aa957505060115463ffffffff16151590565b60008051602061406b8339815191526113868161249a565b600f548211604051806040016040528060048152602001634534333960e01b815250906113c65760405162461bcd60e51b81526004016109f59190613d4b565b50600f8290556040518281527fe954ac3b1cf93cdb233d81606975d71ee5760ee91ef5f9119524cdfc1f0bd5ec90602001610905565b60006114078161249a565b6040805180820190915260048152634532333160e01b6020820152826114405760405162461bcd60e51b81526004016109f59190613d4b565b50600480546040516370a0823160e01b815230928101929092526000916001600160a01b03909116906370a0823190602401602060405180830381865afa15801561148f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114b39190613e3a565b905082811015604051806040016040528060048152602001632299981b60e11b815250906114f45760405162461bcd60e51b81526004016109f59190613d4b565b50604080516001600160a01b0386168152602081018590527fc0a044d864362b2fd8fe093346df0c0f1d224408ed9649da3f3e8f82ded0edf5910160405180910390a160045461154e906001600160a01b03168585612448565b50505050565b600061155e611343565b8015610aa9575061156d610c51565b63ffffffff1661157b61227d565b63ffffffff161015905090565b60009182526002602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6001600160a01b03166000908152600360209081526040808320938352929052205460ff1690565b60008060006115e984612692565b6001600160a01b0385166000818152600a6020908152604080832085518387015163ffffffff16600160e01b026001600160e01b03909116179055805163aa5af0fd60e01b81529051949550919361168c939263aa5af0fd9260048083019391928290030181865afa158015611663573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116879190613e3a565b6127c5565b9050600061169a868361282e565b6001600160a01b039096166000908152600b602090815260409091208751919097015163ffffffff16600160e01b026001600160e01b0382161790965550505193915050565b60008051602061406b8339815191526116f88161249a565b6000821180156117105750670de0b6b3a76400008211155b604051806040016040528060048152602001630453434360e41b8152509061174b5760405162461bcd60e51b81526004016109f59190613d4b565b5060108290556040518281527fffb6527714188301c85bfd9d63747580aca9f4871b10e613611ba7138ee3d84d90602001610905565b61178a82612985565b600061179582612b27565b6040516370a0823160e01b81526001600160a01b0384811660048301529192506000918516906370a0823190602401602060405180830381865afa1580156117e1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118059190613e3a565b6001600160a01b038086166000908152600a6020908152604080832054600c83528184209489168452939091529020919250611852918491879185916001600160e01b0316906001612b9b565b61154e82600001518360200151612e2d565b60008051602061406b83398151915261187c8161249a565b611884611f16565b604051633d98a1e560e01b81526001600160a01b0386811660048301529190911690633d98a1e590602401602060405180830381865afa1580156118cc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118f09190613dbd565b60405180604001604052806004815260200163114c8c0d60e21b8152509061192b5760405162461bcd60e51b81526004016109f59190613d4b565b506001600160a01b03841660009081526008602052604090205483146119a95761195484612985565b6001600160a01b038416600081815260086020908152604091829020869055815192835282018590527ff929aab734285ec10b2439f24d57ce096e5c09f5b8dc69f9c3d7ab1e46440863910160405180910390a15b6001600160a01b038416600090815260096020526040902054821461154e576000611a0b856001600160a01b031663aa5af0fd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611663573d6000803e3d6000fd5b9050611a178582613000565b6001600160a01b038516600081815260096020908152604091829020869055815192835282018590527fcd8642d7b68e8199d42d54190cebd93b2b282d5ee9e4a1b2eae44163b60cbf1791015b60405180910390a15050505050565b600082815260026020526040902060010154611a8e8161249a565b610f5283836125b4565b611aa1816131df565b611aab82826115b3565b15611ab557600080fd5b6001600160a01b0381166000818152600360209081526040808320868452825291829020805460ff191660011790558151858152908101929092527f073c51ddd8218684c2d74687bd6b4fd16aea280702c4cfb4744fe8a2a916a4539101610905565b6000611b22610a6b565b611b2e57506000919050565b60115460009063ffffffff16611b4261227d565b611b4c9190613e53565b63ffffffff1690506000611b6362278d0083613e70565b6001600160a01b038516600090815260126020526040902054909150611b899082613e27565b949350505050565b6000611bd4836001600160a01b031663aa5af0fd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611663573d6000803e3d6000fd5b9050611be08382613000565b6000611beb83612b27565b6040516395dd919360e01b81526001600160a01b0385811660048301529192506000916001600160e01b03851691670de0b6b3a7640000918816906395dd919390602401602060405180830381865afa158015611c4c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c709190613e3a565b611c7a9190613df3565b611c849190613e70565b6001600160a01b038087166000908152600b6020908152604080832054600d8352818420948a168452939091528120929350611cd2928592899286926001600160e01b039092169190612b9b565b611ce482600001518360200151612e2d565b5050505050565b600054610100900460ff1615808015611d0b5750600054600160ff909116105b80611d255750303b158015611d25575060005460ff166001145b611d885760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016109f5565b6000805460ff191660011790558015611dab576000805461ff0019166101001790555b611db66000866124a4565b611de07f20162831d2f54c3e11eebafebfeda495d4c52c67b1708251179ec91fb76dd3b2866124a4565b611df860008051602061406b833981519152866124a4565b600480546001600160a01b038087166001600160a01b0319928316179092556005805486841690831617905560068054928516929091169190911790558015611ce4576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb384740249890602001611a64565b611e82600033611588565b604051806040016040528060048152602001632298981960e11b81525090610e1d5760405162461bcd60e51b81526004016109f59190613d4b565b600260015403611f0f5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016109f5565b6002600155565b6000611f20611171565b6001600160a01b03166356e4b68b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f5d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aa99190613e92565b6000611f8c85612b27565b905060005b8451811015612223576000858281518110611fae57611fae613da7565b60200260200101519050841561213d576040516395dd919360e01b81526001600160a01b038881166004830152600091908316906395dd919390602401602060405180830381865afa158015612008573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061202c9190613e3a565b9050801561213b576000612077836001600160a01b031663aa5af0fd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611663573d6000803e3d6000fd5b90506120838382613000565b61213985846001600160e01b0384166120a4670de0b6b3a764000087613df3565b6120ae9190613e70565b600b6000886001600160a01b03166001600160a01b0316815260200190815260200160002060000160009054906101000a90046001600160e01b0316600d6000896001600160a01b03166001600160a01b0316815260200190815260200160002060008f6001600160a01b03166001600160a01b031681526020019081526020016000206000612b9b565b505b505b8315612210576040516370a0823160e01b81526001600160a01b038881166004830152600091908316906370a0823190602401602060405180830381865afa15801561218d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121b19190613e3a565b9050801561220e576121c282612985565b6001600160a01b038083166000908152600a6020908152604080832054600c8352818420948d16845293909152902061220e918691859185916001600160e01b03909116906001612b9b565b505b508061221b81613dda565b915050611f91565b50611ce481600001518260200151612e2d565b6000612240611171565b6001600160a01b031663f8ec69116040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f5d573d6000803e3d6000fd5b6000610aa9425b600063ffffffff8211156122e95760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203360448201526532206269747360d01b60648201526084016109f5565b5090565b6001600160a01b0381166000908152600760205260408120549061231083611b18565b9050600061231e828461261b565b6001600160a01b03851660009081526007602052604081208054929350839290919061234b908490613e27565b90915550506001600160a01b03841660009081526012602052604081208054849290612378908490613d94565b9091555050604080516001600160a01b0386168152602081018390527f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364910160405180910390a16004546123d6906001600160a01b03168583612448565b801561154e576123e4612236565b604051631af3bd6f60e31b81526001600160a01b038681166004830152919091169063d79deb78906024015b600060405180830381600087803b15801561242a57600080fd5b505af115801561243e573d6000803e3d6000fd5b5050505050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610f52908490613209565b61099b81336132de565b6124ae8282611588565b610e1d5760008281526002602090815260408083206001600160a01b03851684529091529020805460ff191660011790556124e63390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6000610aa97316700000000000000000000000000000000100016001600160a01b03166333d5ac9b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612581573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125a59190613eaf565b67ffffffffffffffff16612284565b6125be8282611588565b15610e1d5760008281526002602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b60008260000361262d57506000610887565b6010546000805b85811015612689576000670de0b6b3a76400006126518588613df3565b61265b9190613e70565b90506126678187613e27565b95506126738184613d94565b925050808061268190613dda565b915050612634565b50949350505050565b604080518082018252600080825260209182018190526001600160a01b0384168152600a82528290208251808401845290546001600160e01b038116808352600160e01b90910463ffffffff168284015283518085019094526004845263114c8c0d60e21b9284019290925291906a0c097ce7bc90715b34b9f160241b111561272e5760405162461bcd60e51b81526004016109f59190613d4b565b506127c08160086000856001600160a01b03166001600160a01b0316815260200190815260200160002054846001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612797573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127bb9190613e3a565b613337565b919050565b60006001600160e01b038211156122e95760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20326044820152663234206269747360c81b60648201526084016109f5565b604080518082018252600080825260209182018190526001600160a01b0385168152600b82528290208251808401845290546001600160e01b038116808352600160e01b90910463ffffffff168284015283518085019094526004845263114c8c0d60e21b9284019290925291906a0c097ce7bc90715b34b9f160241b11156128ca5760405162461bcd60e51b81526004016109f59190613d4b565b506000826001600160e01b0316670de0b6b3a7640000856001600160a01b03166347bd37186040518163ffffffff1660e01b8152600401602060405180830381865afa15801561291e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129429190613e3a565b61294c9190613df3565b6129569190613e70565b6001600160a01b03851660009081526009602052604090205490915061297e90839083613337565b5092915050565b6001600160a01b0381166000908152600a6020526040902054600160e01b900463ffffffff166129b361252a565b63ffffffff168163ffffffff16036129c9575050565b600560009054906101000a90046001600160a01b03166001600160a01b031663899acddf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a409190613dbd565b15612adb576001600160a01b0382166000908152600a60205260408120546001600160e01b031690612a7184612692565b6001600160a01b038086166000908152600a602090815260409182902084519185015163ffffffff16600160e01b026001600160e01b038316179055600554915163656fdaf360e01b815293945091169163656fdaf3916124109188918891889190600401613ed9565b612ae482612692565b6001600160a01b0383166000908152600a602090815260409091208251929091015163ffffffff16600160e01b026001600160e01b039092169190911790555050565b612b2f61391f565b6e26b73a2234b9ba3934b13aba34b7b760891b612b4d8160006115b3565b15604051806040016040528060048152602001634531303360e01b81525090612b895760405162461bcd60e51b81526004016109f59190613d4b565b50612b93836133e7565b825250919050565b6000612ba561252a565b83549091506001600160e01b03811690600160e01b900463ffffffff1681158015612be757506a0c097ce7bc90715b34b9f160241b6001600160e01b03871610155b15612c0057506a0c097ce7bc90715b34b9f160241b9050815b63ffffffff8316600160e01b026001600160e01b03808816918217875583169003612c2d57505050610c49565b6000612c398388613f11565b8a51602001516001600160e01b039190911691506001600160a01b031615612c9057895160600151670de0b6b3a764000090612c759083613df3565b612c7f9190613e70565b612c899082613d94565b9050612d40565b6005548a515160405163243e2cb560e21b81526001600160a01b038c8116600483015291821660248201526001600160e01b03808716604483015263ffffffff861660648301528a16608482015287151560a48201529116906390f8b2d49060c401602060405180830381865afa158015612d0f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d339190613e3a565b612d3d9082613d94565b90505b60006a0c097ce7bc90715b34b9f160241b612d5b838b613df3565b612d659190613e70565b9050808b60000151608001818151612d7d9190613d94565b91508181525050612d948a82888e602001516134dd565b8515612ddf578a51516040517f53165211eb309c92d4fedb907931978ef63a16e6b53f0fc5ab2b30bae8c82b1991612dd2918d919085908d90613f31565b60405180910390a1612e20565b8a51516040517ffe2416fcae87f2fcf0d5f947d4573f3cdeba0e9ad1638b22b341c3c64c58388091612e17918d919085908d90613f31565b60405180910390a15b5050505050505050505050565b8160800151600003612e3d575050565b608082015182516001600160a01b031660009081526007602052604081208054909190612e6b908490613d94565b909155505081516080830151604080516001600160a01b03909316835260208301919091527fd73d70a3c59aea6d9a85940fbe0f4cf07e6dcdbdb61dcdb552d2468f9ef9635b910160405180910390a160208201516001600160a01b031615612f90576000670de0b6b3a764000083604001518460800151612eed9190613df3565b612ef79190613e70565b9050806007600085602001516001600160a01b03166001600160a01b031681526020019081526020016000206000828254612f329190613d94565b90915550506020838101518451604080516001600160a01b03938416815292909116928201929092529081018290527f68ba76d0d38f1d7b74cb8c7020ef5f22d452ebb28a0d8c7706d10442a1b2ccbb9060600160405180910390a1505b81518151612f9e9190613591565b612fa6612236565b8251604051630c88b02b60e11b81526001600160a01b0391821660048201529116906319116056906024015b600060405180830381600087803b158015612fec57600080fd5b505af1158015610c49573d6000803e3d6000fd5b6001600160a01b0382166000908152600b6020526040902054600160e01b900463ffffffff1661302e61252a565b63ffffffff168163ffffffff160361304557505050565b600560009054906101000a90046001600160a01b03166001600160a01b031663899acddf6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613098573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130bc9190613dbd565b15613191576001600160a01b0383166000908152600b60205260408120546001600160e01b0316906130ee858561282e565b6001600160a01b038087166000908152600b602090815260409182902084519185015163ffffffff16600160e01b026001600160e01b03831617905560055491516359e2a9f560e01b81529394509116916359e2a9f5916131589189918891889190600401613ed9565b600060405180830381600087803b15801561317257600080fd5b505af1158015613186573d6000803e3d6000fd5b505050505050505050565b61319b838361282e565b6001600160a01b0384166000908152600b602090815260409091208251929091015163ffffffff16600160e01b026001600160e01b03909216919091179055505050565b611e827f20162831d2f54c3e11eebafebfeda495d4c52c67b1708251179ec91fb76dd3b233611588565b600061325e826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166135e99092919063ffffffff16565b905080516000148061327f57508080602001905181019061327f9190613dbd565b610f525760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016109f5565b6132e88282611588565b610e1d576132f5816135f8565b61330083602061360a565b604051602001613311929190613f62565b60408051601f198184030181529082905262461bcd60e51b82526109f591600401613d4b565b600061334161252a565b63ffffffff16905082156133d4576000846020015163ffffffff16826133679190613e27565b905060006133758583613df3565b905060008085116133875760006133aa565b846133a06a0c097ce7bc90715b34b9f160241b84613df3565b6133aa9190613e70565b90506133b5816127c5565b875188906133c4908390613fd7565b6001600160e01b03169052505050505b63ffffffff166020909301929092525050565b6133ef613952565b6e26b73a2234b9ba3934b13aba34b7b760891b61340d8160006115b3565b15604051806040016040528060048152602001634531303360e01b815250906134495760405162461bcd60e51b81526004016109f59190613d4b565b506001600160a01b03838116808452600654604051631e7aaa9f60e11b8152600481019290925290911690633cf5553e90602401608060405180830381865afa15801561349a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134be9190613ff7565b6001600160a01b03166020860152506040840152606083015250919050565b600e546001600160a01b0316158015906134f75750600083115b1561154e57600e54604051630ad4c12360e41b81526001600160a01b0386811660048301526024820186905284151560448301529091169063ad4c123090606401602060405180830381865afa158015613555573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135799190613e3a565b81518290613588908390613d94565b90525050505050565b600e546001600160a01b0316158015906135ab5750600081115b15610e1d57600e5460405163a3b882fd60e01b81526001600160a01b038481166004830152602482018490529091169063a3b882fd90604401612fd2565b6060611b8984846000856137a6565b60606108876001600160a01b03831660145b60606000613619836002613df3565b613624906002613d94565b67ffffffffffffffff81111561363c5761363c613c41565b6040519080825280601f01601f191660200182016040528015613666576020820181803683370190505b509050600360fc1b8160008151811061368157613681613da7565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106136b0576136b0613da7565b60200101906001600160f81b031916908160001a90535060006136d4846002613df3565b6136df906001613d94565b90505b6001811115613757576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061371357613713613da7565b1a60f81b82828151811061372957613729613da7565b60200101906001600160f81b031916908160001a90535060049490941c9361375081614037565b90506136e2565b5083156111ec5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016109f5565b6060824710156138075760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016109f5565b600080866001600160a01b03168587604051613823919061404e565b60006040518083038185875af1925050503d8060008114613860576040519150601f19603f3d011682016040523d82523d6000602084013e613865565b606091505b509150915061387687838387613881565b979650505050505050565b606083156138f05782516000036138e9576001600160a01b0385163b6138e95760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016109f5565b5081611b89565b611b8983838151156139055781518083602001fd5b8060405162461bcd60e51b81526004016109f59190613d4b565b6040518060400160405280613932613952565b815260200161394d6040518060200160405280600081525090565b905290565b6040518060a0016040528060006001600160a01b0316815260200160006001600160a01b031681526020016000815260200160008152602001600081525090565b6000602082840312156139a557600080fd5b81356001600160e01b0319811681146111ec57600080fd5b6001600160a01b038116811461099b57600080fd5b6000602082840312156139e457600080fd5b81356111ec816139bd565b60008060408385031215613a0257600080fd5b823591506020830135613a14816139bd565b809150509250929050565b60008060408385031215613a3257600080fd5b8235613a3d816139bd565b946020939093013593505050565b60008083601f840112613a5d57600080fd5b50813567ffffffffffffffff811115613a7557600080fd5b6020830191508360208260051b8501011115613a9057600080fd5b9250929050565b801515811461099b57600080fd5b60008060008060008060808789031215613abe57600080fd5b863567ffffffffffffffff80821115613ad657600080fd5b613ae28a838b01613a4b565b90985096506020890135915080821115613afb57600080fd5b50613b0889828a01613a4b565b9095509350506040870135613b1c81613a97565b91506060870135613b2c81613a97565b809150509295509295509295565b600060208284031215613b4c57600080fd5b5035919050565b63ffffffff8116811461099b57600080fd5b600060208284031215613b7757600080fd5b81356111ec81613b53565b60008060408385031215613b9557600080fd5b8235613ba0816139bd565b91506020830135613a14816139bd565b600080600060608486031215613bc557600080fd5b8335613bd0816139bd565b95602085013595506040909401359392505050565b60008060008060808587031215613bfb57600080fd5b8435613c06816139bd565b93506020850135613c16816139bd565b92506040850135613c26816139bd565b91506060850135613c36816139bd565b939692955090935050565b634e487b7160e01b600052604160045260246000fd5b80516127c0816139bd565b60006020808385031215613c7557600080fd5b825167ffffffffffffffff80821115613c8d57600080fd5b818501915085601f830112613ca157600080fd5b815181811115613cb357613cb3613c41565b8060051b604051601f19603f83011681018181108582111715613cd857613cd8613c41565b604052918252848201925083810185019188831115613cf657600080fd5b938501935b82851015613d1b57613d0c85613c57565b84529385019392850192613cfb565b98975050505050505050565b60005b83811015613d42578181015183820152602001613d2a565b50506000910152565b6020815260008251806020840152613d6a816040850160208701613d27565b601f01601f19169190910160400192915050565b634e487b7160e01b600052601160045260246000fd5b8082018082111561088757610887613d7e565b634e487b7160e01b600052603260045260246000fd5b600060208284031215613dcf57600080fd5b81516111ec81613a97565b600060018201613dec57613dec613d7e565b5060010190565b808202811582820484141761088757610887613d7e565b63ffffffff81811683821601908082111561297e5761297e613d7e565b8181038181111561088757610887613d7e565b600060208284031215613e4c57600080fd5b5051919050565b63ffffffff82811682821603908082111561297e5761297e613d7e565b600082613e8d57634e487b7160e01b600052601260045260246000fd5b500490565b600060208284031215613ea457600080fd5b81516111ec816139bd565b600060208284031215613ec157600080fd5b815167ffffffffffffffff811681146111ec57600080fd5b6001600160a01b0394909416845263ffffffff9290921660208401526001600160e01b03908116604084015216606082015260800190565b6001600160e01b0382811682821603908082111561297e5761297e613d7e565b6001600160a01b03948516815292909316602083015260408201526001600160e01b03909116606082015260800190565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351613f9a816017850160208801613d27565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351613fcb816028840160208801613d27565b01602801949350505050565b6001600160e01b0381811683821601908082111561297e5761297e613d7e565b6000806000806080858703121561400d57600080fd5b8451935060208501519250604085015161402681613b53565b6060860151909250613c36816139bd565b60008161404657614046613d7e565b506000190190565b60008251614060818460208701613d27565b919091019291505056feaefebe170cbaff0af052a32795af0e1b8afff9850f946ad2869be14f35534371a26469706673582212206f6b79d44f371bb6d0c2dd3e83cd9773cc049c1ff4c8a8c937a4ae406e2c82cf64736f6c63430008110033