Source Code
Overview
ETH Balance
0 ETH
Eth Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0xc171399D...7af943bb0 The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
StabilityPool_v1
Compiler Version
v0.8.30+commit.73712a01
Optimization Enabled:
Yes with 700 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Token} from "@bao/Token.sol";
import {TokenHolder} from "@bao/TokenHolder.sol";
import {DecrementalFloatingPoint} from "src/math/DecrementalFloatingPoint.sol";
import {MultipleRewardCompoundingAccumulator} from "src/reward/accumulator/MultipleRewardCompoundingAccumulator.sol";
import {IStabilityPool} from "src/interfaces/IStabilityPool.sol";
import {IMinter} from "src/interfaces/IMinter.sol";
// solhint-disable not-rely-on-time
// slither-disable-start timestamp
/// @title StabilityPool
/// @notice This contract hold asset minted as pegged tokens by the Minter contract.
/// Depositing pegged assets here results in:
/// * wrapped collateral being deposited here automatically from the minter when wrapped collateral's value increases
/// In the event of a rebalance, which occurs automatically, when the collateral ration held by the Minter contract
/// drops below a threshold. In that event some, ro even all, deposited assets are converted to wrapped collatersl
/// or to leveage tokens, depending on what the LIQUIDATION_TOKEN is.
///
/// This contract also mints an ERC20 that can:
/// * represent ownership of the assets deposited here in a wallet.
///
/// @author rootminus0x1 mostly copied from Aladdin's Fx framework
/// @dev Uses UUPS proxy, erc7201 storage
/// @custom:oz-upgrades
// solhint-disable-next-line contract-name-camelcase
contract StabilityPool_v1 is
Initializable,
UUPSUpgradeable,
MultipleRewardCompoundingAccumulator,
TokenHolder,
IStabilityPool
{
using SafeERC20 for IERC20;
using DecrementalFloatingPoint for uint128;
/*************
* Constants *
*************/
/// The role used for reward manager in super contracts
/// @dev we define it here in the most derived contract to avoid clashes
uint256 private constant _REWARD_MANAGER_ROLE = _ROLE_0;
uint256 public constant REBALANCER_ROLE = _ROLE_1;
uint256 private constant _REWARD_DEPOSITOR_ROLE = _ROLE_2;
/// @notice Role that exempts an account from early-withdrawal fees
uint256 public constant EXEMPT_WITHDRAWAL_FEE_ROLE = _ROLE_3;
uint256 private constant _MAX_EARLY_WITHDRAWAL_FEE = 1 ether;
// these variables are set in the constructor, not the initializer, to improve contract size and gas usage
// to change them the contract must be upgraded
/// @inheritdoc IStabilityPool
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address public immutable ASSET_TOKEN;
/// @inheritdoc IStabilityPool
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address public immutable LIQUIDATION_TOKEN;
/// @dev the pool cannot have less than this supply once it has reached that supply
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint256 public immutable MIN_TOTAL_ASSET_SUPPLY;
/// @dev the minimum deposit size, used to guarantee the MIN_TOTAL_ASSET_SUPPLY if non-zero
/// Although strictly it is only needed for the first deposit, it's a small amount and so not a big penalty for all
/// with the added protection of making multiple small deposit attack vectors harder
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint256 public immutable MIN_DEPOSIT; // = MIN_TOTAL_ASSET_SUPPLY;
/// @dev immutable withdrawal window configuration
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint64 public immutable WITHDRAWAL_START_DELAY;
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint64 public immutable WITHDRAWAL_END_WINDOW;
/***********
* Structs *
***********/
/// @dev The token balance struct. The compiler will pack this into single `uint256`.
///
/// @param product The encoding product data, see the comments of `DecrementalFloatingPoint`.
/// @param amount The amount of token currently.
/// @param updatedAt The timestamp in day when the struct is updated.
struct TokenBalance {
uint128 product; // TODO: this could be 124 bits
uint104 amount; // This has to store 1e36
uint40 updatedAt; // TODO: this could be days rather than seconds requiring fewer bits
}
/// @dev The withdrawal request window for an account
struct WithdrawalRequest {
uint64 start;
uint64 end;
}
/// @dev Packed fee payment configuration: fits in one 256-bit slot
/// @param feeAddress The address that receives early withdrawal fees (160 bits)
/// @param earlyWithdrawalFee The fee ratio scaled by 1e18 (uint96)
struct FeePayment {
address feeAddress;
uint96 earlyWithdrawalFee;
}
/*************
* Variables *
*************/
// Share-with-proxy Storage
// ------------------------
/// @custom:storage-location erc7201:bao.storage.StabilityPool
struct StabilityPoolStorage {
/// @dev The TokenBalance struct for current total supply.
TokenBalance totalAssetSupply;
/// @dev Mapping account address to TokenBalance struct. Accessed via assetBalanceOf
mapping(address => TokenBalance) assetBalances;
/// @notice Mapping from index to history totalSupply.
/// If there are multiple updates at the same timestamp, only the last one will be recorded.
mapping(uint256 => TokenBalance) totalAssetSupplyHistory;
uint256 totalAssetSupplyHistoryLength; // number of total supply history records
/// @notice The address of token wrapper for liquidated base token;
// address wrapper;
/// @notice Error trackers for the error correction in the loss calculation.
uint256 lastAssetLossError;
/// @notice Mapping from account to withdrawal request
mapping(address => WithdrawalRequest) withdrawalRequests;
/// @dev Packed fee configuration (address + uint96)
FeePayment feePayment;
}
// chisel eval 'keccak256(abi.encode(uint256(keccak256("bao.storage.StabilityPool")) - 1)) & ~bytes32(uint256(0xff))'
bytes32 private constant _STABILITYPOOL_STORAGE =
0xcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e400;
// internal as it is used in testing
function _getStabilityPoolStorage() internal pure returns (StabilityPoolStorage storage $) {
// solhint-disable-next-line no-inline-assembly
assembly {
$.slot := _STABILITYPOOL_STORAGE
}
}
/***************
* Constructor *
***************/
function initialize(address owner_, uint256 earlyWithdrawalFee_, address feeAddress_) external initializer {
_initializeOwner(owner_);
__UUPSUpgradeable_init();
__ReentrancyGuardTransient_init();
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
// initialize fee configuration on the proxy
if (earlyWithdrawalFee_ > _MAX_EARLY_WITHDRAWAL_FEE) {
revert InvalidFee(earlyWithdrawalFee_);
}
if (feeAddress_ == address(0)) {
revert InvalidFeeAddress(feeAddress_);
}
$.feePayment = FeePayment({feeAddress: feeAddress_, earlyWithdrawalFee: uint96(earlyWithdrawalFee_)});
TokenBalance memory initialSupply = TokenBalance({
product: DecrementalFloatingPoint.init(),
amount: 0,
updatedAt: uint40(block.timestamp - 1) // set to 1 second ago so this is sure to be the start of history
});
$.totalAssetSupply = initialSupply;
$.totalAssetSupplyHistory[0] = initialSupply;
$.totalAssetSupplyHistoryLength = 1;
}
/// @notice In UUPS proxies the constructor is used only to stop the implementation being initialized to any version
/// https://forum.openzeppelin.com/t/what-does-disableinitializers-function-mean/28730
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(
address minter_,
address liquidationToken_,
uint256 earlyWithdrawalFee_,
address feeAddress_,
uint256 withdrawalStartDelay_,
uint256 withdrawalEndWindow_,
uint256 minTotalAssetSupply
) MultipleRewardCompoundingAccumulator(_REWARD_MANAGER_ROLE, _REWARD_DEPOSITOR_ROLE, 1 weeks) {
_disableInitializers();
address asset = IMinter(minter_).PEGGED_TOKEN();
Token.sanityCheckERC20Token(asset);
// slither-disable-next-line missing-zero-check
ASSET_TOKEN = asset;
Token.sanityCheckERC20Token(liquidationToken_);
if (
liquidationToken_ != IMinter(minter_).WRAPPED_COLLATERAL_TOKEN() &&
liquidationToken_ != IMinter(minter_).LEVERAGED_TOKEN()
) {
revert InvalidLiquidationToken(liquidationToken_);
}
LIQUIDATION_TOKEN = liquidationToken_;
// early withdrawal settings validations (for implementation construct-only tests)
if (earlyWithdrawalFee_ > _MAX_EARLY_WITHDRAWAL_FEE) {
revert InvalidFee(earlyWithdrawalFee_);
}
if (feeAddress_ == address(0)) {
revert InvalidFeeAddress(feeAddress_);
}
if (withdrawalEndWindow_ == 0) {
revert InvalidWithdrawalWindow(withdrawalStartDelay_, withdrawalEndWindow_);
}
// set these two to the same thing, for public visibility
// their purpose is the same thing - preventing a complete emptying of a non-empty pool
MIN_TOTAL_ASSET_SUPPLY = minTotalAssetSupply;
MIN_DEPOSIT = minTotalAssetSupply;
// set immutable withdrawal window params
WITHDRAWAL_START_DELAY = uint64(withdrawalStartDelay_);
WITHDRAWAL_END_WINDOW = uint64(withdrawalEndWindow_);
}
/// @notice The check that allow this contract to be upgraded:
/// In UUPS proxies the implementation is responsible for upgrading itself and only owners can upgrade this contract.
function _authorizeUpgrade(address) internal override onlyOwner {} // solhint-disable-line no-empty-blocks
/*************************
* Public View Functions *
*************************/
/// @inheritdoc IStabilityPool
function totalAssetSupply() external view returns (uint256 totalSupply_) {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
totalSupply_ = $.totalAssetSupply.amount;
}
/// @inheritdoc IStabilityPool
// solhint-disable-next-line explicit-types
function totalAssetSupplyHistory(uint index) external view returns (uint40 atDay, uint256 amount) {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
TokenBalance memory record = $.totalAssetSupplyHistory[index];
atDay = record.updatedAt;
amount = record.amount;
}
/// @inheritdoc IStabilityPool
function assetBalanceOf(address account) external view returns (uint256 amount) {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
TokenBalance memory balance = $.assetBalances[account];
amount = _getCompoundedBalance(balance.amount, balance.product, $.totalAssetSupply.product);
}
/// @inheritdoc IStabilityPool
function lastAssetLossError() external view returns (uint256) {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
return $.lastAssetLossError;
}
// expose claimable from parent via interface
/// @inheritdoc IStabilityPool
/// @notice Returns the configured withdrawal request window for an account.
function getWithdrawalRequest(address account) external view returns (uint64 start, uint64 end) {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
WithdrawalRequest memory request = $.withdrawalRequests[account];
start = request.start;
end = request.end;
}
/// @inheritdoc IStabilityPool
/// @notice Returns the current early withdrawal fee ratio (scaled by 1e18).
function getEarlyWithdrawalFee() external view returns (uint256) {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
return uint256($.feePayment.earlyWithdrawalFee);
}
/// @inheritdoc IStabilityPool
/// @notice Returns the current fee recipient address for early withdrawal fees.
function getFeeAddress() external view returns (address) {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
return $.feePayment.feeAddress;
}
/// @inheritdoc IStabilityPool
/// @notice Returns the global withdrawal window configuration.
function getWithdrawalWindow() external view returns (uint64 startDelay, uint64 endWindow) {
startDelay = WITHDRAWAL_START_DELAY;
endWindow = WITHDRAWAL_END_WINDOW;
}
/****************************
* Public Mutator Functions *
****************************/
/// @inheritdoc IStabilityPool
// slither-disable-next-line reentrancy-benign,reentrancy-no-eth
function deposit(
uint256 assetAmount,
address receiver,
uint256 minAmount
) external nonReentrant returns (uint256 assetsDeposited) {
if (receiver == address(0)) {
revert InvalidReceiver(address(0));
}
address sender = _msgSender();
assetsDeposited = Token.allOf(sender, ASSET_TOKEN, assetAmount);
if (assetsDeposited < minAmount) {
revert DepositAmountLessThanMinimum(assetsDeposited, minAmount);
}
// although not strictly necessary: it is only needed for the first deposit
// we enforce this limit on all deposits because it is a small amount (1$)
if (assetsDeposited < MIN_TOTAL_ASSET_SUPPLY) {
revert DepositAmountLessThanMinimum(assetsDeposited, MIN_TOTAL_ASSET_SUPPLY);
}
// Required for ERC20 compatibility - we're actually minting ourselves
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
// If depositing before the end of a valid withdrawal window, cancel the request
WithdrawalRequest memory request = $.withdrawalRequests[sender];
if (request.start != 0 && request.end > request.start && block.timestamp <= request.end) {
$.withdrawalRequests[sender] = WithdrawalRequest({start: 0, end: 0});
emit WithdrawalRequestCancelled(sender);
}
// Emit deposit event for off-chain indexers and auditing
emit Deposit(sender, receiver, assetsDeposited);
// get the assets from the sender
IERC20(ASSET_TOKEN).safeTransferFrom(sender, address(this), assetsDeposited);
// send their representative to the gauge, if one
_checkpoint(receiver);
// do the deposit
// update the global record
// It should never exceed `type(uint104).max`.
TokenBalance memory supply = $.totalAssetSupply;
supply.amount += uint104(assetsDeposited);
supply.updatedAt = uint40(block.timestamp);
_recordTotalSupply(supply);
// update the user record
TokenBalance memory balance = $.assetBalances[receiver];
balance.amount += uint104(assetsDeposited);
$.assetBalances[receiver] = balance;
emit UserDepositChange(receiver, balance.amount, 0);
}
/// @inheritdoc IStabilityPool
// slither-disable-next-line reentrancy-no-eth,reentrancy-eth,reentrancy-unlimited-gas,reentrancy-benign
// slither-disable-next-line cyclomatic-complexity
function withdraw(
uint256 assetAmount,
address receiver,
uint256 minAmount
) external virtual nonReentrant returns (uint256 assetsWithdrawn) {
if (receiver == address(0)) {
revert InvalidReceiver(address(0));
}
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
address sender = _msgSender();
// slither-disable-next-line reentrancy-no-eth
_checkpoint(sender);
// Read any existing withdrawal request (optional)
WithdrawalRequest memory request = $.withdrawalRequests[sender];
TokenBalance memory balance = $.assetBalances[sender];
if (assetAmount == type(uint256).max) {
assetsWithdrawn = balance.amount;
} else if (assetAmount > balance.amount) {
revert WithdrawAmountExceedsBalance(assetAmount, balance.amount);
} else {
assetsWithdrawn = assetAmount;
}
if (assetsWithdrawn == 0) {
revert WithdrawZeroAmount();
}
if (assetsWithdrawn < minAmount) {
revert WithdrawAmountLessThanMinimum(assetsWithdrawn, minAmount);
}
// Determine fee policy
// - If no request: fee applies
// - If request exists: fee applies outside [start, end]; no fee during window
uint256 feeAmount = 0;
bool hasRequest = (request.start != 0 && request.end > request.start);
bool inWindow = hasRequest && block.timestamp >= request.start && block.timestamp <= request.end;
// Role-based fee exemption: addresses with EXEMPT_WITHDRAWAL_FEE_ROLE never pay early-withdrawal fees
bool isExempt = hasAnyRole(sender, EXEMPT_WITHDRAWAL_FEE_ROLE);
if (!inWindow && !isExempt) {
feeAmount = (assetsWithdrawn * uint256($.feePayment.earlyWithdrawalFee)) / 1 ether;
assetsWithdrawn -= feeAmount;
}
// floor the total supply at the minimum
TokenBalance memory supply = $.totalAssetSupply;
if (supply.amount - assetsWithdrawn < MIN_TOTAL_ASSET_SUPPLY) {
assetsWithdrawn = supply.amount - MIN_TOTAL_ASSET_SUPPLY;
// if fee pushed us below min, trim fee as well
if (supply.amount - assetsWithdrawn - feeAmount < MIN_TOTAL_ASSET_SUPPLY) {
uint256 maxFee = supply.amount - MIN_TOTAL_ASSET_SUPPLY - assetsWithdrawn;
if (feeAmount > maxFee) feeAmount = maxFee;
}
}
// Close any existing withdrawal request after successful withdrawal
if (hasRequest) {
$.withdrawalRequests[sender] = WithdrawalRequest({start: 0, end: 0});
emit WithdrawalRequestUpdated(sender, request.start, 0);
}
emit Withdraw(sender, receiver, assetsWithdrawn);
// update the global record
unchecked {
supply.amount -= uint104(assetsWithdrawn + feeAmount);
supply.updatedAt = uint40(block.timestamp);
}
_recordTotalSupply(supply);
// update the user record
unchecked {
balance.amount -= uint104(assetsWithdrawn + feeAmount);
}
$.assetBalances[sender] = balance;
emit UserDepositChange(sender, balance.amount, 0);
IERC20(ASSET_TOKEN).safeTransfer(receiver, assetsWithdrawn);
// Transfer fee if applicable
if (feeAmount > 0) {
IERC20(ASSET_TOKEN).safeTransfer($.feePayment.feeAddress, feeAmount);
emit EarlyWithdrawalFee(sender, feeAmount);
}
}
/// @inheritdoc IStabilityPool
/// @notice Creates or updates the withdrawal request window for msg.sender.
/// @dev Window is [start, end] where start = now + WITHDRAWAL_START_DELAY and end = start + WITHDRAWAL_END_WINDOW.
function requestWithdrawal() external nonReentrant {
address sender = _msgSender();
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
// Guard against unconfigured window in implementation (constructor ensures > 0)
if (WITHDRAWAL_END_WINDOW == 0) {
revert InvalidWithdrawalWindow(WITHDRAWAL_START_DELAY, WITHDRAWAL_END_WINDOW);
}
uint64 start = uint64(block.timestamp + WITHDRAWAL_START_DELAY);
uint64 end = uint64(start + WITHDRAWAL_END_WINDOW);
$.withdrawalRequests[sender] = WithdrawalRequest({start: start, end: end});
emit WithdrawalRequested(sender, start, end);
}
/**********************
* Internal Functions *
**********************/
/// @inheritdoc MultipleRewardCompoundingAccumulator
// slither-disable-next-line reentrancy-events,reentrancy-benign,reentrancy-no-eth // function is only called from nonReentrant external functions
function _checkpoint(address account) internal virtual override {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
super._checkpoint(account);
if (account != address(0)) {
TokenBalance memory supply = $.totalAssetSupply;
TokenBalance memory balance = $.assetBalances[account];
uint104 newBalance = uint104(_getCompoundedBalance(balance.amount, balance.product, supply.product));
if (newBalance != balance.amount) {
// no unchecked here, just in case
emit UserDepositChange(account, newBalance, balance.amount - newBalance);
}
balance = TokenBalance({amount: newBalance, product: supply.product, updatedAt: uint40(block.timestamp)});
$.assetBalances[account] = balance;
}
}
/// @inheritdoc MultipleRewardCompoundingAccumulator
function _getTotalPoolShare() internal view virtual override returns (uint128 currentProd, uint256 totalShare) {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
TokenBalance memory supply = $.totalAssetSupply;
currentProd = supply.product;
totalShare = supply.amount;
}
/// @inheritdoc MultipleRewardCompoundingAccumulator
function _getUserPoolShare(
address account
) internal view virtual override returns (uint128 previousProd, uint256 share) {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
TokenBalance memory balance = $.assetBalances[account];
previousProd = balance.product;
share = balance.amount;
}
/// @dev Internal function to reduce asset accounting.
/// @param loss The amount of asset lost.
function _notifyLoss(uint256 loss) internal {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
TokenBalance memory supply = $.totalAssetSupply;
if (supply.amount == 0) {
return;
}
// Enforce minimum balance to prevent complete depletion
if (loss >= supply.amount - MIN_TOTAL_ASSET_SUPPLY) {
// Loss would breach minimum - limit it
loss = supply.amount - MIN_TOTAL_ASSET_SUPPLY;
}
if (loss == 0) {
return; // No loss to apply
}
// calculate the loss per unit. which, due to integer division, has errors
uint256 assetLossPerUnitStaked;
// those errors are contained in an over-applied error which is essentially
// lossError ≈ supply.amount - (loss % supply.amount)
// this lossError (over application) is subtracted from any future call to this function
// the loss error does not affect the supply, only the user share of that and ensures that
// when it comes to making a claim, users get a fair allocation.
uint256 lossInEther = loss * 1 ether;
// calculate the new loss error (over applied)
// Handle case where loss is less than the over-application error
if (lossInEther <= $.lastAssetLossError) {
// Consume the error by the loss amount
$.lastAssetLossError -= lossInEther;
assetLossPerUnitStaked = 0; // No loss per unit staked, as the error absorbs the loss
} else {
// Calculate adjusted loss after accounting for error
uint256 lossNumerator = lossInEther - $.lastAssetLossError;
// Use ceiling division (n-1)/d + 1 to round up if there's any remainder
// this is an optimised version of ceilDiv in that we know the denominator is > zero (see code above)
// This ensures the pool is not disadvantaged and only favours the pool when necessary.
assetLossPerUnitStaked = (lossNumerator - 1) / uint256(supply.amount) + 1;
// Store the over-application as the new error
$.lastAssetLossError = (assetLossPerUnitStaked * uint256(supply.amount)) - lossNumerator;
}
// Reduce supply by loss amount
supply.amount -= uint104(loss);
// Update product factor and total supply
// The newProductFactor is the factor by which to change all deposits, due to the depletion of StabilityPool assets in the liquidation.
// As we don't allow pool emptying it is (1 - assetLossPerUnitStaked) which is always > 0 and < 1.
uint128 newProductFactor = 1 ether - uint128(assetLossPerUnitStaked);
supply.product = supply.product.mul(newProductFactor);
supply.updatedAt = uint40(block.timestamp);
_recordTotalSupply(supply);
}
/// @dev Internal function to record the historical total supply.
/// @param supply The new total supply to record.
function _recordTotalSupply(TokenBalance memory supply) private {
StabilityPoolStorage storage $ = _getStabilityPoolStorage();
uint256 totalSupplyHistoryLength_ = $.totalAssetSupplyHistoryLength;
// slither-disable-next-line incorrect-equality
if ($.totalAssetSupplyHistory[totalSupplyHistoryLength_ - 1].updatedAt == supply.updatedAt) {
$.totalAssetSupplyHistory[totalSupplyHistoryLength_ - 1] = supply;
} else {
$.totalAssetSupplyHistory[totalSupplyHistoryLength_] = supply;
$.totalAssetSupplyHistoryLength = totalSupplyHistoryLength_ + 1;
}
$.totalAssetSupply = supply;
}
// Rebalancing support
// -------------------------------------------------------
/// @notice function used to control access to the sweep function for extracting harvestable amounts
function _checkSweeper() internal view override(TokenHolder) {
_checkOwnerOrRoles(REBALANCER_ROLE);
}
/// @inheritdoc IStabilityPool
// slither-disable-next-line reentrancy-no-eth,reentrancy-benign should only ever called from nonReentrant functions
function notifyLiquidation(uint256 liquidated, uint256 returned) external onlyRoles(REBALANCER_ROLE) {
// Emit liquidation event to record loss and conversion details
emit Liquidated(ASSET_TOKEN, liquidated, LIQUIDATION_TOKEN, returned);
// recalculate balances and
// make sure rewards in-flight rewards are distributed on the pre-loss balances
_checkpoint(address(0));
// capture the reward, distributed immediately, at the prior-to-loss balances
_accumulateReward(LIQUIDATION_TOKEN, returned);
// update balances due to loss
_notifyLoss(liquidated);
}
}
// slither-disable-end timestamp// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @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 Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._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 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._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() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @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 {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @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(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (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(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, 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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @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.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
// TODO: check OZ address class
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/*
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
*/
// import {DateUtils} from "DateUtils/DateUtils.sol";
// Attribution: string basics stolen from OpenZeppelin
library Token {
/// @dev thrown when zero collateral is passed in or -1 is passed in and the balance is zero
error ZeroInputBalance(address token);
error ZeroAddress();
error NotContractAddress(address addr);
error NotERC20Token(address token);
function allOf(address account, address token, uint256 tokenIn) internal view returns (uint256 actualIn) {
if (tokenIn == type(uint256).max) {
actualIn = IERC20(token).balanceOf(account);
} else {
actualIn = tokenIn;
}
// slither-disable-next-line incorrect-equality
if (actualIn == 0) {
revert ZeroInputBalance(token);
}
}
function allOfQuiet(address account, address token, uint256 tokenIn) internal view returns (uint256 actualIn) {
if (tokenIn == type(uint256).max) {
actualIn = IERC20(token).balanceOf(account);
} else {
actualIn = tokenIn;
}
}
function ensureNonZeroAddress(address that) internal pure {
if (that == address(0)) revert ZeroAddress();
}
function ensureContract(address addr) internal view {
ensureNonZeroAddress(addr);
// from https://www.rareskills.io/post/solidity-code-length
if (addr.code.length == 0) revert NotContractAddress(addr);
}
/// @notice Sanity checks the given address for some ERC20 compliance. This does not guaranteed the contract is a valid ERC20 token
/// @dev Checks if the contract implements some of the basic ERC20 functions by calling them.
/// @dev It doesn't check for the full ERC20 interface, because that cannot be done reliably on chain since for example:
/// * The contract may implement the interface but not respond to the functions correctly
/// * Checking mutating functions such as 'approve' is practically impossible to do reliably on chain because a revert can happen for many reasons,
/// making it look like the function does not exist when it actually does.
/// * Checking for calls, even non-mutating ones, such as 'allowance', as it is takes parameters that we can't be sure won't cause reverts
/// but rather ensures that the contract responds, without reverting, to some of the functions.
// slither-disable-next-line dead-code
function sanityCheckERC20Token(address addr) internal view {
ensureContract(addr);
if (
// check all the readonly functions that IERC20 supports
!_hasNonMutatingFunction(addr, abi.encodeWithSelector(IERC20Metadata.name.selector)) ||
!_hasNonMutatingFunction(addr, abi.encodeWithSelector(IERC20Metadata.symbol.selector)) ||
!_hasNonMutatingFunction(addr, abi.encodeWithSelector(IERC20Metadata.decimals.selector)) ||
!_hasNonMutatingFunction(addr, abi.encodeWithSelector(IERC20.totalSupply.selector)) ||
!_hasNonMutatingFunction(addr, abi.encodeWithSelector(IERC20.balanceOf.selector, address(this)))
) {
revert NotERC20Token(addr);
}
}
// slither-disable-next-line dead-code
function _hasNonMutatingFunction(address contract_, bytes memory data) internal view returns (bool) {
// slither-disable-next-line low-level-calls
(bool success, ) = contract_.staticcall(data);
return success;
}
function hasNonMutatingParameterlessFunction(
address contract_,
string memory funcName
) external view returns (bool) {
bytes4 selector = bytes4(keccak256(bytes(string.concat(funcName, "()"))));
return _hasNonMutatingFunction(contract_, abi.encodeWithSelector(selector));
}
/**
* @notice Checks if a contract contains a function corresponding to a given function selector and then calls it.
* @dev First performs a low-level `call` to check if the target contract responds to the given selector. If it exists, performs a second `call` to invoke it.
* @param target The address of the contract to check and call.
* @param selector The 4-byte function selector (first 4 bytes of the Keccak-256 hash of the function signature).
* @param calldataParams The encoded calldata to pass when calling the function (excluding the selector).
* @return success Boolean indicating whether the function call succeeded.
* @return returnData The data returned from the function call.
*/
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
import {ReentrancyGuardTransientUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardTransientUpgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {BaoCheckOwner} from "@bao/internal/BaoCheckOwner.sol";
import {Token} from "./Token.sol";
import {ITokenHolder} from "./interfaces/ITokenHolder.sol";
abstract contract TokenHolder is ReentrancyGuardTransientUpgradeable, BaoCheckOwner, ITokenHolder {
using SafeERC20 for IERC20;
/// @notice function to transfer owned owned balance of a token
/// This allows. for example dust resulting from rounding errors, etc.
/// in case tokens are transferred to this contract by mistake, they can be recovered
// slither-disable-next-line reentrancy-no-eth
function sweep(address token, uint256 amount, address receiver) external onlySweeper nonReentrant {
Token.ensureNonZeroAddress(receiver);
amount = Token.allOf(address(this), token, amount);
if (amount > 0) {
emit Swept(token, amount, receiver);
_sweep(token, amount, receiver);
}
}
function _sweep(address token, uint256 amount, address receiver) internal virtual {
IERC20(token).safeTransfer(receiver, amount);
}
/// @notice function used in the 'onlySweeper' modifier
/// @dev this can be overridden to control access to the sweep function
/// @dev it's simpler to override this than the onlySweeper modifier
function _checkSweeper() internal view virtual {
_checkOwner();
}
/// @notice modifier used by the 'sweep' function
/// @dev this can be overridden to control access to the sweep function
/// @dev it's simpler to override the '_checkSweeper' function than this
modifier onlySweeper() virtual {
_checkSweeper();
_;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
// solhint-disable no-inline-assembly
/// @title DecrementalFloatingPoint
/// The term "decremental" indicates that this floating point implementation is specialized for values that
/// typically decrease over time:
/// * Loss-Focused Design: Optimized for the product factor which decreases with each loss event
/// * Precision Preservation: Maintains accuracy even as values approach zero
/// * Exponent Tracking: Records precision scaling events (no epochs)
/// * Efficient Representation: Packs multiple components into a compact uint128
///
/// @dev The real number is `magnitude * 10^{-36 - 9 * exponent}`, where `magnitude` is in range `(0, 10^36]`.
/// exponent is powers of 1e9 and as such cannot be more than 8
/// And the floating point is encoded as:
/// [ exponent | magnitude ]
/// [ 8 bits | 120 bits ]
/// [ MSB LSB ]
///
library DecrementalFloatingPoint {
/// @dev The precision of the `magnitude` in the floating point.
uint120 internal constant MAGNITUDE_PRECISION = 1e36;
// what the exponent is multiplied by to form a factor for the magnitude
uint120 internal constant SCALE_FACTOR = 1e9;
// can't be any more than this in 256 bits diff of 8 gives exponent of 72 decimals
uint8 internal constant _MAX_EXPONENT_DIFFERENCE = 8;
/// @dev The threshold below which exponent is incremented (1e27).
uint120 internal constant MIN_PRECISION = MAGNITUDE_PRECISION / SCALE_FACTOR;
/// @dev Encode `exponent` and `magnitude` to the floating point.
function encode(uint8 exponent_, uint120 magnitude_) internal pure returns (uint128 prod) {
prod = uint128(magnitude_) | (uint128(exponent_) << 120);
}
/// @dev Return the exponent of the floating point.
/// @param prod The current encoded floating point.
function exponent(uint128 prod) internal pure returns (uint8 exponent_) {
exponent_ = uint8(prod >> 120);
}
/// @dev Return the magnitude of the floating point.
/// @param prod The current encoded floating point.
function magnitude(uint128 prod) internal pure returns (uint120 magnitude_) {
magnitude_ = uint120(prod & ((1 << 120) - 1));
}
// solhint-disable-next-line explicit-types
function _divByScaleFactor(uint256 value, uint i) internal pure returns (uint256 result) {
uint256[/*DecrementalFloatingPoint._MAX_EXPONENT_DIFFERENCE + 1*/ 9] memory scaleFactors = [
uint256(1),
1e9,
1e18,
1e27,
1e36,
1e45,
1e54,
1e63,
1e72
];
result = value / scaleFactors[i];
}
/// @dev Multiply the floating point by a scalar in range (0..1].
///
/// Caller should make sure `factor` is always > 0 and <= 1
///
/// @param prod The current encoded floating point.
/// @param factor The multiplier applied to the product, multiplied by 1e18.
// function mul(uint128 prod, uint256 factor) internal pure returns (uint128 newProd) {
// // require(factor <= PRECISION, "Factor must be <= 1e36");
// // require(factor > 0, "Factor must be > 0"); // Minimum balance prevents factor=0
// uint8 currentExponent = exponent(prod);
// uint256 currentMagnitude = magnitude(prod);
// unchecked {
// // Apply the factor
// uint256 newMagnitude = (currentMagnitude * factor) / 1 ether;
// uint8 newExponent = currentExponent;
// // if result < MIN_PRECISION, scale up
// while (newMagnitude < MIN_PRECISION && newMagnitude > 0) {
// newMagnitude *= SCALE_FACTOR; // Multiply by 1e9
// newExponent += 1; // Increment exponent
// }
// // Ensure magnitude stays within bounds
// // require(newMagnitude <= PRECISION, "Magnitude overflow");
// newProd = encode(newExponent, uint120(newMagnitude));
// }
// }
// slither-disable-next-line divide-before-multiply
function mul(uint128 prod, uint256 factor) internal pure returns (uint128 newProd) {
uint8 currentExponent = exponent(prod);
uint256 currentMagnitude = magnitude(prod);
unchecked {
// Calculate intermediate result (without division yet)
uint256 intermediate = currentMagnitude * factor;
uint8 newExponent = currentExponent;
if (intermediate > 0) {
// Determine if we need scaling by checking against thresholds
uint256 divResult = intermediate / 1 ether;
// Based on the division result, determine how many scales we need
if (divResult < MIN_PRECISION) {
// We'll need at least 1 scale
if (divResult < MIN_PRECISION / 1e18) {
// Need at least 3 scales
if (divResult < MIN_PRECISION / 1e27) {
// Need 4 scales: We'll scale intermediate by 1e36
newExponent += 4;
// intermediate = (intermediate * 1e36) / 1 ether;
intermediate *= 1e18;
} else {
// Need 3 scales: We'll scale intermediate by 1e27
newExponent += 3;
// intermediate = (intermediate * 1e27) / 1 ether;
intermediate *= 1e9;
}
} else {
// Need 1-2 scales
if (divResult < MIN_PRECISION / 1e9) {
// Need 2 scales: We'll scale intermediate by 1e18
newExponent += 2;
// intermediate = (intermediate * 1e18) / 1 ether;
} else {
// Need 1 scale: We'll scale intermediate by 1e9
newExponent += 1;
// intermediate = (intermediate * 1e9) / 1 ether;
intermediate /= 1e9;
}
}
} else {
// No scaling needed, just divide by 1 ether
intermediate = divResult;
}
}
// Encode the final result
newProd = encode(newExponent, uint120(intermediate));
}
}
/// @dev Initialize a new floating point with full precision (equivalent to Liquity's P = P_PRECISION).
function init() internal pure returns (uint128) {
return encode(0, MAGNITUDE_PRECISION); // exponent=0, magnitude=1e36
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuardTransientUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardTransientUpgradeable.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IMultipleRewardAccumulator} from "src/interfaces/IMultipleRewardAccumulator.sol";
import {DecrementalFloatingPoint} from "src/math/DecrementalFloatingPoint.sol";
import {LinearMultipleRewardDistributor} from "src/reward/distributor/LinearMultipleRewardDistributor.sol";
// solhint-disable not-rely-on-time
/// @title MultipleRewardCompoundingAccumulator
/// @notice `MultipleRewardCompoundingAccumulator` is a reward accumulator for reward distribution in a staking pool.
/// In the staking pool, the total stakes will decrease unexpectedly and the user stakes will also decrease proportionally.
/// The contract will distribute rewards in proportion to a staker’s share of total stakes with only O(1) complexity.
///
/// This accumulator handles complex staking scenarios where both user stakes and total
/// stakes can decrease unexpectedly. It efficiently tracks user rewards based on their
/// proportional share of the total pool, even as these values change over time.
///
/// The mathematical model uses a system of checkpoints and floating-point calculations
/// to handle stake reductions, reward distributions, and precision concerns. It introduces
/// epochs to handle cases where total supply reduces to zero and uses exponents to
/// manage precision loss in calculations.
///
/// Key features:
/// - O(1) complexity for reward calculations regardless of time elapsed
/// - Support for multiple reward tokens
/// - Handles stake decreases correctly without requiring per-user operations
/// - Precision-preserving calculations using floating-point representation
/// - Customizable reward receivers
/// - Support for claiming historical rewards
///
/// Assume that there are n events e[1], e[2], ..., and e[n]. The types of events are user stake,
/// user unstake, total stakes decrease and reward distribution.
/// Right after event e[i], let the total pool stakes be s[i], the user pool stakes be u[i],
/// the total stake decrease is d[i], and the rewards distributed be r[i].
///
/// The basic assumptions are, if
/// + e[i] is user stake, r[i] = 0, u[i] > u[i-1] and s[i] - s[i-1] = u[i] - u[i-1].
/// + e[i] is user unstake, r[i] = 0, u[i] < u[i-1] and s[i] - s[i-1] = u[i] - u[i-1].
/// + e[i] is total stakes decrease, r[i] = 0, d[i] > 0, s[i] = s[i-1] - d[i] and u[i] = u[i-1] * (1 - d[i] / s[i-1])
/// + e[i] is reward distribution, r[i] > 0, u[i] = u[i-1] and s[i] = s[i-1].
///
/// So under the assumptions, if
/// + e[i] is user stake/unstake, we can maintain the value of u[i] and s[i] easily.
/// + e[i] is total stakes decrease, we can only maintain the value of s[i] easily.
///
/// To compute the value of u[i], assuming the only events are total stakes decrease. Then after n events,
/// u[n] = u[0] * (1 - d[1]/s[0]) * (1 - d[2]/s[1]) * ... * (1 - d[n]/s[n-1])
///
/// To compute the user stakes correctly, we can maintain the value of
/// p[n] = (1 - d[1]/s[0]) * (1 - d[2]/s[1]) * ... * (1 - d[n]/s[n-1])
///
/// Then the user stakes from event x to event y is u[y] = u[x] * p[y] / p[x]
///
/// As for the accumutated rewards, the total amount of rewards for the user is:
/// u[0] u[1] u[n-1]
/// g[n] = r[1] * ---- + r[2] * ---- + ... + r[n] * ------
/// s[0] s[1] s[n-1]
///
/// Also, u[n] = u[0] * p[n], we have
/// p[0] p[1] p[n-1]
/// g[n] = u[0] * (r[1] * ---- + r[2] * ---- + ... + r[n] * ------)
/// s[0] s[1] s[n-1]
///
/// And, the rewards from event x to event y (both inclusive) for the user is:
/// p[x-1] p[x] p[y-1]
/// g[x->y] = u[x] * (r[x] * ------ + r[x+1] * ---- + ... + r[y] * ------)
/// s[x-1] s[x] s[y-1]
///
/// To check the accumulated total user rewards, we can maintain the value of
/// p[0] p[1] p[n-1]
/// acc = r[1] * ---- + r[2] * ---- + ... + r[n] * ------
/// s[0] s[1] s[n-1]
///
/// For each event, if
/// + e[i] is user stake or unstake, new accumulated rewards is
/// gain += u[i-1] * (acc - last_user_acc) / last_user_prod,
/// and update `last_user_acc` to `acc`
/// and update `last_user_prod` to p[i].
/// + e[i] is total stakes decrease, p[i] *= (1 - d[i] / s[i-1])
/// + e[i] is reward distribution, acc += r[i] * p[i-1] / s[i-1].
///
/// Notice that total stakes decrease event will possible make s[i] be zero. We introduce epoch to handle this problem.
/// When the total supply reduces to zero, we start a new epoch.
///
/// Another problem is precision loss in solidity, the p[i] will eventually become a very small non-zero value. To solve
/// the problem, we treat p[i] as m[i] * 10^{-18 - 9 * e[i]}, where m[i] is the magnitude and e[i] is the exponent.
/// When the value of m[i] is smaller than 10^9, we will multiply m[i] by 1e9 and then increase e[i] by one.
// e[i]: The i-th event in the system (can be stake, unstake, total stakes decrease, or reward distribution)
// s[i]: Total pool stakes after event i (corresponds to the contract's internal tracking of total stakes)
// u[i]: User's personal stakes after event i (tracked per user)
// d[i]: Amount of total stake decrease in event i
// r[i]: Amount of rewards distributed in event i
// These variables directly map to contract data structures:
// Math Notation Code Implementation
// s[i] Tracked via the product value in _getTotalPoolShare()
// u[i] Tracked via user checkpoint data in userRewardSnapshot
// d[i] Used in calculations when total stakes decrease
// r[i] Amount added to reward accumulators
// The mathematical model describes how these values interact during different events to maintain accurate reward distribution despite fluctuating stake amounts.
///
/// @dev The method comes from liquity's StabilityPool, the paper is in
/// https://github.com/liquity/dev/blob/main/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf
abstract contract MultipleRewardCompoundingAccumulator is
ReentrancyGuardTransientUpgradeable,
LinearMultipleRewardDistributor,
IMultipleRewardAccumulator
{
using SafeERC20 for IERC20;
using DecrementalFloatingPoint for uint128;
/*************
* Constants *
*************/
/// @dev The precision used to calculate accumulated rewards.
uint256 internal constant _REWARD_PRECISION = 1e18;
/// @dev Compiler will pack this into single `uint256`.
struct RewardSnapshot {
// The timestamp when the snapshot is updated.
uint64 timestamp;
// The reward integral until now.
uint192 integral;
}
/// @dev Compiler will pack this into single `uint256`.
struct ClaimData {
// The number of pending rewards.
uint128 pending;
// The number of claimed rewards.
uint128 claimed;
}
/// @dev Compiler will pack this into two `uint256`.
struct UserRewardSnapshot {
// The claim data for the user.
ClaimData rewards;
// The reward snapshot for user.
RewardSnapshot checkpoint;
}
/*************
* Variables *
*************/
struct MultipleRewardCompoundingAccumulatorStorage {
/// @inheritdoc IMultipleRewardAccumulator
mapping(address => address) rewardReceiver;
/// @notice Mapping from reward token address to global reward snapshot.
///
/// - The inner mapping records the `acc` at different `exponent`
/// - The outer mapping records the (exponent => acc) mappings, for different tokens.
///
/// @dev The integral is defined as 1e18 * ∫(rate(t) * prod(t) / totalPoolShare(t) dt).
mapping(address => mapping(uint8 => uint192)) tokenToExponentToIntegral;
/// @notice Mapping from user address to reward token address to user reward snapshot.
///
/// @dev The integral is the value of `rewardSnapshot[token].integral` when the snapshot is taken.
mapping(address => mapping(address => UserRewardSnapshot)) userRewardSnapshot;
}
// slither-disable-next-line dead-code
function _tokenToExponentToIntegral(address token, uint8 exponent) internal view returns (uint192 globalIntegral) {
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
globalIntegral = $.tokenToExponentToIntegral[token][exponent];
}
// slither-disable-next-line dead-code
function _userRewardSnapshot(
address account,
address token
) internal view returns (UserRewardSnapshot memory userRewardSnapshot_) {
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
userRewardSnapshot_ = $.userRewardSnapshot[account][token];
}
// slither-disable-next-line dead-code
function _setUserRewardSnapshot(
address account,
address token,
UserRewardSnapshot memory userRewardSnapshot_
) internal {
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
$.userRewardSnapshot[account][token] = userRewardSnapshot_;
}
// chisel eval 'keccak256(abi.encode(uint256(keccak256("bao.storage.MultipleRewardCompoundingAccumulator")) - 1)) & ~bytes32(uint256(0xff))'
bytes32 private constant _MULTIPLEREWARDCOMPOUNDINGACCUMULATOR_STORAGE =
0x47ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e7900;
function _getMultipleRewardCompoundingAccumulatorStorage()
private
pure
returns (MultipleRewardCompoundingAccumulatorStorage storage $)
{
// solhint-disable-next-line no-inline-assembly
assembly {
$.slot := _MULTIPLEREWARDCOMPOUNDINGACCUMULATOR_STORAGE
}
}
/***************
* Constructor *
***************/
// solhint-disable-next-line func-name-mixedcase
// function __MultipleRewardCompoundingAccumulator_init() internal onlyInitializing {
// // __LinearMultipleRewardDistributor_init();
// __ReentrancyGuardTransient_init();
// // __MultipleRewardCompoundingAccumulator_init_unchained();
// }
// // solhint-disable-next-line func-name-mixedcase, no-empty-blocks
// function __MultipleRewardCompoundingAccumulator_init_unchained() internal onlyInitializing {}
/// @custom:oz-upgrades-unsafe-allow constructor
/// @dev we don't disable initializers here, because this contract is abstract - the deriving contract should do that.
constructor(
uint256 rewardManagerRole,
uint256 rewardDepositorRole,
uint40 periodLength
) LinearMultipleRewardDistributor(rewardManagerRole, rewardDepositorRole, periodLength) {}
/*************************
* Public View Functions *
*************************/
function rewardReceiver(address account) external view returns (address) {
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
return $.rewardReceiver[account];
}
/// @inheritdoc IMultipleRewardAccumulator
function claimable(address account, address token) external view virtual override returns (uint256) {
return _claimable(account, token, true);
}
/// @inheritdoc IMultipleRewardAccumulator
function claimed(address account, address token) external view returns (uint256) {
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
return $.userRewardSnapshot[account][token].rewards.claimed;
}
/****************************
* Public Mutator Functions *
****************************/
/// @inheritdoc IMultipleRewardAccumulator
function setRewardReceiver(address newReceiver) external {
address caller = _msgSender();
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
address oldReceiver = $.rewardReceiver[caller];
$.rewardReceiver[caller] = newReceiver;
emit UpdateRewardReceiver(caller, oldReceiver, newReceiver);
}
/// @inheritdoc IMultipleRewardAccumulator
function checkpoint(address account) external virtual override nonReentrant {
_checkpoint(account);
}
/// @inheritdoc IMultipleRewardAccumulator
function claim() external override {
address sender = _msgSender();
claim(sender, address(0));
}
/// @inheritdoc IMultipleRewardAccumulator
function claim(address account) external override {
claim(account, address(0));
}
/// @inheritdoc IMultipleRewardAccumulator
function claim(address account, address receiver) public override nonReentrant {
if (account != _msgSender() && receiver != address(0)) {
revert ClaimOthersRewardToAnother();
}
_checkpoint(account);
_claim(account, receiver);
}
/// @inheritdoc IMultipleRewardAccumulator
function claimHistorical(address[] memory tokens) external nonReentrant {
address sender = _msgSender();
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
_checkpoint(sender);
address receiver = $.rewardReceiver[sender];
if (receiver == address(0)) {
receiver = sender;
}
for (uint256 i = 0; i < tokens.length; i++) {
_claimSingle(sender, tokens[i], receiver); // wake-disable-line unchecked-return-value
}
}
/// @inheritdoc IMultipleRewardAccumulator
function claimHistorical(address account, address[] memory tokens) external nonReentrant {
_checkpoint(account);
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
address receiver = $.rewardReceiver[account];
if (receiver == address(0)) {
receiver = account;
}
for (uint256 i = 0; i < tokens.length; i++) {
_claimSingle(account, tokens[i], receiver); // wake-disable-line unchecked-return-value
}
}
/**********************
* Internal Functions *
**********************/
// @dev like a mulDiv, but for product factors
function _scaleAdjustedValue(
uint256 baseValue,
uint128 toProd,
uint128 fromProd
) internal pure returns (uint256 adjusted) {
uint8 fromExp = fromProd.exponent();
uint8 toExp = toProd.exponent();
uint256 fromMag = fromProd.magnitude();
uint256 toMag = toProd.magnitude();
if (baseValue == 0 || toExp < fromExp || toExp - fromExp > DecrementalFloatingPoint._MAX_EXPONENT_DIFFERENCE) {
adjusted = 0; // Too many scale changes
} else {
adjusted = DecrementalFloatingPoint._divByScaleFactor(
Math.mulDiv(baseValue, toMag, fromMag),
toExp - fromExp
);
}
}
/// @dev Internal function to compute the amount of asset deposited after several liquidation.
///
/// @param initialBalance The amount of asset deposited initially.
/// @param initialProduct The epoch state snapshot at initial depositing.
/// @return compoundedBalance The amount asset deposited after several liquidation.
function _getCompoundedBalance(
uint256 initialBalance,
uint128 initialProduct,
uint128 currentProduct
) internal pure returns (uint256 compoundedBalance) {
return _scaleAdjustedValue(initialBalance, currentProduct, initialProduct);
}
function _claimable(
address account,
address token,
bool includeTemporalPending
) internal view virtual returns (uint256 claimable_) {
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
claimable_ = uint256($.userRewardSnapshot[account][token].rewards.pending);
(uint128 userProd, uint256 shares) = _getUserPoolShare(account);
if (shares > 0) {
uint8 userExponent = userProd.exponent();
(uint128 currentProd, uint256 totalShares) = _getTotalPoolShare();
uint8 maxExponentsToCheck = uint8(
Math.min(DecrementalFloatingPoint._MAX_EXPONENT_DIFFERENCE, currentProd.exponent() - userExponent)
);
// Get the sum 'S' from the epoch at which the stake was made. The gain may span many exponent changes.
mapping(uint8 => uint192) storage tokenIntegrals = $.tokenToExponentToIntegral[token];
uint192 integral = tokenIntegrals[userExponent];
for (uint8 i = 1; i <= maxExponentsToCheck; ++i) {
uint192 integralAtScale = tokenIntegrals[userExponent + i];
if (integralAtScale > 0) {
// Skip zero integrals for gas efficiency
integral += uint192(DecrementalFloatingPoint._divByScaleFactor(integralAtScale, i));
}
}
// Get user's checkpoint integral
uint192 userCheckpointIntegral = $.userRewardSnapshot[account][token].checkpoint.integral;
if (integral > userCheckpointIntegral) {
claimable_ += Math.mulDiv(
shares,
integral - userCheckpointIntegral,
userProd.magnitude() * _REWARD_PRECISION
);
}
if (includeTemporalPending && totalShares > 0) {
(uint256 amount, ) = _pendingRewards(token);
// if exponents are the same this degenerates to (amount * shares) / totalShares
claimable_ += _scaleAdjustedValue(amount * shares, currentProd, userProd) / totalShares;
}
}
}
/// @dev Internal function to update the global and user snapshot.
/// @param account The address of user to update.
/// Use zero address if you only want to update global snapshot.
function _checkpoint(address account) internal virtual {
_distributePendingReward();
if (account != address(0)) {
// get all the reward tokens ever
address[] memory activeTokens = activeRewardTokens();
address[] memory historicalTokens = historicalRewardTokens();
uint256 activeLength = activeTokens.length;
uint256 totalLength = activeLength + historicalTokens.length;
// Early exit if no tokens to process
if (totalLength == 0) {
return;
}
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
(uint128 currentProd, ) = _getTotalPoolShare();
uint8 exponent = currentProd.exponent();
for (uint256 i = 0; i < totalLength; i++) {
address token = (i < activeLength) ? activeTokens[i] : historicalTokens[i - activeLength];
UserRewardSnapshot memory snapshot = $.userRewardSnapshot[account][token];
snapshot.rewards.pending = uint128(_claimable(account, token, false));
snapshot.checkpoint.integral = $.tokenToExponentToIntegral[token][exponent];
snapshot.checkpoint.timestamp = uint64(block.timestamp);
$.userRewardSnapshot[account][token] = snapshot;
}
}
}
/// @dev Internal function to claim active reward tokens.
///
/// @param account The address of user to claim.
/// @param receiver The address of recipient of the reward token.
function _claim(address account, address receiver) internal virtual {
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
address receiverStored = $.rewardReceiver[account];
if (receiverStored != address(0) && receiver == address(0)) {
receiver = receiverStored;
}
if (receiver == address(0)) {
receiver = account;
}
address[] memory activeRewardTokens = activeRewardTokens();
for (uint256 i = 0; i < activeRewardTokens.length; i++) {
_claimSingle(account, activeRewardTokens[i], receiver); // wake-disable-line unchecked-return-value
}
}
/// @dev Internal function to claim single reward token.
/// Caller should make sure `_checkpoint` is called before this function.
///
/// @param account The address of user to claim.
/// @param token The address of reward token.
/// @param receiver The address of recipient of the reward token.
function _claimSingle(address account, address token, address receiver) internal virtual returns (uint256) {
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
ClaimData memory rewards = $.userRewardSnapshot[account][token].rewards;
uint256 amount = rewards.pending;
if (amount > 0) {
rewards.claimed += rewards.pending;
rewards.pending = 0;
$.userRewardSnapshot[account][token].rewards = rewards;
IERC20(token).safeTransfer(receiver, amount);
emit Claim(account, token, receiver, amount);
}
return amount;
}
/// @inheritdoc LinearMultipleRewardDistributor
function _accumulateReward(address token, uint256 amount) internal virtual override {
// slither-disable-next-line incorrect-equality
if (amount == 0) {
return;
}
(uint128 currentProd, uint256 totalShare) = _getTotalPoolShare();
if (totalShare == 0) {
// no deposits, queue rewards
_getRewardData(token).queued += uint96(amount);
return;
}
uint8 exponent = currentProd.exponent();
MultipleRewardCompoundingAccumulatorStorage storage $ = _getMultipleRewardCompoundingAccumulatorStorage();
uint192 integral = $.tokenToExponentToIntegral[token][exponent];
integral += uint192(Math.mulDiv(amount * _REWARD_PRECISION, uint256(currentProd.magnitude()), totalShare));
$.tokenToExponentToIntegral[token][exponent] = integral;
}
/// @dev Internal function to get the total pool shares.
function _getTotalPoolShare() internal view virtual returns (uint128 currentProd, uint256 totalShare);
/// @dev Internal function to get the amount of user shares.
///
/// @param account The address of user to query.
function _getUserPoolShare(address account) internal view virtual returns (uint128 previousProd, uint256 share);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
interface IStabilityPool {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when user deposit asset into this contract.
/// @param owner The address of asset owner.
/// @param receiver The address of receiver of the asset in this contract.
/// @param amount The amount of asset deposited.
event Deposit(address indexed owner, address indexed receiver, uint256 amount);
/// @notice Emitted when the amount of deposited asset changed due to liquidation or deposit or unlock.
/// @param owner The address of asset owner.
/// @param newDeposit The new amount of deposited asset.
/// @param loss The amount of asset used by liquidation.
event UserDepositChange(address indexed owner, uint256 newDeposit, uint256 loss);
/// @notice Emitted when user withdraw asset.
/// @param owner The address of asset owner.
/// @param reciever The address of receiver of the asset.
/// @param amount The amount of token to withdraw.
event Withdraw(address indexed owner, address indexed reciever, uint256 amount);
/// @notice Emitted when a reward token is gained.
/// @param rewardToken address of the reward token
/// @param rewardAmount The amount of token gained.
event RewardReceived(address rewardToken, uint256 rewardAmount);
event Liquidated(
address liquidatedToken,
uint256 liquidatedAmount,
address liquidatedToToken,
uint256 liquidatedToAmount
);
/// @notice Emitted when a withdrawal request is created
/// @param owner The address creating the request
/// @param start The timestamp when withdrawal without fee starts
/// @param end The timestamp when the withdrawal window ends
event WithdrawalRequested(address indexed owner, uint64 start, uint64 end);
/// @notice Emitted when a withdrawal request is updated (typically ended early after a withdraw)
/// @param owner The address whose request was updated
/// @param start The original/unchanged start timestamp
/// @param end The new end timestamp (often current time - 1)
event WithdrawalRequestUpdated(address indexed owner, uint64 start, uint64 end);
/// @notice Emitted when a withdrawal request is cancelled due to a deposit
/// @param owner The address whose request was cancelled
event WithdrawalRequestCancelled(address indexed owner);
/// @notice Emitted when an early withdrawal fee is charged
/// @param owner The address paying the fee
/// @param amount The fee amount
event EarlyWithdrawalFee(address indexed owner, uint256 amount);
/// @notice Emitted when the early withdrawal fee is updated
/// @param newFee The new fee ratio (scaled by 1e18)
event EarlyWithdrawalFeeUpdated(uint256 newFee);
/// @notice Emitted when the fee address is updated
/// @param newFeeAddress The new fee address
event FeeAddressUpdated(address newFeeAddress);
/// @notice Emitted when the withdrawal window parameters are updated
/// @param newStartDelay The new start delay (seconds from now to start)
/// @param newEndWindow The window period (seconds duration after start)
event WithdrawalWindowUpdated(uint256 newStartDelay, uint256 newEndWindow);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @dev Thrown when the deposited amount is zero.
error DepositZeroAmount();
/// @dev Thrown when the deposited amount is less than the minimum.
error DepositAmountLessThanMinimum(uint256 amount, uint256 minAmount);
/// @dev Thrown when the withdrawn amount is zero.
error WithdrawZeroAmount();
/// @dev Thrown when the deposited amount is less than the minimum.
error WithdrawAmountLessThanMinimum(uint256 amount, uint256 minAmount);
/// @dev Thrown when the withdrawn amount is zero.
error WithdrawAmountExceedsBalance(uint256 amount, uint256 balance);
/// @dev Thrown when the liquidation token given is not a valid one
/// either wrapped collateral or leveraged tokens
error InvalidLiquidationToken(address token);
/// @dev Thrown when a receiver address is not valid
error InvalidReceiver(address receiver);
/// @dev Thrown when a provided fee is invalid
error InvalidFee(uint256 fee);
/// @dev Thrown when the fee address is invalid (zero address)
error InvalidFeeAddress(address feeAddress);
/// @dev Thrown when withdrawal window parameters are invalid
error InvalidWithdrawalWindow(uint256 startDelay, uint256 endWindow);
/// @dev Thrown when attempting to withdraw without an active request or after it ended
error NoActiveWithdrawalRequest(address owner);
/*//////////////////////////////////////////////////////////////
PUBLIC READ FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice The role used for notifying rebalancing.
function REBALANCER_ROLE() external view returns (uint256 role); // solhint-disable-line func-name-mixedcase
/// @notice Return the address of token the asset token is liquidated to when needed and requested.
function LIQUIDATION_TOKEN() external view returns (address token); // solhint-disable-line func-name-mixedcase
/// @notice Return the minimum the amount of assets the pool can hold if non-zero.
function MIN_TOTAL_ASSET_SUPPLY() external view returns (uint256 token); // solhint-disable-line func-name-mixedcase
/// @notice Return the minimum the amount of assets that can be deposited in one call.
function MIN_DEPOSIT() external view returns (uint256 token); // solhint-disable-line func-name-mixedcase
/// @notice Return the address of underlying token of this contract.
function ASSET_TOKEN() external view returns (address token); // solhint-disable-line func-name-mixedcase
/// @notice Return the total amount of asset deposited to this contract.
function totalAssetSupply() external view returns (uint256 amount);
/// @notice Return the historical total asset deposited to this contract.
// solhint-disable-next-line explicit-types
function totalAssetSupplyHistory(uint index) external view returns (uint40 atDay, uint256 amount);
/// @notice Return the amount of assets currently attributed to 'account'.
function assetBalanceOf(address account) external view returns (uint256 amount);
/// @notice Error trackers for the error correction in the loss calculation.
function lastAssetLossError() external view returns (uint256);
/// @notice Get the withdrawal request window for an account
/// @return start The timestamp when fee-free withdrawal starts
/// @return end The timestamp when the withdrawal window ends
function getWithdrawalRequest(address account) external view returns (uint64 start, uint64 end);
/// @notice The current early withdrawal fee ratio (scaled by 1e18)
function getEarlyWithdrawalFee() external view returns (uint256);
/// @notice The address that receives early withdrawal fees
function getFeeAddress() external view returns (address);
/// @notice Get the global withdrawal window configuration
/// @return startDelay The delay in seconds before a window starts after a request
/// @return endWindow The window duration in seconds (must be > 0)
function getWithdrawalWindow() external view returns (uint64 startDelay, uint64 endWindow);
/*//////////////////////////////////////////////////////////////
PUBLIC UPDATE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Deposit some asset to this contract.
/// @dev Use `amount=uint256(-1)` if you want to deposit all asset held.
/// @param assetAmount The amount of asset to deposit.
/// @param receiver The address of recipient for the deposited asset.
/// @param minAmount The minimum amount to deposit
/// @return sharesMinted the amount of shares sent to 'receiver'
function deposit(uint256 assetAmount, address receiver, uint256 minAmount) external returns (uint256 sharesMinted);
/// @notice Withdraw asset from this contract.
/// @dev
/// - Requires an existing withdrawal request (created via requestWithdrawal()).
/// - Fee rules:
/// - Before start: allowed, early-withdrawal fee applies.
/// - During [start, end]: allowed, no fee applies.
/// - After end: allowed, early-withdrawal fee applies.
/// - Calling withdraw ends the request window immediately (both start and end are zeroed).
/// - Use `assetAmount=type(uint256).max` to withdraw full balance.
/// @param assetAmount The amount of asset to withdraw.
/// @param receiver The address of recipient for the withdrawn asset.
/// @param minAmount The minimum acceptable withdrawn amount (post-fee), to protect against slippage/fee changes.
/// @return sharesBurned the amount of shares sent to 'receiver'
function withdraw(uint256 assetAmount, address receiver, uint256 minAmount) external returns (uint256 sharesBurned);
/// @notice Create or update a withdrawal request for msg.sender.
/// @dev Sets a window: start = now + startDelay; end = start + endWindow (window period).
/// - A deposit made during an active window cancels the request (start and end are zeroed).
/// - A successful withdraw clears the request immediately (start and end are zeroed).
function requestWithdrawal() external;
/// @notice perform a liquidation of the amount
// function liquidate(uint256 liquidatedAmount) external returns (uint256 returnedAmount);
/*//////////////////////////////////////////////////////////////
PROTECTED UPDATE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Notify the stability pool of a liquidation event.
function notifyLiquidation(uint256 liquidated, uint256 returned) external;
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
/// @title Bao Minter
/// @author rootminus0x1 based on (albeit significantly modified) Aladdin's FX system
/// @notice Provides an interface for minting and redeeming pegged and leveraged tokens, some with fees, others without.
/// <br>
/// For the fee'd fuctions equivalent "dry run" functions are available that could allow a user to know what
/// fees, discounts, etc. are expected (modulo slippage). This id designed for a user interface to use.
/// <br>
/// Configuration functions are available such as for allowing setting of:
/// <ul>
/// <li>the fee/discount/disallow configuration
/// <li>the collateral ratio that rebalancing can start
/// <li>the price oracle and rate (for wrapped) of the collateral
/// <li>the fee receiver and discount provider (reserve pool)
/// </ul>
/// Various queries are provided such as:
/// <ul>
/// <li>the net asset values of the tokens,
/// <li>leverage ratio of the leveraged tokens
/// <li>collateral ratio of the system
/// </ul>
interface IMinter {
/*//////////////////////////////////////////////////////////////
DATA STRUCTURES
//////////////////////////////////////////////////////////////*/
struct IncentiveConfig {
// note: incentive ratios have one more entry than the band bounds do
// the boundaries of the collateral ratio where the incentive ratios apply
// must be strictly increasing at the precision of 18 decimals
uint256[] collateralRatioBandUpperBounds;
// incentive ratios for the above bands , interval (-1 ether, 1 ether]
// positive = fee ratio, negative for discount, == 1 ether disallow
// any 1 ether values must be at index 0
// no negative values are allowed in the highest band
int256[] incentiveRatios;
}
struct Config {
// bonus/fees
IncentiveConfig mintPeggedIncentiveConfig;
IncentiveConfig redeemPeggedIncentiveConfig;
// leverage tokens have their own intrinsic value in that they increase in leverage the lower the collateral
// ratio, so there is a convenient intrinsic incentive to mint at low collateral ratios
IncentiveConfig mintLeveragedIncentiveConfig;
IncentiveConfig redeemLeveragedIncentiveConfig;
}
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when peggedToken is minted.
/// @param sender The address of collateral token owner.
/// @param receiver The address of receiver for peggedToken or leveragedToken.
/// @param collateralIn The amount of collateral token deposited.
/// @param peggedOut The amount of peggedToken minted.
event MintPeggedToken(address indexed sender, address indexed receiver, uint256 collateralIn, uint256 peggedOut);
/// @notice Emitted when leveragedToken is minted.
/// @param sender The address of collateral token owner.
/// @param receiver The address of receiver for peggedToken or leveragedToken.
/// @param collateralIn The amount of collateral token deposited.
/// @param leveragedOut The amount of leveragedToken minted.
event MintLeveragedToken(
address indexed sender,
address indexed receiver,
uint256 collateralIn,
uint256 leveragedOut
);
/// @notice Emitted when someone redeems a peggedToken .
/// @param sender The address of peggedToken owner.
/// @param receiver The address of receiver for collateral and leveraged token.
/// @param peggedTokenBurned The amount of peggedToken burned.
/// @param collateralOut The amount of collateral token redeemed.
/// @param leveragedOut The amount of leveraged token redeemed
event RedeemPeggedToken(
address indexed sender,
address indexed receiver,
uint256 peggedTokenBurned,
uint256 collateralOut,
uint256 leveragedOut
);
/// @notice Emitted when someone redeem collateral token with peggedToken or leveragedToken.
/// @param sender The address of peggedToken and leveragedToken owner.
/// @param receiver The address of receiver for collateral token.
/// @param leveragedTokenBurned The amount of leveragedToken burned.
/// @param collateralOut The amount of collateral token redeemed.
event RedeemLeveragedToken(
address indexed sender,
address indexed receiver,
uint256 leveragedTokenBurned,
uint256 collateralOut
);
/// @notice Emitted when there's been a slashing event and Zhenglong responds by calling reset.
event Reset(uint256 oldCollateral, uint256 newCollateral);
/// @notice Emitted whenever the config is updated.
event UpdateConfig(Config newConfig);
/// @notice Emitted when the fee receiving contract is updated.
/// @param oldFeeReceiver The address of previous fee receiving contract.
/// @param newFeeReceiver The address of the new (current) fee receiving contract.
event UpdateFeeReceiver(address indexed oldFeeReceiver, address indexed newFeeReceiver);
/// @notice Emitted when the platform contract is updated.
/// @param oldReservePool The address of previous reserve pool contract.
/// @param newReservePool The address of new (current) reserve pool contract.
event UpdateReservePool(address indexed oldReservePool, address indexed newReservePool);
/// @notice Emitted when the price oracle contract is updated.
/// @param oldPriceOracle The address of previous price oracle contract.
/// @param newPriceOracle The address of current price oracle contract.
event UpdatePriceOracle(address indexed oldPriceOracle, address indexed newPriceOracle);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/// @dev Thrown when the oracle price is invalid.
error InvalidOraclePrice();
/// @dev Thrown when the oracle price is zero.
error ZeroOraclePrice();
// @inderitdoc Token
/// @dev thrown when zero collateral is passed in or -1 is passed in and the balance is zero
error ZeroInputBalance(address token);
error RequestedBonusNotGiven(uint256 requested, uint256 available);
/// @dev Thrown when collateral is passed but minting is prevented for some other reason.
error MintZeroAmount(address mintingToken);
/// @dev Thrown when collateral is passed but minting is reduced below the miniumum requested.
error MintInsufficientAmount(address mintingToken, uint256 actual, uint256 miniumum);
/// @dev Thrown when pegged or leveraged is passed but redeeming is prevented for some other reason.
error ReturnZeroAmount(address returningToken);
/// @dev Thrown when pegged or leveraged is passed but redeeming is reduced below the miniumum requested.
error ReturnInsufficientAmount(address returningToken, uint256 actual, uint256 miniumum);
error NoRedeemableTokens(address redeemingToken);
error InsufficientRedeemableTokens(address redeemingToken, uint256 available, uint256 requested);
/// @dev thrown if a ratio doesn't make sense in some context
error InvalidRatio();
error TooManyCollateralRatioBounds(string config, uint count, uint max); // solhint-disable-line explicit-types
error InvalidCollateralRatioBoundValue(string config, uint256 value, uint index, string reason); // solhint-disable-line explicit-types
error CollateralRatioBoundValueNotIncreasing(
string config,
uint256 shouldBeLessOrEqual,
uint index, // solhint-disable-line explicit-types
uint256 shouldBeGreaterOrEqual
);
error TooManyIncentiveRatios(string config, uint count, uint max); // solhint-disable-line explicit-types
error TooFewIncentiveRatios(string config, uint count, uint min); // solhint-disable-line explicit-types
error InvalidIncentiveRatioValue(string config, uint index, int256 shouldBeMinusOnetoOne, string reason); // solhint-disable-line explicit-types
error IncentiveRatioTooPrecise(string config, int256 value);
error CollateralRatioBoundsIncentivesLengthsMismatch(string config, uint256 oneLess, uint256 oneMore);
error CollateralRatioBoundTooPrecise(string config, uint256 value);
error NoDepegBoundaryOrDisallow(string config);
/// @notice Thrown when the burn interface does not match one known by this contract
error UnsupportedBurnInterface(bytes4 interfaceId);
/*//////////////////////////////////////////////////////////////
PUBLIC READ FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice returns the role needed to access the zero fee functions (free*)
// solhint-disable-next-line func-name-mixedcase
function ZERO_FEE_ROLE() external view returns (uint256);
/// @notice returns the role needed to access the harvesting function
// solhint-disable-next-line func-name-mixedcase
function HARVESTER_ROLE() external view returns (uint256);
/// @notice Return the address of the collateral token
// solhint-disable-next-line func-name-mixedcase
function WRAPPED_COLLATERAL_TOKEN() external view returns (address);
/// @notice Return the address of the pegged token.
// solhint-disable-next-line func-name-mixedcase
function PEGGED_TOKEN() external view returns (address);
/// @notice Return the address of the leveraged token.
// solhint-disable-next-line func-name-mixedcase
function LEVERAGED_TOKEN() external view returns (address);
/// @notice Return the current config.
function config() external view returns (Config memory);
/// @notice Return the current collateral ratio of the system (18 decimals).
/// This is the raw ratio of (collateral value) / (pegged token balance) without any flooring.
/// When the system is depegged (ratio < 1), this function will return the actual value below 1.
///
/// Special cases:
/// - If both collateral and pegged tokens are zero: Returns 1 ether (to avoid discontinuity when first minting)
/// - If pegged tokens are zero but collateral exists: Returns a very large number (1 ether * 1 ether * 1 ether)
/// - If collateral price is zero: Returns 1 ether * 1 ether
///
/// This value is used for critical system operations like rebalancing, especially in depegged scenarios.
/// For the real market value of the pegged token, see peggedTokenPrice() instead.
function collateralRatio() external view returns (uint256);
/// @notice Return the current leveraged ratio of the leveragedToken (18 decimals).
function leverageRatio() external view returns (uint256);
/// @notice Return the price of a leveraged token in terms of the pegged token's underlying (18 decimals).
function leveragedTokenPrice() external view returns (uint256);
/// @notice Return the price of a pegged token in terms of the pegged token's underlying (18 decimals).
/// this should normally be 1 ether but if the token depegs then this number will be this token's share of the
/// collateral.
function peggedTokenPrice() external view returns (uint256);
/// @notice Returns the amount of Pegged tokens that need to be redeemed to achieve a given target collateral ratio
/// This is based on the fact that redeeming pegged tokens has a upward pressure on collateral ratio
/// If, however, there are no leveraged tokens, or their value is 0 due to a depeg, then no amount of redemption can
/// change the collateral ratio.
/// In the case of total leveraged token value being zero we return the supply minted by this Minter
/// @param targetCollateralRatio The collateral ratio that we aim to meet by the returned pegged tokens redeemed.
/// Must be greater than 1 ether
/// @return peggedForCollateral The number of pegged tokens that need to be redeemed to achieve the `targetCollateralRatio`
/// given the current collateral ratio and redeeming into collateral
/// @return peggedForLeveraged The number of pegged tokens that need to be redeemed to achieve the `targetCollateralRatio`
/// given the current collateral ratio and redeeming into leveaged tokens
function redeemPeggedForCollateralRatio(
uint256 targetCollateralRatio
) external view returns (uint256 peggedForCollateral, uint256 peggedForLeveraged);
/// @notice Returns the address of the price oracle contract
function priceOracle() external view returns (address);
/// @notice Returns the address of the reserve pool contract that provides the collateral for discounts
function reservePool() external view returns (address);
/// @notice Returns the address of the fee receiver contract
function feeReceiver() external view returns (address);
/// @notice Returns the totalAmount of pegged tokens minted, and not redeemed, by the minter
function peggedTokenBalance() external view returns (uint256);
/// @notice Returns the totalAmount of leveraged tokens minted, and not redeemed, by the minter
/// This number is the same as the totelSupply of the leveraged token
function leveragedTokenBalance() external view returns (uint256);
/// @notice Returns the totalAmount of collateral tokens received in exchange for pegged and leveraged tokens
/// (18 decimals)
function collateralTokenBalance() external view returns (uint256);
/// @notice Returns the current instantaneous incentive ratio for minting pegged tokens (18 decimals).
/// A positive number is a fee ratio; a negative number indicates a discount.
function mintPeggedTokenIncentiveRatio() external view returns (int256 incentiveRatio);
/// @notice Returns the current instantaneous incentive ratio for redeeming pegged tokens (18 decimals).
/// A positive number is a fee ratio; a negative number indicates a discount.
function redeemPeggedTokenIncentiveRatio() external view returns (int256 incentiveRatio);
/// @notice Returns the current instantaneous incentive ratio for minting leveraged tokens (18 decimals).
/// A positive number is a fee ratio; a negative number indicates a discount.
function mintLeveragedTokenIncentiveRatio() external view returns (int256 incentiveRatio);
/// @notice Returns the current instantaneous incentive ratio for redeeming leveraged tokens (18 decimals).
/// A positive number is a fee ratio; a negative number indicates a discount.
function redeemLeveragedTokenIncentiveRatio() external view returns (int256 incentiveRatio);
/// @notice Returns values that will be used if an actual `mintPeggedToken` function call is made.
/// This function is useful to give a user an indication of the actual transfers that would occur if the function
/// was to be called.
///
/// ┌──────┐ ┌────────┐ ┌──────────┐
/// │ user │ ─── collateralTaken ──► │ minter │ ─────── fee ───────► │ fee │
/// │ │ ◀════ peggedMinted ════ │ │ (only +ve, i.e. fee) │ receiver │
/// └──────┘ └────────┘ └──────────┘
/// │
/// collateral held += collateralTaken - fee
///
/// @param collateralIn The amount of wrapped collateral to be exchanged for pegged tokens.
/// @return incentiveRatio the effective incentive ratio for `collateralIn` collateral tokens. A positive number is
/// a fee ratio; a negative number indicates a discount.
/// @return fee The amount deducted from `collateralIn` as a fee.
/// @return collateralTaken The amount of collateral used in the exchange.
/// This is usually the same as `collateralIn` but at certain collateral ratio levels minting pegged tokens may be
/// disallowed by configuration.
/// @return peggedMinted The amount of pegged tokens that would be minted, given the 'collateralTaken' value and 'fee'.
/// @return price The price of collateral in terms of pegged tokens used in the calculations.
/// @return rate The conversion rate from underlying collateral to wrapped collateral.
function mintPeggedTokenDryRun(
uint256 collateralIn
)
external
view
returns (
int256 incentiveRatio,
uint256 fee,
uint256 collateralTaken,
uint256 peggedMinted,
uint256 price,
uint256 rate
);
/// @notice Returns values that will be used if an actual `redeemPeggedToken` function call is made.
/// ┌──────────────┐
/// ┌──────┐ ┌────────┐ ┌─► │ fee receiver │
/// │ user │ ════ peggedRedeemed ════▶ │ minter │ ───── fee ────┘ └──────────────┘
/// │ │ ◄── collateralReturned ── │ │ ◄── discount ─┐ ┌──────────────┐
/// └──────┘ (including any discount) └────────┘ └── │ reserve pool │
/// │ └──────────────┘
/// collateral held -= collateral value of peggedRedeemed - fee
///
/// @param peggedIn The amount of pegged token to be redeemed.
/// @return incentiveRatio the effective incentive ratio for `peggedIn` pegged tokens. A positive number is a fee
/// ratio; a negative number indicates a discount. This is the theoretic value.
/// @return fee The amount deducted in wrapped collateral from 'peggedIn' as a fee.
/// @return discount The amount in wrapped collateral added to 'collateralReturned' taken from the reserve pool.
/// This takes into account the possibility the reserve pool may be exhausted by this action.
/// @return peggedRedeemed The amount of pegged tokens that would be redeemed.
/// @return wrappedCollateralReturned The amount of collateral returned to the caller including from the reserve pool (if a discount has been configured)
/// @return price is the price of collateral in terms of pegged tokens used in the calculations.
/// @return rate The conversion rate from underlying collateral to wrapped collateral.
function redeemPeggedTokenDryRun(
uint256 peggedIn
)
external
view
returns (
int256 incentiveRatio,
uint256 fee,
uint256 discount,
uint256 peggedRedeemed,
uint256 wrappedCollateralReturned,
uint256 price,
uint256 rate
);
/// @notice Returns values that will be used if an actual `mintLeveragedToken` function call is made.
/// @param collateralIn The amount of collateral to be exchanged for leveraged tokens.
/// @return incentiveRatio the effective incentive ratio for `collateralIn` collateral tokens. A positive number is
/// a fee ratio; a negative number indicates a discount.
/// @return fee The amount deducted from 'collateralIn' as a fee.
/// @return discount The amount in wrapped collateral added to 'leverageMinted' taken from the reserve pool.
/// This takes into account the possibility the reserve pool may be exhausted by this action.
/// @return collateralUsed The amount of collateral used in the exchange.
/// @return leveragedMinted The amount of leveraged tokens that would be minted. This takes into account the discount applied.
function mintLeveragedTokenDryRun(
uint256 collateralIn
)
external
view
returns (
int256 incentiveRatio,
uint256 fee,
uint256 discount,
uint256 collateralUsed,
uint256 leveragedMinted,
uint256 price,
uint256 rate
);
/// @notice Returns values that will be used if an actual `redeemLeveragedToken` function call is made.
/// @param leveragedIn The amount of pegged token to be redeemed.
/// @return incentiveRatio the effective incentive ratio for `leveragedIn` pegged tokens. A positive number is a
/// fee ratio; a negative number indicates a discount.
/// @return fee The amount deducted from the returned collateral as a fee.
/// @return leveragedRedeemed The amount of leveraged tokens that would be redeemed.
/// This could be limited (some or all redeeming being disallowed) by configuration
/// @return collateralReturned The amount of collateral returned from the reserve pool and passed to the caller.
/// @return price is the price of collateral in terms of pegged tokens used in the calculations.
/// @return rate The conversion rate from underlying collateral to wrapped collateral.
function redeemLeveragedTokenDryRun(
uint256 leveragedIn
)
external
view
returns (
int256 incentiveRatio,
uint256 fee,
uint256 leveragedRedeemed,
uint256 collateralReturned,
uint256 price,
uint256 rate
);
/// @notice Returns value accrued, and thus harvestable, by holding wrapped collateral tokens as opposed to underlying
/// @return wrappedAmount the amount of wrapped collateral that can be distributed as rewards.
function harvestable() external view returns (uint256 wrappedAmount);
/*//////////////////////////////////////////////////////////////
PUBLIC UPDATE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Mint some pegged tokens in exchange for collateral tokens.
/// @param collateralIn The amount of wrapped value of collateral token supplied, use `uint256(-1)` to supply all
/// collateral token.
/// @param receiver The address of receiver for peggedToken.
/// @param minPeggedOut The minimum amount of peggedToken should be received. 0 means no check is made.
/// @return peggedOut The amount of peggedToken should be received.
function mintPeggedToken(
uint256 collateralIn,
address receiver,
uint256 minPeggedOut
) external returns (uint256 peggedOut);
/// @notice Redeem some pegged tokens for collateral tokens.
/// @param peggedIn the amount of peggedToken to redeem, use `uint256(-1)` to redeem all peggedToken.
/// @param receiver The address of receiver for collateral token.
/// @param minCollateralOut The minimum amount of wrapped value of collateral token should be received. 0 means no
/// check is made.
/// @return collateralOut The amount of wrapped value of collateral token should be received.
function redeemPeggedToken(
uint256 peggedIn,
address receiver,
uint256 minCollateralOut
) external returns (uint256 collateralOut);
/// @notice Mint some leveraged tokens in exchange for collateral tokens.
/// @param collateralIn The amount of wrapped value of collateral token supplied, use `uint256(-1)` to supply all
/// collateral token.
/// @param receiver The address of receiver for leveragedToken.
/// @param minLeveragedOut The minimum amount of leveragedToken should be received. 0 means no check is made.
/// @return leveragedOut The amount of leveragedToken should be received.
function mintLeveragedToken(
uint256 collateralIn,
address receiver,
uint256 minLeveragedOut
) external returns (uint256 leveragedOut);
/// @notice Redeem some leveraged tokens for collateral tokens.
/// @param leveragedIn the amount of leveragedToken to redeem, use `uint256(-1)` to redeem all leveragedToken.
/// @param receiver The address of receiver for collateral token.
/// @param minCollateralOut The minimum amount of wrapped value of collateral token should be received. 0 means no
/// check is made.
/// @return collateralOut The amount of wrapped value of collateral token should be received.
function redeemLeveragedToken(
uint256 leveragedIn,
address receiver,
uint256 minCollateralOut
) external returns (uint256 collateralOut);
/*//////////////////////////////////////////////////////////////
PROTECTED UPDATE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Resets the underlying collateral count to equal the value of the held wrapped collateral
/// This is anticipation of a slashing event for the wrapped collateral which could
/// leave the whole system with overvalued collateral which would prevent a rebalancing
function reset() external;
/// @notice Updates the config to the given config
/// @param config_ The new config
function updateConfig(Config calldata config_) external;
/// @notice Updates the fee receiver to the given address
/// @param feeReceiver_ The new fee receiver
function updateFeeReceiver(address feeReceiver_) external;
/// @notice Updates the reserve pool to the given address
/// @param reservePool_ The new reserve pool
function updateReservePool(address reservePool_) external;
/// @notice Updates the price oracle to the given address
/// @param priceOracle_ The new price oracle
function updatePriceOracle(address priceOracle_) external;
/// @notice Mint some pegged tokens in exchange for collateral tokens.
/// @param collateralIn The amount of wrapped value of collateral token supplied, use `uint256(-1)` to supply all
/// collateral token.
/// @param receiver The address of receiver for peggedToken.
/// @return peggedOut The amount of pegged tokens received.
function freeMintPeggedToken(uint256 collateralIn, address receiver) external returns (uint256 peggedOut);
/// @notice Redeem some pegged tokens for collateral tokens and leveraged tokens.
/// @param peggedForCollateral the amount of peggedToken to redeem for collateral.
/// @param peggedForLeveraged the amount of peggedToken to redeem for leveraged tokens.
/// @param receiver The address of receiver for collateral token.
/// @return wrappedCollateralOut The amount of collateral tokens received.
/// @return leveragedOut The amount of leveraged tokens received.
function freeRedeemPeggedToken(
uint256 peggedForCollateral,
uint256 peggedForLeveraged,
address receiver
) external returns (uint256 wrappedCollateralOut, uint256 leveragedOut);
/// @notice Mint some leveraged tokens in exchange for collateral tokens.
/// @param collateralIn The amount of wrapped value of collateral token supplied, use `uint256(-1)` to supply all
/// collateral token.
/// @param receiver The address of receiver for leveraged Tokens.
/// @return leveragedOut The amount of leveraged tokens received.
function freeMintLeveragedToken(uint256 collateralIn, address receiver) external returns (uint256 leveragedOut);
/// @notice Redeem some leveraged tokens for collateral tokens.
/// @param leveragedIn the amount of leveragedToken to redeem, use `uint256(-1)` to redeem all leveragedToken.
/// @param receiver The address of receiver for collateral token.
/// @return collateralOut The amount of collateral tokens received.
function freeRedeemLeveragedToken(uint256 leveragedIn, address receiver) external returns (uint256 collateralOut);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) 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
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "@openzeppelin/contracts/utils/TransientSlot.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransientUpgradeable is Initializable {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @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 __ReentrancyGuardTransient_init() internal onlyInitializing {
}
function __ReentrancyGuardTransient_init_unchained() internal onlyInitializing {
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @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 REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
/// @title Bao Check Owner
/// @dev Note:
/// provides a modifier that throws if the caller is not the owner
/// @author rootminus0x1 taken from Solady's Ownable contract (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
/// @dev Uses erc7201 storage
abstract contract BaoCheckOwner {
/*//////////////////////////////////////////////////////////////////////////
INTERNAL DATA
//////////////////////////////////////////////////////////////////////////*/
/// @dev The owner slot is given by:
/// `keccak256(abi.encode(uint256(keccak256("bao.storage.BaoOwnable.owner")) - 1)) & ~bytes32(uint256(0xff))`.
/// The choice of manual storage layout is to enable compatibility with both regular and upgradeable contracts.
bytes32 internal constant _INITIALIZED_SLOT = 0x61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a60500;
/*//////////////////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_INITIALIZED_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/*//////////////////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
interface ITokenHolder {
/*//////////////////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////////////////*/
/// @notice emits when a token has been swept, via the sweep function
/// @param token the token being swept
/// @param amount amount of given token swept
/// @param to address the tokens have been transferred to
event Swept(address token, uint256 amount, address to);
/*//////////////////////////////////////////////////////////////////////////
PUBLIC UPDATE FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice transfers tokens owned by this contract to `receiver`
/// @param token the token being swept
/// @param amount amount of given token swept
/// @param receiver address the tokens have been transferred to
function sweep(address token, uint256 amount, address receiver) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(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 towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* 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²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
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²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_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.
uint256 twos = denominator & (0 - denominator);
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²⁵⁶ / 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²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
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⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// 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²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, 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;
}
}
/**
* @dev 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) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* 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;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
interface IMultipleRewardAccumulator {
/**********
* Events *
**********/
/// @notice Emitted when user claim pending rewards.
/// @param account The address of user.
/// @param token The address of token claimed.
/// @param receiver The address of token receiver.
/// @param amount The amount of token claimed.
event Claim(address indexed account, address indexed token, address indexed receiver, uint256 amount);
/// @notice Emitted when the reward receiver is updated.
/// @param account The address of the account.
/// @param oldReceiver The address of the previous reward receiver.
/// @param newReceiver The address of the current reward receiver.
event UpdateRewardReceiver(address indexed account, address indexed oldReceiver, address indexed newReceiver);
/**********
* Errors *
**********/
/// @dev Thrown when caller claim others reward to another user.
error ClaimOthersRewardToAnother();
/*************************
* Public View Functions *
*************************/
/// @notice The address of default reward receiver for given user.
/// @param account The address of user to query.
function rewardReceiver(address account) external view returns (address);
/// @notice Get the amount of pending rewards.
/// @param account The address of user to query.
/// @param token The address of reward token to query.
/// @return amount The amount of pending rewards.
function claimable(address account, address token) external view returns (uint256 amount);
/// @notice Get the total amount of rewards claimed from this contract.
/// @param account The address of user to query.
/// @param token The address of reward token to query.
/// @return amount The amount of claimed rewards.
function claimed(address account, address token) external view returns (uint256 amount);
/****************************
* Public Mutator Functions *
****************************/
/// @notice Set the default reward receiver for the caller.
/// @dev When set to address(0), rewards are sent to the caller.
/// @param _newReceiver The new receiver address for any rewards claimed via `claim`.
function setRewardReceiver(address _newReceiver) external;
/// @notice Update the global and user snapshot.
/// @param account The address of user to update.
function checkpoint(address account) external;
/// @notice Claim pending rewards of all active tokens for the caller.
function claim() external;
/// @notice Claim pending rewards of all active tokens for some user.
/// @param account The address of the user.
function claim(address account) external;
/// @notice Claim pending rewards of all active tokens for the user and transfer to others.
/// @param account The address of the user.
/// @param receiver The address of the recipient.
function claim(address account, address receiver) external;
/// @notice Claim pending rewards of historical reward tokens for the caller.
/// @param tokens The address list of historical reward tokens to claim.
function claimHistorical(address[] memory tokens) external;
/// @notice Claim pending rewards of historical reward tokens for some user.
/// @param account The address of the user.
/// @param tokens The address list of historical reward tokens to claim.
function claimHistorical(address account, address[] memory tokens) external;
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ContextUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {BaoOwnableRoles} from "@bao/BaoOwnableRoles.sol";
import {IMultipleRewardDistributor} from "src/interfaces/IMultipleRewardDistributor.sol";
import {LinearReward} from "./LinearReward.sol";
// solhint-disable no-empty-blocks
// solhint-disable not-rely-on-time
/// @title Linear Multiple Reward Distributor
/// @dev A base contract for distributing multiple reward tokens linearly over time.
///
/// This contract manages the registration, tracking, and linear distribution of
/// multiple reward tokens. It maintains a list of active and historical reward tokens,
/// associates distributors using roles based access, and calculates distribution rates
/// over defined time periods.
///
/// Key features:
/// - Register and unregister reward tokens
/// - Configure linear reward distribution with customizable period lengths
/// - Track pending and distributed rewards
/// - Manage active and historical reward tokens
///
/// The contract uses a role-based access control system to manage distributors
/// and supports immediate or time-based reward distribution depending on the
/// configured period length.
abstract contract LinearMultipleRewardDistributor is
Initializable,
ContextUpgradeable,
BaoOwnableRoles,
IMultipleRewardDistributor
{
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
using LinearReward for LinearReward.RewardData;
/*************
* Constants *
*************/
/// @notice The role used to manage rewards.
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint256 public immutable REWARD_MANAGER_ROLE;
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint256 public immutable REWARD_DEPOSITOR_ROLE;
/// @notice The length of reward period in seconds.
/// @dev If the value is zero, the reward will be distributed immediately.
/// @dev It is either zero or at least 1 day (which is 86400).
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
uint40 public immutable REWARD_PERIOD_LENGTH;
/*************
* Variables *
*************/
struct LinearMultipleRewardDistributorStorage {
/// @notice Mapping from reward token address to linear distribution reward data.
mapping(address => LinearReward.RewardData) rewardData;
/// @dev The list of active reward tokens.
EnumerableSet.AddressSet activeRewardTokens;
/// @dev The list of historical reward tokens.
EnumerableSet.AddressSet historicalRewardTokens;
}
// chisel eval 'keccak256(abi.encode(uint256(keccak256("bao.storage.LinearMultipleRewardDistributor")) - 1)) & ~bytes32(uint256(0xff))'
bytes32 private constant _LINEARMULTIPLEREWARDDISTRIBUTOR_STORAGE =
0xe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d300;
function _getLinearMultipleRewardDistributorStorage()
private
pure
returns (LinearMultipleRewardDistributorStorage storage $)
{
// solhint-disable-next-line no-inline-assembly
assembly {
$.slot := _LINEARMULTIPLEREWARDDISTRIBUTOR_STORAGE
}
}
/***************
* Constructor *
***************/
/// @dev there is no need for an initializer
/// @dev abstract classes should not define role numbers, so pass them in
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(uint256 rewardManagerRole, uint256 rewardDepositorRole, uint40 periodLength_) {
REWARD_MANAGER_ROLE = rewardManagerRole;
if (periodLength_ != 0 && (periodLength_ < 1 days || periodLength_ > 28 days)) {
revert InvalidPeriodLength(periodLength_);
}
REWARD_PERIOD_LENGTH = periodLength_;
REWARD_DEPOSITOR_ROLE = rewardDepositorRole;
}
/*************************
* Public View Functions *
*************************/
/// @inheritdoc IMultipleRewardDistributor
function rewardData(
address token
) external view returns (uint256 lastUpdate, uint256 finishAt, uint256 rate, uint256 queued) {
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
LinearReward.RewardData memory data = $.rewardData[token];
return (data.lastUpdate, data.finishAt, data.rate, data.queued);
}
/// @inheritdoc IMultipleRewardDistributor
// slither-disable-next-line shadowing-local // this isn't shadowing, it's implementing an interface
function activeRewardTokens() public view override returns (address[] memory rewardTokens) {
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
rewardTokens = $.activeRewardTokens.values();
}
/// @inheritdoc IMultipleRewardDistributor
function isActiveRewardToken(address token) public view returns (bool isActive) {
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
isActive = $.activeRewardTokens.contains(token);
}
/// @inheritdoc IMultipleRewardDistributor
function historicalRewardTokens() public view override returns (address[] memory rewardTokens) {
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
rewardTokens = $.historicalRewardTokens.values();
}
/// @inheritdoc IMultipleRewardDistributor
function pendingRewards(
address token
) external view override returns (uint256 distributable, uint256 undistributed) {
(distributable, undistributed) = _pendingRewards(token);
}
/****************************
* Public Mutator Functions *
****************************/
/// @inheritdoc IMultipleRewardDistributor
function depositReward(address token, uint256 amount) external override onlyOwnerOrRoles(REWARD_DEPOSITOR_ROLE) {
address _distributor = _msgSender();
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
if (!$.activeRewardTokens.contains(token)) {
revert NotActiveRewardToken();
}
if (amount > 0) {
IERC20(token).safeTransferFrom(_distributor, address(this), amount);
}
_distributePendingReward();
_notifyReward(token, amount);
emit DepositReward(token, amount);
}
/************************
* Restricted Functions *
************************/
/// @inheritdoc IMultipleRewardDistributor
function registerRewardToken(address token) external onlyOwnerOrRoles(REWARD_MANAGER_ROLE) {
if (token == address(0)) {
revert RewardTokenIsZero();
}
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
if (!$.activeRewardTokens.add(token)) {
revert DuplicatedRewardToken(); // if value was not added then it already exists
}
// slither-disable-next-line unused-return we don't care if the the token was already in the set
$.historicalRewardTokens.remove(token); // wake-disable-line unchecked-return-value
emit RegisterRewardToken(token);
}
/// @inheritdoc IMultipleRewardDistributor
function unregisterRewardToken(address token) external onlyOwnerOrRoles(REWARD_MANAGER_ROLE) {
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
if (!$.activeRewardTokens.remove(token)) {
revert NotActiveRewardToken();
}
LinearReward.RewardData memory _data = $.rewardData[token];
unchecked {
(uint256 _distributable, uint256 _undistributed) = _data.pending();
if (_data.queued < REWARD_PERIOD_LENGTH) {
_data.queued = 0; // ignore round error
}
if (_data.queued + _distributable + _undistributed > 0) {
revert RewardDistributionNotFinished();
}
}
// slither-disable-next-line unused-return we don't care if the the token was already in the set
$.historicalRewardTokens.add(token); // wake-disable-line unchecked-return-value
emit UnregisterRewardToken(token);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to notify new rewards.
///
/// @param token The address of token.
/// @param amount The amount of new rewards.
function _notifyReward(address token, uint256 amount) internal {
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
if (REWARD_PERIOD_LENGTH == 0) {
_accumulateReward(token, amount);
} else {
LinearReward.RewardData memory data = $.rewardData[token];
data.increase(REWARD_PERIOD_LENGTH, amount);
$.rewardData[token] = data;
}
}
/// @dev Internal function to distribute all pending reward tokens.
function _distributePendingReward() internal {
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
// If the reward period length is zero, we distribute rewards immediately.
// If there are no active reward tokens, we do nothing.
if (REWARD_PERIOD_LENGTH == 0 || $.activeRewardTokens.length() == 0) {
return;
}
address[] memory activeRewardTokens_ = $.activeRewardTokens.values();
for (uint256 i = 0; i < activeRewardTokens_.length; i++) {
address token = activeRewardTokens_[i];
// slither-disable-next-line unused-return
(uint256 pending, ) = $.rewardData[token].pending();
$.rewardData[token].lastUpdate = uint40(block.timestamp);
if (pending > 0) {
_accumulateReward(token, pending);
}
}
}
function _getRewardData(address token) internal view returns (LinearReward.RewardData storage) {
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
return $.rewardData[token];
}
/// @dev Internal function to accumulate distributed rewards.
/// @dev derived contracts should implement this
/// @param token The address of token.
/// @param amount The amount of rewards to accumulate.
function _accumulateReward(address token, uint256 amount) internal virtual;
function _pendingRewards(address token) internal view returns (uint256 distributable, uint256 undistributed) {
LinearMultipleRewardDistributorStorage storage $ = _getLinearMultipleRewardDistributorStorage();
(distributable, undistributed) = $.rewardData[token].pending();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @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 ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 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) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
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) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
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) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool 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.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @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
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
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
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
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
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
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
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
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
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
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
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
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
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
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
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
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
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
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
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
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
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
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
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
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
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
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
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
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
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
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
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
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
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
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
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
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
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
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
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
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
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
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
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
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
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
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
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
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
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
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
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
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
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
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
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
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
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
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
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
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
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @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
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @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
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @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
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @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
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @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
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @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
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @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
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @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
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @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
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @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
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @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
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @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
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @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
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @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
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @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
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @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
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @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
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @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
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @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
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @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
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @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
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @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
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @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
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @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
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @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
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
import {BaoOwnable} from "@bao/BaoOwnable.sol";
import {BaoRoles} from "@bao/internal/BaoRoles.sol";
/// @title Bao Ownable Roles
/// see BaoOwnable and BaoRoles for more information
abstract contract BaoOwnableRoles is BaoOwnable, BaoRoles {
function supportsInterface(bytes4 interfaceId) public view virtual override(BaoOwnable, BaoRoles) returns (bool) {
return BaoOwnable.supportsInterface(interfaceId) || BaoRoles.supportsInterface(interfaceId);
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
interface IMultipleRewardDistributor {
/**********
* Events *
**********/
/// @notice Emitted when new reward token is registered.
/// distributors are those who hold the REWARD_DEPOSITOR_ROLE
/// @param token The address of reward token.
event RegisterRewardToken(address indexed token);
/// @notice Emitted when a reward token is unregistered.
///
/// @param token The address of reward token.
event UnregisterRewardToken(address indexed token);
/// @notice Emitted when a reward token is deposited.
///
/// @param token The address of reward token.
/// @param amount The amount of reward token deposited.
event DepositReward(address indexed token, uint256 amount);
/**********
* Errors *
**********/
/// @dev Thrown when caller access an unactive reward token.
error NotActiveRewardToken();
/// @dev Thrown when the address of reward distributor is `address(0)`.
error RewardDistributorIsZero();
/// @dev Thrown when the address of reward token is `address(0)`.
error RewardTokenIsZero();
/// @dev Thrown when caller is not reward distributor.
error NotRewardDistributor();
/// @dev Thrown when caller try to register an existing reward token.
error DuplicatedRewardToken();
/// @dev Thrown when caller try to unregister a reward with pending rewards.
error RewardDistributionNotFinished();
/// @dev Thrown when period length is non-zero and outside the range 1 day to 28 day (inclusive).
error InvalidPeriodLength(uint40 periodLength);
/*************************
* Public View Functions *
*************************/
/// @notice The length of reward period in seconds.
/// @dev If the value is zero, the reward will be distributed immediately.
/// @dev It is either zero or at least 1 day (which is 86400).
function REWARD_PERIOD_LENGTH() external view returns (uint40); // solhint-disable-line func-name-mixedcase
function REWARD_MANAGER_ROLE() external view returns (uint256 role); // solhint-disable-line func-name-mixedcase
function REWARD_DEPOSITOR_ROLE() external view returns (uint256 role); // solhint-disable-line func-name-mixedcase
/// @notice Return the list of active reward tokens.
function activeRewardTokens() external view returns (address[] memory);
/// @notice Check if a reward token is active.
function isActiveRewardToken(address token) external view returns (bool isActive);
/// @notice Return the list of historical reward tokens.
function historicalRewardTokens() external view returns (address[] memory);
function rewardData(
address token
) external view returns (uint256 lastUpdate, uint256 finishAt, uint256 rate, uint256 queued);
/// @notice Return the amount of pending distributed rewards in current period.
///
/// @param token The address of reward token.
/// @return distributable The amount of reward token can be distributed in current period.
/// @return undistributed The amount of reward token still locked in current period.
function pendingRewards(address token) external view returns (uint256 distributable, uint256 undistributed);
/****************************
* Public Mutator Functions *
****************************/
/// @notice Register a new reward token.
/// @dev Make sure no fee on transfer token is added as reward token.
/// @param token The address of reward token.
function registerRewardToken(address token) external;
/// @notice Unregister an existing reward token.
/// @param token The address of reward token.
function unregisterRewardToken(address token) external;
/// @notice Deposit new rewards to this contract.
/// @param token The address of reward token.
/// @param amount The amount of new rewards.
function depositReward(address token, uint256 amount) external;
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
// solhint-disable not-rely-on-time
library LinearReward {
using SafeCast for uint256;
/// @dev Compiler will pack this into single `uint256`.
/// Usually, we assume the amount of rewards won't exceed `uint96.max`.
/// In such case, the rate won't exceed `uint80.max`, since `periodLength` is at least `86400`.
/// Also `uint40.max` is enough for timestamp, which is about 30000 years.
struct RewardData {
// The amount of rewards pending to distribute.
uint96 queued;
// The current reward rate per second.
uint80 rate;
// The last timestamp when the reward is distributed.
uint40 lastUpdate;
// The timestamp when this period will finish.
uint40 finishAt;
}
/// @dev Add new rewards to current one. It is possible that the rewards will not distribute immediately.
/// The rewards will be only distributed when current period is end or the current increase or
/// decrease no more than 10%.
///
/// @param _data The struct of reward data, will be modified inplace.
/// @param _periodLength The length of a period, caller should make sure it is at least `86400`.
/// @param _amount The amount of new rewards to distribute.
function increase(RewardData memory _data, uint256 _periodLength, uint256 _amount) internal view {
_amount = _amount + _data.queued;
_data.queued = 0;
// slither-disable-next-line timestamp
if (block.timestamp >= _data.finishAt) {
// period finished, distribute to next period
_data.rate = (_amount / _periodLength).toUint80();
_data.queued = uint96(_amount - (_data.rate * _periodLength)); // keep rounding error
_data.lastUpdate = uint40(block.timestamp);
_data.finishAt = uint40(block.timestamp + _periodLength);
} else {
// If the new rewards (including queued) are at least 90% of what has already been distributed, then
// start a new period and recalculate the rate. Otherwise, add the new rewards to the queue.
uint256 _elapsed = block.timestamp - (_data.finishAt - _periodLength);
uint256 _distributed = uint256(_data.rate) * _elapsed;
if (_distributed * 9 <= _amount * 10) {
// APR increase, or drop no more than 10%, distribute
_amount = _amount + uint256(_data.rate) * (_data.finishAt - _data.lastUpdate);
_data.rate = (_amount / _periodLength).toUint80();
_data.queued = uint96(_amount - (_data.rate * _periodLength)); // keep rounding error
_data.finishAt = uint40(block.timestamp + _periodLength);
_data.lastUpdate = uint40(block.timestamp);
} else {
// APR decrease or drop more than 10%, wait for more rewards
_data.queued = _amount.toUint96();
}
}
}
/// @dev Return the amount of pending distributed rewards in current period.
///
/// @param _data The struct of reward data.
function pending(RewardData memory _data) internal view returns (uint256, uint256) {
uint256 _elapsed;
uint256 _left = 0;
// slither-disable-next-line timestamp
if (block.timestamp > _data.finishAt) {
// finishAt >= lastUpdate will happen, if `_notifyReward` is not called during current period.
_elapsed = _data.finishAt >= _data.lastUpdate ? _data.finishAt - _data.lastUpdate : 0;
} else {
unchecked {
_elapsed = block.timestamp - _data.lastUpdate;
_left = uint256(_data.finishAt) - block.timestamp;
}
}
return (uint256(_data.rate) * _elapsed, uint256(_data.rate) * _left);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* 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[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {BaoCheckOwner} from "@bao/internal/BaoCheckOwner.sol";
import {ERC165} from "@bao/ERC165.sol";
import {IBaoOwnable} from "@bao/interfaces/IBaoOwnable.sol";
/// @title Bao Ownable
/// @dev Note:
/// This implementation auto-initialises the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer of the deriving contract.
/// This initialization sets the owner to `msg.sender`, not to the passed 'finalOwner' parameter.
/// The contract deployer can now act as owner then 'transferOwnership' once complete.
///
/// This contract follows [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// however the transferOwnership function can only be called once and then, only by the caller that calls
/// initializeOwner, and then only within 1 hour
///
/// Multiple initialisations are not allowed, to ensure this we make a separate check for a previously set owner including
/// including to address(0). This ensure that the initializeOwner, an otherwise unprotected function, cannot be called twice.
///
/// it also adds IRC165 interface query support
/// @author rootminus0x1
/// @dev Uses erc7201 storage
abstract contract BaoOwnable is IBaoOwnable, BaoCheckOwner, ERC165 {
/*//////////////////////////////////////////////////////////////////////////
CONSTRUCTOR/INITIALIZER
//////////////////////////////////////////////////////////////////////////*/
/// @notice Initialises the ownership
/// This is an unprotected function designed to let a derive contract's initializer to call it
/// This function can only be called once.
/// The caller of the initializer function will be the deployer of the contract. The deployer (msg.sender)
/// becomes the owner, allowing them to do owner-type set up, then ownership is transferred to the 'finalOwner'
/// when 'transferOwnership' is called. 'transferOwnership' must be called within an hour.
/// @param finalOwner sets the owner, a privileged address, of the contract to be set when 'transferOwnership' is called
// slither-disable-next-line dead-code
function _initializeOwner(address finalOwner) internal virtual {
unchecked {
_checkNotInitialized();
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
sstore(_PENDING_SLOT, or(finalOwner, shl(192, add(timestamp(), 3600))))
}
_setOwner(address(0), msg.sender);
}
}
/*//////////////////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IBaoOwnable).interfaceId || super.supportsInterface(interfaceId);
}
/// @inheritdoc IBaoOwnable
function owner() public view virtual returns (address owner_) {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
owner_ := sload(_INITIALIZED_SLOT)
}
}
/*//////////////////////////////////////////////////////////////////////////
PROTECTED FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @inheritdoc IBaoOwnable
/// @dev Allows the owner to complete the ownership transfer to `pendingOwner`.
/// Reverts if there is no existing ownership transfer requested by `pendingOwner`.
function transferOwnership(address confirmOwner) public virtual {
unchecked {
address oldOwner;
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
oldOwner := sload(_INITIALIZED_SLOT)
if iszero(eq(caller(), oldOwner)) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
let pending_ := sload(_PENDING_SLOT)
if or(
// confirm == pending
iszero(eq(confirmOwner, shr(95, shl(95, pending_)))),
// within the timescale allowed
gt(timestamp(), shr(192, pending_))
) {
mstore(0x00, 0x8cd65fff) // `CannotCompleteTransfer()`.
revert(0x1c, 0x04)
}
sstore(_PENDING_SLOT, 0)
}
_setOwner(oldOwner, confirmOwner);
}
}
/*//////////////////////////////////////////////////////////////////////////
PRIVATE DATA
//////////////////////////////////////////////////////////////////////////*/
/// @dev The owner address storage slot is defined in BaoCheckOwner
/// We utilise an extra bit in that slot, to prevent re-initialisations (only needed for address(0))
uint8 internal constant _BIT_INITIALIZED = 255;
/// @dev The pending owner slot is given by:
/// `keccak256(abi.encode(uint256(keccak256("bao.storage.BaoOwnable.pending")) - 1)) & ~bytes32(uint256(0xff))`.
bytes32 internal constant _PENDING_SLOT = 0x9839bd1b7d13bef2e7a66ce106fd5e418f9f8fee5da4e55d26c2c33ef0bf4800;
// | 255, 64 bits - expiry | 191, 32 bits - spare | 159, 160 bits - pending owner address |
/// `keccak256(abi.encode(uint256(keccak256("bao.storage.BaoOwnable.isInitialized")) - 1)) & ~bytes32(uint256(0xff))`.
//bytes32 private constant _IS_INITIALIZED_SLOT = 0xf62b6656174671598fb5a8f20c699816e60e61b09b105786e842a4b16193e900;
/// @dev OR an address to get the address stored in owner, if they were also the deployer
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 internal constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/*//////////////////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Sets the owner directly
/// @param oldOwner, The old owner about to be replaced. This is a clean address (i.e. top bits are zero)
/// @param newOwner, The new owner about to replace `oldOwner`. This is not a clean address (i.e. top bits may not be zero)
function _setOwner(address oldOwner, address newOwner) internal {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// Emit the {OwnershipTransferred} event with cleaned addresses
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, oldOwner, newOwner)
// Store the new value. with initialised bit set, to prevent multiple initialisations
// i.e. an initialisation after a ownership transfer
sstore(_INITIALIZED_SLOT, or(newOwner, shl(_BIT_INITIALIZED, iszero(newOwner))))
}
}
// @dev performs a check to determine if the contract has been initialised (via '_initializeOwnership)
// Reverts if it has been initialised.
// slither-disable-next-line dead-code
function _checkNotInitialized() internal view {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// throw if we are already initialized
// this works even if it's initialised to zero because
// _setOwner sets the _BITINITIALIZED bit if the address is 0
if sload(_INITIALIZED_SLOT) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165} from "@bao/ERC165.sol";
import {IBaoRoles} from "@bao/interfaces/IBaoRoles.sol";
import {BaoCheckOwner} from "@bao/internal/BaoCheckOwner.sol";
/// @title Bao Ownable
/// @author rootminus0x1 a barefaced copy of Solady's OwnableRoles contract
/// (https://github.com/vectorized/solady/blob/main/src/auth/OwnableRoles.sol)
/// @notice It is a copy of Solady's 'OwnableRoles' with the necessary 'Ownable' part
/// moved into a base contract 'BaoCheckOwner'. We retain solady's sleek mechanism of
/// utilising the same seed slot for ownability and user roles.
/// This change allows it to be mixed in with the 'BaoOwnable' or 'BaoOwnableTransferrable'
/// contracts to create Roles enabled versions of those contracts
/// it also adds IRC165 interface query support
abstract contract BaoRoles is BaoCheckOwner, IBaoRoles, ERC165 {
/// @dev `keccak256(bytes("RolesUpdated(address,uint256)"))`.
uint256 private constant _ROLES_UPDATED_EVENT_SIGNATURE =
0x715ad5ce61fc9595c7b415289d59cf203f23a94fa06f04af7e489a0a76e1fe26;
uint256 private constant _ROLE_SLOT_SEED = 0x8b78c6d8;
/*//////////////////////////////////////////////////////////////////////////
PUBLIC VIEW FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Returns the roles of `user`.
function rolesOf(address user) public view virtual returns (uint256 roles) {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, user)
// Load the stored value.
roles := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Returns whether `user` has any of `roles`.
function hasAnyRole(address user, uint256 roles) public view virtual returns (bool) {
return rolesOf(user) & roles != 0;
}
/// @dev Returns whether `user` has all of `roles`.
function hasAllRoles(address user, uint256 roles) public view virtual returns (bool) {
return rolesOf(user) & roles == roles;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IBaoRoles).interfaceId || super.supportsInterface(interfaceId);
}
/*//////////////////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Allow the caller to remove their own roles.
/// If the caller does not have a role, then it will be an no-op for the role.
function renounceRoles(uint256 roles) public virtual {
_removeRoles(msg.sender, roles);
}
/*//////////////////////////////////////////////////////////////////////////
PROTECTED FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Allows the owner to grant `user` `roles`.
/// If the `user` already has a role, then it will be an no-op for the role.
function grantRoles(address user, uint256 roles) public virtual onlyOwner {
_grantRoles(user, roles);
}
/// @dev Allows the owner to remove `user` `roles`.
/// If the `user` does not have a role, then it will be an no-op for the role.
function revokeRoles(address user, uint256 roles) public virtual onlyOwner {
_removeRoles(user, roles);
}
/*//////////////////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Updates the roles directly without authorization guard.
/// If `on` is true, each set bit of `roles` will be turned on,
/// otherwise, each set bit of `roles` will be turned off.
function _updateRoles(address user, uint256 roles, bool on) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, user)
let roleSlot := keccak256(0x0c, 0x20)
// Load the current value.
let current := sload(roleSlot)
// Compute the updated roles if `on` is true.
let updated := or(current, roles)
// Compute the updated roles if `on` is false.
// Use `and` to compute the intersection of `current` and `roles`,
// `xor` it with `current` to flip the bits in the intersection.
if iszero(on) {
updated := xor(current, and(current, roles))
}
// Then, store the new value.
sstore(roleSlot, updated)
// Emit the {RolesUpdated} event.
log3(0, 0, _ROLES_UPDATED_EVENT_SIGNATURE, shr(96, mload(0x0c)), updated)
}
}
/// @dev Grants the roles directly without authorization guard.
/// Each bit of `roles` represents the role to turn on.
function _grantRoles(address user, uint256 roles) internal virtual {
_updateRoles(user, roles, true);
}
/// @dev Removes the roles directly without authorization guard.
/// Each bit of `roles` represents the role to turn off.
function _removeRoles(address user, uint256 roles) internal virtual {
_updateRoles(user, roles, false);
}
/// @dev Throws if the sender does not have any of the `roles`.
// slither-disable-next-line dead-code
function _checkRoles(uint256 roles) internal view virtual {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, caller())
// Load the stored value, and if the `and` intersection
// of the value and `roles` is zero, revert.
if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Throws if the sender is not the owner,
/// and does not have any of the `roles`.
/// Checks for ownership first, then lazily checks for roles.
// slither-disable-next-line dead-code
function _checkOwnerOrRoles(uint256 roles) internal view virtual {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// If the caller is not the stored owner.
// Note: `_ROLE_SLOT_SEED` is equal to `_OWNER_SLOT_NOT`.
if iszero(eq(caller(), sload(_INITIALIZED_SLOT))) {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, caller())
// Load the stored value, and if the `and` intersection
// of the value and `roles` is zero, revert.
if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Throws if the sender does not have any of the `roles`,
/// and is not the owner.
/// Checks for roles first, then lazily checks for ownership.
// slither-disable-next-line dead-code
function _checkRolesOrOwner(uint256 roles) internal view virtual {
// solhint-disable-next-line no-inline-assembly
assembly ("memory-safe") {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, caller())
// Load the stored value, and if the `and` intersection
// of the value and `roles` is zero, revert.
if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
// If the caller is not the stored owner.
// Note: `_ROLE_SLOT_SEED` is equal to `_OWNER_SLOT_NOT`.
if iszero(eq(caller(), sload(_INITIALIZED_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
}
/*//////////////////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Marks a function as only callable by an account with `roles`.
modifier onlyRoles(uint256 roles) virtual {
_checkRoles(roles);
_;
}
/// @dev Marks a function as only callable by the owner or by an account
/// with `roles`. Checks for ownership first, then lazily checks for roles.
modifier onlyOwnerOrRoles(uint256 roles) virtual {
_checkOwnerOrRoles(roles);
_;
}
/// @dev Marks a function as only callable by an account with `roles`
/// or the owner. Checks for roles first, then lazily checks for ownership.
modifier onlyRolesOrOwner(uint256 roles) virtual {
_checkRolesOrOwner(roles);
_;
}
/*//////////////////////////////////////////////////////////////////////////
ROLE CONSTANTS
//////////////////////////////////////////////////////////////////////////*/
// IYKYK
uint256 internal constant _ROLE_0 = 1 << 0;
uint256 internal constant _ROLE_1 = 1 << 1;
uint256 internal constant _ROLE_2 = 1 << 2;
uint256 internal constant _ROLE_3 = 1 << 3;
uint256 internal constant _ROLE_4 = 1 << 4;
uint256 internal constant _ROLE_5 = 1 << 5;
uint256 internal constant _ROLE_6 = 1 << 6;
uint256 internal constant _ROLE_7 = 1 << 7;
uint256 internal constant _ROLE_8 = 1 << 8;
uint256 internal constant _ROLE_9 = 1 << 9;
uint256 internal constant _ROLE_10 = 1 << 10;
uint256 internal constant _ROLE_11 = 1 << 11;
uint256 internal constant _ROLE_12 = 1 << 12;
uint256 internal constant _ROLE_13 = 1 << 13;
uint256 internal constant _ROLE_14 = 1 << 14;
uint256 internal constant _ROLE_15 = 1 << 15;
uint256 internal constant _ROLE_16 = 1 << 16;
uint256 internal constant _ROLE_17 = 1 << 17;
uint256 internal constant _ROLE_18 = 1 << 18;
uint256 internal constant _ROLE_19 = 1 << 19;
uint256 internal constant _ROLE_20 = 1 << 20;
uint256 internal constant _ROLE_21 = 1 << 21;
uint256 internal constant _ROLE_22 = 1 << 22;
uint256 internal constant _ROLE_23 = 1 << 23;
uint256 internal constant _ROLE_24 = 1 << 24;
uint256 internal constant _ROLE_25 = 1 << 25;
uint256 internal constant _ROLE_26 = 1 << 26;
uint256 internal constant _ROLE_27 = 1 << 27;
uint256 internal constant _ROLE_28 = 1 << 28;
uint256 internal constant _ROLE_29 = 1 << 29;
uint256 internal constant _ROLE_30 = 1 << 30;
uint256 internal constant _ROLE_31 = 1 << 31;
uint256 internal constant _ROLE_32 = 1 << 32;
uint256 internal constant _ROLE_33 = 1 << 33;
uint256 internal constant _ROLE_34 = 1 << 34;
uint256 internal constant _ROLE_35 = 1 << 35;
uint256 internal constant _ROLE_36 = 1 << 36;
uint256 internal constant _ROLE_37 = 1 << 37;
uint256 internal constant _ROLE_38 = 1 << 38;
uint256 internal constant _ROLE_39 = 1 << 39;
uint256 internal constant _ROLE_40 = 1 << 40;
uint256 internal constant _ROLE_41 = 1 << 41;
uint256 internal constant _ROLE_42 = 1 << 42;
uint256 internal constant _ROLE_43 = 1 << 43;
uint256 internal constant _ROLE_44 = 1 << 44;
uint256 internal constant _ROLE_45 = 1 << 45;
uint256 internal constant _ROLE_46 = 1 << 46;
uint256 internal constant _ROLE_47 = 1 << 47;
uint256 internal constant _ROLE_48 = 1 << 48;
uint256 internal constant _ROLE_49 = 1 << 49;
uint256 internal constant _ROLE_50 = 1 << 50;
uint256 internal constant _ROLE_51 = 1 << 51;
uint256 internal constant _ROLE_52 = 1 << 52;
uint256 internal constant _ROLE_53 = 1 << 53;
uint256 internal constant _ROLE_54 = 1 << 54;
uint256 internal constant _ROLE_55 = 1 << 55;
uint256 internal constant _ROLE_56 = 1 << 56;
uint256 internal constant _ROLE_57 = 1 << 57;
uint256 internal constant _ROLE_58 = 1 << 58;
uint256 internal constant _ROLE_59 = 1 << 59;
uint256 internal constant _ROLE_60 = 1 << 60;
uint256 internal constant _ROLE_61 = 1 << 61;
uint256 internal constant _ROLE_62 = 1 << 62;
uint256 internal constant _ROLE_63 = 1 << 63;
uint256 internal constant _ROLE_64 = 1 << 64;
uint256 internal constant _ROLE_65 = 1 << 65;
uint256 internal constant _ROLE_66 = 1 << 66;
uint256 internal constant _ROLE_67 = 1 << 67;
uint256 internal constant _ROLE_68 = 1 << 68;
uint256 internal constant _ROLE_69 = 1 << 69;
uint256 internal constant _ROLE_70 = 1 << 70;
uint256 internal constant _ROLE_71 = 1 << 71;
uint256 internal constant _ROLE_72 = 1 << 72;
uint256 internal constant _ROLE_73 = 1 << 73;
uint256 internal constant _ROLE_74 = 1 << 74;
uint256 internal constant _ROLE_75 = 1 << 75;
uint256 internal constant _ROLE_76 = 1 << 76;
uint256 internal constant _ROLE_77 = 1 << 77;
uint256 internal constant _ROLE_78 = 1 << 78;
uint256 internal constant _ROLE_79 = 1 << 79;
uint256 internal constant _ROLE_80 = 1 << 80;
uint256 internal constant _ROLE_81 = 1 << 81;
uint256 internal constant _ROLE_82 = 1 << 82;
uint256 internal constant _ROLE_83 = 1 << 83;
uint256 internal constant _ROLE_84 = 1 << 84;
uint256 internal constant _ROLE_85 = 1 << 85;
uint256 internal constant _ROLE_86 = 1 << 86;
uint256 internal constant _ROLE_87 = 1 << 87;
uint256 internal constant _ROLE_88 = 1 << 88;
uint256 internal constant _ROLE_89 = 1 << 89;
uint256 internal constant _ROLE_90 = 1 << 90;
uint256 internal constant _ROLE_91 = 1 << 91;
uint256 internal constant _ROLE_92 = 1 << 92;
uint256 internal constant _ROLE_93 = 1 << 93;
uint256 internal constant _ROLE_94 = 1 << 94;
uint256 internal constant _ROLE_95 = 1 << 95;
uint256 internal constant _ROLE_96 = 1 << 96;
uint256 internal constant _ROLE_97 = 1 << 97;
uint256 internal constant _ROLE_98 = 1 << 98;
uint256 internal constant _ROLE_99 = 1 << 99;
uint256 internal constant _ROLE_100 = 1 << 100;
uint256 internal constant _ROLE_101 = 1 << 101;
uint256 internal constant _ROLE_102 = 1 << 102;
uint256 internal constant _ROLE_103 = 1 << 103;
uint256 internal constant _ROLE_104 = 1 << 104;
uint256 internal constant _ROLE_105 = 1 << 105;
uint256 internal constant _ROLE_106 = 1 << 106;
uint256 internal constant _ROLE_107 = 1 << 107;
uint256 internal constant _ROLE_108 = 1 << 108;
uint256 internal constant _ROLE_109 = 1 << 109;
uint256 internal constant _ROLE_110 = 1 << 110;
uint256 internal constant _ROLE_111 = 1 << 111;
uint256 internal constant _ROLE_112 = 1 << 112;
uint256 internal constant _ROLE_113 = 1 << 113;
uint256 internal constant _ROLE_114 = 1 << 114;
uint256 internal constant _ROLE_115 = 1 << 115;
uint256 internal constant _ROLE_116 = 1 << 116;
uint256 internal constant _ROLE_117 = 1 << 117;
uint256 internal constant _ROLE_118 = 1 << 118;
uint256 internal constant _ROLE_119 = 1 << 119;
uint256 internal constant _ROLE_120 = 1 << 120;
uint256 internal constant _ROLE_121 = 1 << 121;
uint256 internal constant _ROLE_122 = 1 << 122;
uint256 internal constant _ROLE_123 = 1 << 123;
uint256 internal constant _ROLE_124 = 1 << 124;
uint256 internal constant _ROLE_125 = 1 << 125;
uint256 internal constant _ROLE_126 = 1 << 126;
uint256 internal constant _ROLE_127 = 1 << 127;
uint256 internal constant _ROLE_128 = 1 << 128;
uint256 internal constant _ROLE_129 = 1 << 129;
uint256 internal constant _ROLE_130 = 1 << 130;
uint256 internal constant _ROLE_131 = 1 << 131;
uint256 internal constant _ROLE_132 = 1 << 132;
uint256 internal constant _ROLE_133 = 1 << 133;
uint256 internal constant _ROLE_134 = 1 << 134;
uint256 internal constant _ROLE_135 = 1 << 135;
uint256 internal constant _ROLE_136 = 1 << 136;
uint256 internal constant _ROLE_137 = 1 << 137;
uint256 internal constant _ROLE_138 = 1 << 138;
uint256 internal constant _ROLE_139 = 1 << 139;
uint256 internal constant _ROLE_140 = 1 << 140;
uint256 internal constant _ROLE_141 = 1 << 141;
uint256 internal constant _ROLE_142 = 1 << 142;
uint256 internal constant _ROLE_143 = 1 << 143;
uint256 internal constant _ROLE_144 = 1 << 144;
uint256 internal constant _ROLE_145 = 1 << 145;
uint256 internal constant _ROLE_146 = 1 << 146;
uint256 internal constant _ROLE_147 = 1 << 147;
uint256 internal constant _ROLE_148 = 1 << 148;
uint256 internal constant _ROLE_149 = 1 << 149;
uint256 internal constant _ROLE_150 = 1 << 150;
uint256 internal constant _ROLE_151 = 1 << 151;
uint256 internal constant _ROLE_152 = 1 << 152;
uint256 internal constant _ROLE_153 = 1 << 153;
uint256 internal constant _ROLE_154 = 1 << 154;
uint256 internal constant _ROLE_155 = 1 << 155;
uint256 internal constant _ROLE_156 = 1 << 156;
uint256 internal constant _ROLE_157 = 1 << 157;
uint256 internal constant _ROLE_158 = 1 << 158;
uint256 internal constant _ROLE_159 = 1 << 159;
uint256 internal constant _ROLE_160 = 1 << 160;
uint256 internal constant _ROLE_161 = 1 << 161;
uint256 internal constant _ROLE_162 = 1 << 162;
uint256 internal constant _ROLE_163 = 1 << 163;
uint256 internal constant _ROLE_164 = 1 << 164;
uint256 internal constant _ROLE_165 = 1 << 165;
uint256 internal constant _ROLE_166 = 1 << 166;
uint256 internal constant _ROLE_167 = 1 << 167;
uint256 internal constant _ROLE_168 = 1 << 168;
uint256 internal constant _ROLE_169 = 1 << 169;
uint256 internal constant _ROLE_170 = 1 << 170;
uint256 internal constant _ROLE_171 = 1 << 171;
uint256 internal constant _ROLE_172 = 1 << 172;
uint256 internal constant _ROLE_173 = 1 << 173;
uint256 internal constant _ROLE_174 = 1 << 174;
uint256 internal constant _ROLE_175 = 1 << 175;
uint256 internal constant _ROLE_176 = 1 << 176;
uint256 internal constant _ROLE_177 = 1 << 177;
uint256 internal constant _ROLE_178 = 1 << 178;
uint256 internal constant _ROLE_179 = 1 << 179;
uint256 internal constant _ROLE_180 = 1 << 180;
uint256 internal constant _ROLE_181 = 1 << 181;
uint256 internal constant _ROLE_182 = 1 << 182;
uint256 internal constant _ROLE_183 = 1 << 183;
uint256 internal constant _ROLE_184 = 1 << 184;
uint256 internal constant _ROLE_185 = 1 << 185;
uint256 internal constant _ROLE_186 = 1 << 186;
uint256 internal constant _ROLE_187 = 1 << 187;
uint256 internal constant _ROLE_188 = 1 << 188;
uint256 internal constant _ROLE_189 = 1 << 189;
uint256 internal constant _ROLE_190 = 1 << 190;
uint256 internal constant _ROLE_191 = 1 << 191;
uint256 internal constant _ROLE_192 = 1 << 192;
uint256 internal constant _ROLE_193 = 1 << 193;
uint256 internal constant _ROLE_194 = 1 << 194;
uint256 internal constant _ROLE_195 = 1 << 195;
uint256 internal constant _ROLE_196 = 1 << 196;
uint256 internal constant _ROLE_197 = 1 << 197;
uint256 internal constant _ROLE_198 = 1 << 198;
uint256 internal constant _ROLE_199 = 1 << 199;
uint256 internal constant _ROLE_200 = 1 << 200;
uint256 internal constant _ROLE_201 = 1 << 201;
uint256 internal constant _ROLE_202 = 1 << 202;
uint256 internal constant _ROLE_203 = 1 << 203;
uint256 internal constant _ROLE_204 = 1 << 204;
uint256 internal constant _ROLE_205 = 1 << 205;
uint256 internal constant _ROLE_206 = 1 << 206;
uint256 internal constant _ROLE_207 = 1 << 207;
uint256 internal constant _ROLE_208 = 1 << 208;
uint256 internal constant _ROLE_209 = 1 << 209;
uint256 internal constant _ROLE_210 = 1 << 210;
uint256 internal constant _ROLE_211 = 1 << 211;
uint256 internal constant _ROLE_212 = 1 << 212;
uint256 internal constant _ROLE_213 = 1 << 213;
uint256 internal constant _ROLE_214 = 1 << 214;
uint256 internal constant _ROLE_215 = 1 << 215;
uint256 internal constant _ROLE_216 = 1 << 216;
uint256 internal constant _ROLE_217 = 1 << 217;
uint256 internal constant _ROLE_218 = 1 << 218;
uint256 internal constant _ROLE_219 = 1 << 219;
uint256 internal constant _ROLE_220 = 1 << 220;
uint256 internal constant _ROLE_221 = 1 << 221;
uint256 internal constant _ROLE_222 = 1 << 222;
uint256 internal constant _ROLE_223 = 1 << 223;
uint256 internal constant _ROLE_224 = 1 << 224;
uint256 internal constant _ROLE_225 = 1 << 225;
uint256 internal constant _ROLE_226 = 1 << 226;
uint256 internal constant _ROLE_227 = 1 << 227;
uint256 internal constant _ROLE_228 = 1 << 228;
uint256 internal constant _ROLE_229 = 1 << 229;
uint256 internal constant _ROLE_230 = 1 << 230;
uint256 internal constant _ROLE_231 = 1 << 231;
uint256 internal constant _ROLE_232 = 1 << 232;
uint256 internal constant _ROLE_233 = 1 << 233;
uint256 internal constant _ROLE_234 = 1 << 234;
uint256 internal constant _ROLE_235 = 1 << 235;
uint256 internal constant _ROLE_236 = 1 << 236;
uint256 internal constant _ROLE_237 = 1 << 237;
uint256 internal constant _ROLE_238 = 1 << 238;
uint256 internal constant _ROLE_239 = 1 << 239;
uint256 internal constant _ROLE_240 = 1 << 240;
uint256 internal constant _ROLE_241 = 1 << 241;
uint256 internal constant _ROLE_242 = 1 << 242;
uint256 internal constant _ROLE_243 = 1 << 243;
uint256 internal constant _ROLE_244 = 1 << 244;
uint256 internal constant _ROLE_245 = 1 << 245;
uint256 internal constant _ROLE_246 = 1 << 246;
uint256 internal constant _ROLE_247 = 1 << 247;
uint256 internal constant _ROLE_248 = 1 << 248;
uint256 internal constant _ROLE_249 = 1 << 249;
uint256 internal constant _ROLE_250 = 1 << 250;
uint256 internal constant _ROLE_251 = 1 << 251;
uint256 internal constant _ROLE_252 = 1 << 252;
uint256 internal constant _ROLE_253 = 1 << 253;
uint256 internal constant _ROLE_254 = 1 << 254;
uint256 internal constant _ROLE_255 = 1 << 255;
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 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);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/*//////////////////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
/// @notice Simple single owner authorization mixin based on Solady's Ownable
/// @author rootminus0x1 based on Solady's (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
/// It has ownership transfer support for deployer to final owner
/// No other ownership transfers are supported.
interface IBaoOwnable {
/*//////////////////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/// @dev Can only carry out actions within a window of time and if the new ower has validated.
error CannotCompleteTransfer();
/*//////////////////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////////////////*/
/// @dev The ownership is transferred from `previousOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/*//////////////////////////////////////////////////////////////////////////
PROTECTED UPDATE FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Set the address of the new owner of the contract
/// This is the final step in the 3-step-with-timeouts transfer approach
/// @dev Set confirmOwner to the zero address to renounce any ownership.
/// @param confirmOwner The address of the new owner of the contract.
function transferOwnership(address confirmOwner) external;
/*//////////////////////////////////////////////////////////////////////////
PUBLIC READ FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @notice Get the address of the owner
/// @return The address of the owner.
function owner() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28 <0.9.0;
/// @notice Simple single owner and multiroles authorization mixin.
/// @author rootminus0x1 a barefaced copy of Solady (https://github.com/vectorized/solady/blob/main/src/auth/OwnableRoles.sol)
/// Made into an interface and a implementation
interface IBaoRoles {
/*//////////////////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////////////////*/
/// @dev The `user`'s roles is updated to `roles`.
/// Each bit of `roles` represents whether the role is set.
event RolesUpdated(address indexed user, uint256 indexed roles);
/*//////////////////////////////////////////////////////////////////////////
PROTECTED UPDATE FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Allows the owner to grant `user` `roles`.
/// If the `user` already has a role, then it will be an no-op for the role.
function grantRoles(address user, uint256 roles) external;
/// @dev Allows the owner to remove `user` `roles`.
/// If the `user` does not have a role, then it will be an no-op for the role.
function revokeRoles(address user, uint256 roles) external;
/// @dev Allow the caller to remove their own roles.
/// If the caller does not have a role, then it will be an no-op for the role.
function renounceRoles(uint256 roles) external;
/*//////////////////////////////////////////////////////////////////////////
PUBLIC READ FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/
/// @dev Returns the roles of `user`.
function rolesOf(address user) external view returns (uint256 roles);
/// @dev Returns whether `user` has any of `roles`.
function hasAnyRole(address user, uint256 roles) external view returns (bool);
/// @dev Returns whether `user` has all of `roles`.
function hasAllRoles(address user, uint256 roles) external view returns (bool);
}{
"remappings": [
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
"@solady/=lib/solady/src/",
"@chainlink/contracts/=lib/chainlink-brownie-contracts/contracts/src/v0.8/",
"@bao/=lib/bao-base-audit-2025-07/src/",
"@bao-test/=lib/bao-base/test/",
"@bao-script/=lib/bao-base/script/",
"@bao-factory/=lib/bao-base/lib/bao-factory/src/",
"@bao-factory-test/=lib/bao-base/lib/bao-factory/test/",
"@harbor/=src/",
"@harbor-script/=script/",
"@harbor-test/=test/",
"src/=src/",
"test/=test/"
],
"optimizer": {
"enabled": true,
"runs": 700
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"minter_","type":"address"},{"internalType":"address","name":"liquidationToken_","type":"address"},{"internalType":"uint256","name":"earlyWithdrawalFee_","type":"uint256"},{"internalType":"address","name":"feeAddress_","type":"address"},{"internalType":"uint256","name":"withdrawalStartDelay_","type":"uint256"},{"internalType":"uint256","name":"withdrawalEndWindow_","type":"uint256"},{"internalType":"uint256","name":"minTotalAssetSupply","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"CannotCompleteTransfer","type":"error"},{"inputs":[],"name":"ClaimOthersRewardToAnother","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minAmount","type":"uint256"}],"name":"DepositAmountLessThanMinimum","type":"error"},{"inputs":[],"name":"DepositZeroAmount","type":"error"},{"inputs":[],"name":"DuplicatedRewardToken","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[{"internalType":"uint256","name":"fee","type":"uint256"}],"name":"InvalidFee","type":"error"},{"inputs":[{"internalType":"address","name":"feeAddress","type":"address"}],"name":"InvalidFeeAddress","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"InvalidLiquidationToken","type":"error"},{"inputs":[{"internalType":"uint40","name":"periodLength","type":"uint40"}],"name":"InvalidPeriodLength","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"InvalidReceiver","type":"error"},{"inputs":[{"internalType":"uint256","name":"startDelay","type":"uint256"},{"internalType":"uint256","name":"endWindow","type":"uint256"}],"name":"InvalidWithdrawalWindow","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"NoActiveWithdrawalRequest","type":"error"},{"inputs":[],"name":"NotActiveRewardToken","type":"error"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"NotContractAddress","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"NotERC20Token","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"NotRewardDistributor","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[],"name":"RewardDistributionNotFinished","type":"error"},{"inputs":[],"name":"RewardDistributorIsZero","type":"error"},{"inputs":[],"name":"RewardTokenIsZero","type":"error"},{"inputs":[{"internalType":"uint8","name":"bits","type":"uint8"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintDowncast","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"balance","type":"uint256"}],"name":"WithdrawAmountExceedsBalance","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minAmount","type":"uint256"}],"name":"WithdrawAmountLessThanMinimum","type":"error"},{"inputs":[],"name":"WithdrawZeroAmount","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"ZeroInputBalance","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Claim","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"DepositReward","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"EarlyWithdrawalFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newFee","type":"uint256"}],"name":"EarlyWithdrawalFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newFeeAddress","type":"address"}],"name":"FeeAddressUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"liquidatedToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"liquidatedAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"liquidatedToToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"liquidatedToAmount","type":"uint256"}],"name":"Liquidated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"}],"name":"RegisterRewardToken","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"rewardToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"rewardAmount","type":"uint256"}],"name":"RewardReceived","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"uint256","name":"roles","type":"uint256"}],"name":"RolesUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"address","name":"to","type":"address"}],"name":"Swept","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"}],"name":"UnregisterRewardToken","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"oldReceiver","type":"address"},{"indexed":true,"internalType":"address","name":"newReceiver","type":"address"}],"name":"UpdateRewardReceiver","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"newDeposit","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"loss","type":"uint256"}],"name":"UserDepositChange","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"reciever","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"}],"name":"WithdrawalRequestCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint64","name":"start","type":"uint64"},{"indexed":false,"internalType":"uint64","name":"end","type":"uint64"}],"name":"WithdrawalRequestUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint64","name":"start","type":"uint64"},{"indexed":false,"internalType":"uint64","name":"end","type":"uint64"}],"name":"WithdrawalRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newStartDelay","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newEndWindow","type":"uint256"}],"name":"WithdrawalWindowUpdated","type":"event"},{"inputs":[],"name":"ASSET_TOKEN","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EXEMPT_WITHDRAWAL_FEE_ROLE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIQUIDATION_TOKEN","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_DEPOSIT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_TOTAL_ASSET_SUPPLY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REBALANCER_ROLE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REWARD_DEPOSITOR_ROLE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REWARD_MANAGER_ROLE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REWARD_PERIOD_LENGTH","outputs":[{"internalType":"uint40","name":"","type":"uint40"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WITHDRAWAL_END_WINDOW","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WITHDRAWAL_START_DELAY","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"activeRewardTokens","outputs":[{"internalType":"address[]","name":"rewardTokens","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"assetBalanceOf","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"checkpoint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"receiver","type":"address"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"tokens","type":"address[]"}],"name":"claimHistorical","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address[]","name":"tokens","type":"address[]"}],"name":"claimHistorical","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"token","type":"address"}],"name":"claimable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"token","type":"address"}],"name":"claimed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assetAmount","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"minAmount","type":"uint256"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"assetsDeposited","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"depositReward","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getEarlyWithdrawalFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getFeeAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getWithdrawalRequest","outputs":[{"internalType":"uint64","name":"start","type":"uint64"},{"internalType":"uint64","name":"end","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getWithdrawalWindow","outputs":[{"internalType":"uint64","name":"startDelay","type":"uint64"},{"internalType":"uint64","name":"endWindow","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"roles","type":"uint256"}],"name":"grantRoles","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"roles","type":"uint256"}],"name":"hasAllRoles","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"roles","type":"uint256"}],"name":"hasAnyRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"historicalRewardTokens","outputs":[{"internalType":"address[]","name":"rewardTokens","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner_","type":"address"},{"internalType":"uint256","name":"earlyWithdrawalFee_","type":"uint256"},{"internalType":"address","name":"feeAddress_","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"isActiveRewardToken","outputs":[{"internalType":"bool","name":"isActive","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastAssetLossError","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"liquidated","type":"uint256"},{"internalType":"uint256","name":"returned","type":"uint256"}],"name":"notifyLiquidation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"owner_","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"pendingRewards","outputs":[{"internalType":"uint256","name":"distributable","type":"uint256"},{"internalType":"uint256","name":"undistributed","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"registerRewardToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"roles","type":"uint256"}],"name":"renounceRoles","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"requestWithdrawal","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"roles","type":"uint256"}],"name":"revokeRoles","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"rewardData","outputs":[{"internalType":"uint256","name":"lastUpdate","type":"uint256"},{"internalType":"uint256","name":"finishAt","type":"uint256"},{"internalType":"uint256","name":"rate","type":"uint256"},{"internalType":"uint256","name":"queued","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"rewardReceiver","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"rolesOf","outputs":[{"internalType":"uint256","name":"roles","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newReceiver","type":"address"}],"name":"setRewardReceiver","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"sweep","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"totalAssetSupply","outputs":[{"internalType":"uint256","name":"totalSupply_","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"totalAssetSupplyHistory","outputs":[{"internalType":"uint40","name":"atDay","type":"uint40"},{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"confirmOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"unregisterRewardToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assetAmount","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"minAmount","type":"uint256"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"assetsWithdrawn","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
0x6101c060405230608052348015610014575f5ffd5b50604051615a2d380380615a2d833981016040819052610033916105e3565b600160a0819052600462093a80828282610051565b60405180910390fd5b64ffffffffff1660e05260c0525061006c9250506102c99050565b5f876001600160a01b0316634e485cf76040518163ffffffff1660e01b8152600401602060405180830381865afa1580156100a9573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906100cd919061064b565b90506100d88161037b565b6001600160a01b038116610100526100ef8761037b565b876001600160a01b0316638bc211a76040518163ffffffff1660e01b8152600401602060405180830381865afa15801561012b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061014f919061064b565b6001600160a01b0316876001600160a01b0316141580156101e15750876001600160a01b031663510fe1206040518163ffffffff1660e01b8152600401602060405180830381865afa1580156101a7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101cb919061064b565b6001600160a01b0316876001600160a01b031614155b1561020a576040516370cfe96360e11b81526001600160a01b0388166004820152602401610048565b6001600160a01b03871661012052670de0b6b3a76400008611156102445760405163179c637760e11b815260048101879052602401610048565b6001600160a01b0385166102765760405163e59c387160e01b81526001600160a01b0386166004820152602401610048565b825f036102a057604051637561b6d160e01b81526004810185905260248101849052604401610048565b50610140819052610160526001600160401b0391821661018052166101a0525061068192505050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff16156103195760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b03908116146103785780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b61038481610501565b6040805160048152602481019091526020810180516001600160e01b039081166306fdde0360e01b179091526103bc91839161053f16565b15806103fd57506040805160048152602481019091526020810180516001600160e01b039081166395d89b4160e01b179091526103fb91839161053f16565b155b8061043d57506040805160048152602481019091526020810180516001600160e01b0390811663313ce56760e01b1790915261043b91839161053f16565b155b8061047d57506040805160048152602481019091526020810180516001600160e01b039081166318160ddd60e01b1790915261047b91839161053f16565b155b806104d857506040513060248201526104d69082906370a0823160e01b9060440160408051808303601f190181529190526020810180516001600160e01b0319939093166001600160e01b039384161790529061053f16565b155b1561037857604051633bd01f9b60e21b81526001600160a01b0382166004820152602401610048565b61050a816105a1565b806001600160a01b03163b5f036103785760405163a77cdf3160e01b81526001600160a01b0382166004820152602401610048565b5f5f836001600160a01b031683604051610559919061066b565b5f60405180830381855afa9150503d805f8114610591576040519150601f19603f3d011682016040523d82523d5f602084013e610596565b606091505b509095945050505050565b6001600160a01b0381166103785760405163d92e233d60e01b815260040160405180910390fd5b80516001600160a01b03811681146105de575f5ffd5b919050565b5f5f5f5f5f5f5f60e0888a0312156105f9575f5ffd5b610602886105c8565b9650610610602089016105c8565b60408901519096509450610626606089016105c8565b608089015160a08a015160c0909a0151989b979a509598909795969095945092505050565b5f6020828403121561065b575f5ffd5b610664826105c8565b9392505050565b5f82518060208501845e5f920191825250919050565b60805160a05160c05160e05161010051610120516101405161016051610180516101a0516152646107c95f395f818161080501528181610ba901528181611caa01528181611d100152611d7a01525f81816107e401528181610a7101528181611ce80152611d4c01525f610cb301525f8181610b57015281816113d501528181611411015281816122a5015281816122d80152818161231301528181612360015281816134f7015261353601525f818161046e0152818161129201526112f701525f8181610bfb0152818161125d01528181611381015281816115d8015281816125ad01526125ed01525f818161052e01528181611bd401528181612fba0152818161312c01526131d301525f81816109db015261109e01525f81816108cd01528181611ada0152611f1201525f8181612b9901528181612bc20152612d2701526152645ff3fe608060405260043610610350575f3560e01c80637db4e28f116101bd578063d40f482e116100f2578063dfcf3c2c11610092578063e63697c81161006d578063e63697c814610cf4578063e75c9a4e14610d13578063f2fde38b14610d46578063f4a73b9b14610d65575f5ffd5b8063dfcf3c2c14610c8e578063e1e158a514610ca2578063e46dbc9814610cd5575f5ffd5b8063dae254dd116100cd578063dae254dd14610c1d578063db02794614610c3c578063dbaf214514610c5b578063dc2c256f14610c6f575f5ffd5b8063d40f482e14610b98578063d4570c1c14610bcb578063d706200514610bea575f5ffd5b80639638dcb21161015d578063ad3cb1cc11610138578063ad3cb1cc14610aea578063bc157ac114610b27578063c319692114610b46578063c350a1b514610b79575f5ffd5b80639638dcb214610a60578063a3921f3014610aac578063a972985e14610acb575f5ffd5b80638c661b5d116101985780638c661b5d1461094c5780638d77ca57146109ca5780638da5cb5b146109fd5780638fb807c514610a30575f5ffd5b80637db4e28f146108ef5780637e256e411461090e578063838163ff1461092d575f5ffd5b80632de94807116102935780634f1ef2861161023357806352d1902d1161020e57806352d1902d146108465780636720a1201461085a5780636be2e80d1461089d5780636d750d80146108bc575f5ffd5b80634f1ef2861461078e578063514e62fc146107a157806351986813146107d6575f5ffd5b8063490b48f81161026e578063490b48f81461070b5780634a4ee7b11461071f5780634e71d92d1461073e5780634e7ceacb14610752575f5ffd5b80632de94807146105e757806331d7a2621461061857806348e5d9f81461064c575f5ffd5b8063183a4f6e116102fe5780631dbd2086116102d95780631dbd20861461051d5780631e83409a1461056657806321c0b3421461058557806324ebb13e146105a4575f5ffd5b8063183a4f6e146104a85780631c10893f146104c95780631cd64df4146104e8575f5ffd5b80630bf7bba51161032e5780630bf7bba5146103c95780630c9cbf0e146103ea57806316234de41461045d575f5ffd5b806301ffc9a71461035457806303c9f1301461038857806306b3efd6146103aa575b5f5ffd5b34801561035f575f5ffd5b5061037361036e366004614bd4565b610e0e565b60405190151581526020015b60405180910390f35b348015610393575f5ffd5b5061039c600881565b60405190815260200161037f565b3480156103b5575f5ffd5b5061039c6103c4366004614c16565b610e2d565b3480156103d4575f5ffd5b506103dd610ed1565b60405161037f9190614c2f565b3480156103f5575f5ffd5b5061039c610404366004614c7a565b6001600160a01b039182165f9081527f47ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e790260209081526040808320939094168252919091522054600160801b90046001600160801b031690565b348015610468575f5ffd5b506104907f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b03909116815260200161037f565b3480156104b3575f5ffd5b506104c76104c2366004614cab565b610f10565b005b3480156104d4575f5ffd5b506104c76104e3366004614cc2565b610f1d565b3480156104f3575f5ffd5b50610373610502366004614cc2565b638b78c6d8600c9081525f9290925260209091205481161490565b348015610528575f5ffd5b506105507f000000000000000000000000000000000000000000000000000000000000000081565b60405164ffffffffff909116815260200161037f565b348015610571575f5ffd5b506104c7610580366004614c16565b610f33565b348015610590575f5ffd5b506104c761059f366004614c7a565b610f39565b3480156105af575f5ffd5b507fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e40754600160a01b90046001600160601b031661039c565b3480156105f2575f5ffd5b5061039c610601366004614c16565b638b78c6d8600c9081525f91909152602090205490565b348015610623575f5ffd5b50610637610632366004614c16565b610f9b565b6040805192835260208301919091520161037f565b348015610657575f5ffd5b506106eb610666366004614c16565b6001600160a01b03165f9081525f5160206151cf5f395f51905f526020908152604091829020825160808101845290546001600160601b03811680835269ffffffffffffffffffff600160601b83041693830184905264ffffffffff600160b01b83048116958401869052600160d81b90920490911660609092018290529293909290565b60408051948552602085019390935291830152606082015260800161037f565b348015610716575f5ffd5b5061039c600281565b34801561072a575f5ffd5b506104c7610739366004614cc2565b610fb0565b348015610749575f5ffd5b506104c7610fc2565b34801561075d575f5ffd5b507fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e407546001600160a01b0316610490565b6104c761079c366004614d2f565b610fcd565b3480156107ac575f5ffd5b506103736107bb366004614cc2565b638b78c6d8600c9081525f9290925260209091205416151590565b3480156107e1575f5ffd5b507f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000005b6040805167ffffffffffffffff93841681529290911660208301520161037f565b348015610851575f5ffd5b5061039c610fe8565b348015610865575f5ffd5b50610490610874366004614c16565b6001600160a01b039081165f9081525f5160206151ef5f395f51905f5260205260409020541690565b3480156108a8575f5ffd5b506104c76108b7366004614e51565b611016565b3480156108c7575f5ffd5b5061039c7f000000000000000000000000000000000000000000000000000000000000000081565b3480156108fa575f5ffd5b506104c7610909366004614cc2565b61109c565b348015610919575f5ffd5b50610373610928366004614c16565b611193565b348015610938575f5ffd5b506104c7610947366004614e83565b6111d3565b348015610957575f5ffd5b50610825610966366004614c16565b6001600160a01b03165f9081527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e406602090815260409182902082518084019093525467ffffffffffffffff808216808552600160401b909204169290910182905291565b3480156109d5575f5ffd5b5061039c7f000000000000000000000000000000000000000000000000000000000000000081565b348015610a08575f5ffd5b507f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a6050054610490565b348015610a3b575f5ffd5b505f51602061520f5f395f51905f5254600160801b90046001600160681b031661039c565b348015610a6b575f5ffd5b50610a937f000000000000000000000000000000000000000000000000000000000000000081565b60405167ffffffffffffffff909116815260200161037f565b348015610ab7575f5ffd5b506104c7610ac6366004614ece565b61124c565b348015610ad6575f5ffd5b506104c7610ae5366004614c16565b61132a565b348015610af5575f5ffd5b50610b1a604051806040016040528060058152602001640352e302e360dc1b81525081565b60405161037f9190614eee565b348015610b32575f5ffd5b5061039c610b41366004614f23565b611343565b348015610b51575f5ffd5b5061039c7f000000000000000000000000000000000000000000000000000000000000000081565b348015610b84575f5ffd5b506104c7610b93366004614f56565b6117ab565b348015610ba3575f5ffd5b50610a937f000000000000000000000000000000000000000000000000000000000000000081565b348015610bd6575f5ffd5b5061039c610be5366004614c7a565b611a4e565b348015610bf5575f5ffd5b506104907f000000000000000000000000000000000000000000000000000000000000000081565b348015610c28575f5ffd5b506104c7610c37366004614c16565b611a5b565b348015610c47575f5ffd5b506104c7610c56366004614c16565b611ad8565b348015610c66575f5ffd5b506104c7611c88565b348015610c7a575f5ffd5b506104c7610c89366004614f56565b611e4e565b348015610c99575f5ffd5b506103dd611ed7565b348015610cad575f5ffd5b5061039c7f000000000000000000000000000000000000000000000000000000000000000081565b348015610ce0575f5ffd5b506104c7610cef366004614c16565b611f10565b348015610cff575f5ffd5b5061039c610d0e366004614f23565b611ffc565b348015610d1e575f5ffd5b507fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4055461039c565b348015610d51575f5ffd5b506104c7610d60366004614c16565b61266b565b348015610d70575f5ffd5b50610df1610d7f366004614cab565b5f9081527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4036020908152604091829020825160608101845281546001600160801b0381168252600160801b90046001600160681b031692810183905260019091015464ffffffffff1692018290529091565b6040805164ffffffffff909316835260208301919091520161037f565b5f610e1882612726565b80610e275750610e278261275a565b92915050565b6001600160a01b0381165f9081527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e40260209081526040808320815160608101835281546001600160801b03808216808452600160801b9092046001600160681b031695830186905260019093015464ffffffffff16938201939093525f51602061520f5f395f51905f52805490949193610ec99390911661277e565b949350505050565b60605f5160206151cf5f395f51905f52610f0a7fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30161278a565b91505090565b610f1a3382612796565b50565b610f256127a1565b610f2f82826127d6565b5050565b610f1a815f5b610f416127e2565b6001600160a01b0382163314801590610f6257506001600160a01b03811615155b15610f8057604051630894de8d60e01b815260040160405180910390fd5b610f898261284f565b610f938282612a2c565b610f2f612ad3565b5f5f610fa683612afd565b9094909350915050565b610fb86127a1565b610f2f8282612796565b33610f1a815f610f39565b610fd5612b8e565b610fde82612c45565b610f2f8282612c4d565b5f610ff1612d1c565b507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc90565b61101e6127e2565b335f5160206151ef5f395f51905f526110368261284f565b6001600160a01b038083165f9081526020839052604090205416806110585750815b5f5b8451811015611090576110878486838151811061107957611079614f8f565b602002602001015184612d65565b5060010161105a565b50505050610f1a612ad3565b7f00000000000000000000000000000000000000000000000000000000000000006110c681612ebb565b335f5160206151cf5f395f51905f526110ff7fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30186612f07565b61111c5760405163ad2882d360e01b815260040160405180910390fd5b8315611137576111376001600160a01b038616833087612f28565b61113f612faa565b6111498585613116565b846001600160a01b03167f4f7fd5c9e17300a4800fd572ea53fc291e2ee7470d73346d16b357faee4e72108560405161118491815260200190565b60405180910390a25050505050565b5f5f5160206151cf5f395f51905f526111cc7fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30184612f07565b9392505050565b6111db6127e2565b6111e48261284f565b6001600160a01b038281165f9081525f5160206151ef5f395f51905f526020819052604090912054909116806112175750825b5f5b8351811015611241576112388585838151811061107957611079614f8f565b50600101611219565b505050610f2f612ad3565b6002611257816132cc565b604080517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b039081168252602082018690527f000000000000000000000000000000000000000000000000000000000000000016818301526060810184905290517f3a487deef66df543d7641c7d8d3da7272a2658edd9f10ffe591214499517a2c89181900360800190a16112f25f61284f565b61131c7f0000000000000000000000000000000000000000000000000000000000000000836132f0565b6113258361347c565b505050565b6113326127e2565b61133b8161284f565b610f1a612ad3565b5f61134c6127e2565b6001600160a01b03831661137a57604051639cfea58360e01b81525f60048201526024015b60405180910390fd5b336113a6817f00000000000000000000000000000000000000000000000000000000000000008761369b565b9150828210156113d357604051630525805560e21b81526004810183905260248101849052604401611371565b7f000000000000000000000000000000000000000000000000000000000000000082101561143d57604051630525805560e21b8152600481018390527f00000000000000000000000000000000000000000000000000000000000000006024820152604401611371565b6001600160a01b0381165f9081527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e406602090815260409182902082518084019093525467ffffffffffffffff808216808552600160401b90920416918301919091525f51602061520f5f395f51905f529190158015906114d75750805f015167ffffffffffffffff16816020015167ffffffffffffffff16115b80156114f15750806020015167ffffffffffffffff164211155b1561157e576040805180820182525f80825260208083018281526001600160a01b0388168084526006880190925284832093518454915167ffffffffffffffff908116600160401b026fffffffffffffffffffffffffffffffff1990931691161717909255915190917f943970facef781cb8ed6d08ce322d6e16ccaac1b591098e21464910c69fe582191a25b856001600160a01b0316836001600160a01b03167f5548c837ab068cf56a2c2479df0882a4922fd203edb7517321831d95078c5f62866040516115c391815260200190565b60405180910390a36116006001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016843087612f28565b6116098661284f565b6040805160608101825283546001600160801b0381168252600160801b90046001600160681b031660208201818152600186015464ffffffffff16938301939093529091869161165a908390614fb7565b6001600160681b031690525064ffffffffff4216604082015261167c81613741565b6001600160a01b0387165f908152600284016020908152604091829020825160608101845281546001600160801b0381168252600160801b90046001600160681b031692810183815260019092015464ffffffffff169381019390935287916116e6908390614fb7565b6001600160681b039081169091526001600160a01b038a165f818152600288016020908152604080832087518154898501516001600160801b039092166001600160e81b031990911617600160801b91909716908102969096178155878201516001909101805464ffffffffff191664ffffffffff9092169190911790558051948552908401919091529092507f5fa7d0e13a31540b6d42936e522173de31fa0c53aa5aff71e63c60fe02b2b50e910160405180910390a250505050506111cc612ad3565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f811580156117f05750825b90505f8267ffffffffffffffff16600114801561180c5750303b155b90508115801561181a575080155b156118385760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561186757845468ff00000000000000001916600160401b1785555b61187088613929565b611878613967565b611880613967565b5f51602061520f5f395f51905f52670de0b6b3a76400008811156118ba5760405163179c637760e11b815260048101899052602401611371565b6001600160a01b0387166118ec5760405163e59c387160e01b81526001600160a01b0388166004820152602401611371565b6040805180820182526001600160a01b0389168082526001600160601b038b166020928301819052600160a01b0217600784015581516060810183526ec097ce7bc90715b34b9f100000000081525f91810182905290918101611950600142614fd6565b64ffffffffff90811690915281518454602080850180516001600160681b03908116600160801b9081026001600160e81b03199586166001600160801b0397881617178a55604080890180516001808e018054928c1664ffffffffff199384161790555f80805260038f019098529290962099518a549551909416909202939095169190951617178555915193810180549490931693909116929092179055600490920191909155508315611a4457845468ff000000000000000019168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050565b5f6111cc8383600161396f565b335f8181525f5160206151ef5f395f51905f5260208190526040808320805473ffffffffffffffffffffffffffffffffffffffff1981166001600160a01b0388811691821790935592519394911692839186917f49ddedcc7960d57ef16bbd5dda435520c8a203a051b3eb1a02f7e71e77478bf09190a450505050565b7f0000000000000000000000000000000000000000000000000000000000000000611b0281612ebb565b5f5160206151cf5f395f51905f52611b3a7fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30184613c42565b611b575760405163ad2882d360e01b815260040160405180910390fd5b6001600160a01b0383165f90815260208281526040808320815160808101835290546001600160601b038116825269ffffffffffffffffffff600160601b8204169382019390935264ffffffffff600160b01b8404811692820192909252600160d81b9092041660608201529080611bce83613c56565b915091507f000000000000000000000000000000000000000000000000000000000000000064ffffffffff16835f01516001600160601b03161015611c11575f83525b82516001600160601b03168201810115611c3e57604051630e6d89d360e21b815260040160405180910390fd5b50611c4e90506003830185613d1a565b506040516001600160a01b038516907fbfa4256e0ed8b426ac2df0a3469f79ee315552c50c46d123cfbc165252d8550e905f90a250505050565b611c906127e2565b335f51602061520f5f395f51905f5267ffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000165f03611d3d57604051637561b6d160e01b815267ffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000811660048301527f0000000000000000000000000000000000000000000000000000000000000000166024820152604401611371565b5f611d7267ffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001642614fe9565b90505f611d9f7f000000000000000000000000000000000000000000000000000000000000000083614ffc565b60408051808201825267ffffffffffffffff85811680835284821660208085018281526001600160a01b038c165f81815260068d0184528890209651875492518716600160401b026fffffffffffffffffffffffffffffffff19909316961695909517179094558451918252928101929092529293507fa548576ce23404fb1e2c1f9608435f4859f7d1b46d9497ba9c175554760607ce910160405180910390a250505050611e4c612ad3565b565b611e56613d2e565b611e5e6127e2565b611e6781613d38565b611e7230848461369b565b91508115611ecf57604080516001600160a01b0385811682526020820185905283168183015290517fbb3f74f3539ea7725781ff6810125a75c183f5c944318fc94873d1324f0482ae9181900360600190a1611ecf838383613d5f565b611325612ad3565b60605f5160206151cf5f395f51905f52610f0a7fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30361278a565b7f0000000000000000000000000000000000000000000000000000000000000000611f3a81612ebb565b6001600160a01b038216611f61576040516328346deb60e01b815260040160405180910390fd5b5f5160206151cf5f395f51905f52611f997fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30184613d1a565b611fb657604051638599b12960e01b815260040160405180910390fd5b611fc36003820184613c42565b506040516001600160a01b038416907ffc209c9379ca87c40c0d0b988d5a610ab04c00e2a5d79b765521bf7f1ee2e0f3905f90a2505050565b5f6120056127e2565b6001600160a01b03831661202e57604051639cfea58360e01b81525f6004820152602401611371565b5f51602061520f5f395f51905f52336120468161284f565b6001600160a01b0381165f818152600684016020908152604080832081518083018352905467ffffffffffffffff8082168352600160401b909104168184015293835260028601825291829020825160608101845281546001600160801b0381168252600160801b90046001600160681b03169281019290925260019081015464ffffffffff16928201929092529088016120f05780602001516001600160681b0316945061213a565b80602001516001600160681b0316881115612136576020810151604051632cd2c4c760e01b8152600481018a90526001600160681b039091166024820152604401611371565b8794505b845f0361215a576040516352c6c20960e11b815260040160405180910390fd5b85851015612185576040516345b648a360e01b81526004810186905260248101879052604401611371565b81515f90819067ffffffffffffffff16158015906121bd5750835f015167ffffffffffffffff16846020015167ffffffffffffffff16115b90505f8180156121d85750845167ffffffffffffffff164210155b80156121f25750846020015167ffffffffffffffff164211155b638b78c6d8600c9081525f8890526020902054909150600816151581158015612219575080155b15612260576007880154670de0b6b3a76400009061224790600160a01b90046001600160601b03168b61501c565b6122519190615047565b935061225d848a614fd6565b98505b6040805160608101825289546001600160801b0381168252600160801b90046001600160681b03166020820181905260018b015464ffffffffff1692820192909252907f0000000000000000000000000000000000000000000000000000000000000000906122d0908c90614fd6565b10156123b1577f000000000000000000000000000000000000000000000000000000000000000081602001516001600160681b031661230f9190614fd6565b99507f0000000000000000000000000000000000000000000000000000000000000000858b83602001516001600160681b031661234c9190614fd6565b6123569190614fd6565b10156123b1575f8a7f000000000000000000000000000000000000000000000000000000000000000083602001516001600160681b03166123979190614fd6565b6123a19190614fd6565b9050808611156123af578095505b505b8315612468576040805180820182525f80825260208083018281526001600160a01b038d1680845260068f0190925284832093518454915167ffffffffffffffff908116600160401b026fffffffffffffffffffffffffffffffff19909316911617179092558951925191927f9dc9167c6c5abda9be1c85b7408de345a2d3126d5eb09143aed42ecf9f2f798f9261245f929067ffffffffffffffff92831681529116602082015260400190565b60405180910390a25b8b6001600160a01b0316886001600160a01b03167f9b1bfa7fa9ee420a16e124f794c35ac9f90472acc99140eb2f6447c714cad8eb8c6040516124ad91815260200190565b60405180910390a3602081018051868c0190036001600160681b031690524264ffffffffff1660408201526124e181613741565b60208681018051878d0190036001600160681b0390811682526001600160a01b038b165f81815260028e01855260408082208c51815496516001600160801b039091166001600160e81b031990971696909617600160801b96909516958602949094178455808c01516001909401805464ffffffffff191664ffffffffff909516949094179093558251938452938301939093527f5fa7d0e13a31540b6d42936e522173de31fa0c53aa5aff71e63c60fe02b2b50e910160405180910390a26125d46001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168d8c613d6f565b841561265a576007890154612616906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116911687613d6f565b876001600160a01b03167f21dae94a123f67c07c94c892daa877636785a4c0d964b191ec90df8a48ff27fe8660405161265191815260200190565b60405180910390a25b5050505050505050506111cc612ad3565b7f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a60500543381146126a1576382b429005f526004601cfd5b7f9839bd1b7d13bef2e7a66ce106fd5e418f9f8fee5da4e55d26c2c33ef0bf4800547401ffffffffffffffffffffffffffffffffffffffff811683141560c082901c421117156126f857638cd65fff5f526004601cfd5b505f7f9839bd1b7d13bef2e7a66ce106fd5e418f9f8fee5da4e55d26c2c33ef0bf480055610f2f8183613da0565b5f6001600160e01b031982166307f5828d60e41b1480610e2757506301ffc9a760e01b6001600160e01b0319831614610e27565b5f6001600160e01b03198216632e1546ef60e01b1480610e275750610e2782612726565b5f610ec9848385613df1565b60605f6111cc83613e7b565b610f2f82825f613ed4565b7f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a60500543314611e4c576382b429005f526004601cfd5b610f2f82826001613ed4565b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005c1561282257604051633ee5aeb560e01b815260040160405180910390fd5b611e4c60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005b90613f2b565b5f51602061520f5f395f51905f5261286682613f32565b6001600160a01b03821615610f2f57604080516060808201835283546001600160801b0380821684526001600160681b03600160801b92839004811660208087019190915260018089015464ffffffffff908116888a01526001600160a01b038b165f90815260028b0184528981208a519889018b528054968716808a52979096049094169287018390529301549092169584019590955283519394929361290e929061277e565b905081602001516001600160681b0316816001600160681b03161461298d57846001600160a01b03167f5fa7d0e13a31540b6d42936e522173de31fa0c53aa5aff71e63c60fe02b2b50e828385602001516129699190615066565b604080516001600160681b0393841681529290911660208301520160405180910390a25b6040805160608101825293516001600160801b0390811685526001600160681b03928316602080870191825264ffffffffff4281168886019081526001600160a01b038b165f90815260028b0190935294909120965187549251909516600160801b026001600160e81b0319909216949092169390931792909217845551600190930180549390911664ffffffffff1990931692909217909155505050565b6001600160a01b038281165f9081525f5160206151ef5f395f51905f5260208190526040909120549091168015801590612a6d57506001600160a01b038316155b15612a76578092505b6001600160a01b038316612a88578392505b5f612a91610ed1565b90505f5b8151811015612acb57612ac286838381518110612ab457612ab4614f8f565b602002602001015187612d65565b50600101612a95565b505050505050565b611e4c5f7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00612849565b6001600160a01b0381165f9081525f5160206151cf5f395f51905f5260208181526040808420815160808101835290546001600160601b038116825269ffffffffffffffffffff600160601b8204169382019390935264ffffffffff600160b01b8404811692820192909252600160d81b909204166060820152829190612b8390613c56565b909590945092505050565b306001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480612c2757507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316612c1b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b6001600160a01b031614155b15611e4c5760405163703e46dd60e11b815260040160405180910390fd5b610f1a6127a1565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015612ca7575060408051601f3d908101601f19168201909252612ca491810190615085565b60015b612ccf57604051634c9c8ce360e01b81526001600160a01b0383166004820152602401611371565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8114612d1257604051632a87526960e21b815260048101829052602401611371565b6113258383614268565b306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614611e4c5760405163703e46dd60e11b815260040160405180910390fd5b6001600160a01b038381165f9081527f47ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e79026020908152604080832093861683529281528282208351808501909452546001600160801b03808216808652600160801b909204169184019190915290915f5160206151ef5f395f51905f52918015612eb1578151602083018051612dfb90839061509c565b6001600160801b039081169091525f8085526001600160a01b03808b1682526002870160209081526040808420928c168085529282529092208651928701518416600160801b029290931691909117909155612e5991508683613d6f565b846001600160a01b0316866001600160a01b0316886001600160a01b03167fc1405953cccdad6b442e266c84d66ad671e2534c6584f8e6ef92802f7ad294d584604051612ea891815260200190565b60405180910390a45b9695505050505050565b7f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a60500543314610f1a57638b78c6d8600c52335f52806020600c205416610f1a576382b429005f526004601cfd5b6001600160a01b0381165f90815260018301602052604081205415156111cc565b6040516001600160a01b038481166024830152838116604483015260648201839052612fa49186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506142bd565b50505050565b5f5160206151cf5f395f51905f527f000000000000000000000000000000000000000000000000000000000000000064ffffffffff161580612ff55750612ff381600101614329565b155b15612ffd5750565b5f61300a8260010161278a565b90505f5b8151811015611325575f82828151811061302a5761302a614f8f565b6020908102919091018101516001600160a01b0381165f9081528683526040808220815160808101835290546001600160601b038116825269ffffffffffffffffffff600160601b8204169582019590955264ffffffffff600160b01b8604811692820192909252600160d81b909404166060840152909250906130ad90613c56565b506001600160a01b0383165f90815260208790526040902080547fffffffffff0000000000ffffffffffffffffffffffffffffffffffffffffffff16600160b01b4264ffffffffff16021790559050801561310c5761310c82826132f0565b505060010161300e565b5f5160206151cf5f395f51905f5264ffffffffff7f0000000000000000000000000000000000000000000000000000000000000000165f0361315c5761132583836132f0565b6001600160a01b0383165f9081526020828152604091829020825160808101845290546001600160601b038116825269ffffffffffffffffffff600160601b8204169282019290925264ffffffffff600160b01b8304811693820193909352600160d81b90910482166060820152906131f99082907f00000000000000000000000000000000000000000000000000000000000000001685614332565b6001600160a01b0384165f908152602083815260409182902083518154928501519385015160609095015164ffffffffff908116600160d81b027affffffffffffffffffffffffffffffffffffffffffffffffffffff91909616600160b01b021675ffffffffffffffffffffffffffffffffffffffffffff69ffffffffffffffffffff909516600160601b027fffffffffffffffffffff000000000000000000000000000000000000000000009094166001600160601b0390921691909117929092179290921617919091179055505050565b638b78c6d8600c52335f52806020600c205416610f1a576382b429005f526004601cfd5b805f036132fb575050565b5f5f6133056144ee565b91509150805f0361337c578261333a856001600160a01b03165f9081525f5160206151cf5f395f51905f526020526040902090565b80545f906133529084906001600160601b03166150bb565b92506101000a8154816001600160601b0302191690836001600160601b0316021790555050505050565b6001600160a01b0384165f9081527f47ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e79016020908152604080832060ff607887901c168085529252909120545f5160206151ef5f395f51905f52906001600160c01b031661340b6133f3670de0b6b3a76400008861501c565b6effffffffffffffffffffffffffffff871686614560565b61341590826150da565b6001600160a01b039097165f90815260019092016020908152604080842060ff9095168452939052502080546001600160c01b039095167fffffffffffffffff00000000000000000000000000000000000000000000000090951694909417909355505050565b604080516060810182525f51602061520f5f395f51905f5280546001600160801b0381168352600160801b90046001600160681b0316602083018190527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4015464ffffffffff1693830193909352915f036134f557505050565b7f000000000000000000000000000000000000000000000000000000000000000081602001516001600160681b031661352e9190614fd6565b8310613570577f000000000000000000000000000000000000000000000000000000000000000081602001516001600160681b031661356d9190614fd6565b92505b825f0361357c57505050565b5f8061359085670de0b6b3a764000061501c565b9050836005015481116135be5780846005015f8282546135b09190614fd6565b909155505f925061362d9050565b5f8460050154826135cf9190614fd6565b60208501519091506001600160681b03166135eb600183614fd6565b6135f59190615047565b613600906001614fe9565b92508084602001516001600160681b03168461361c919061501c565b6136269190614fd6565b6005860155505b848360200181815161363f9190615066565b6001600160681b03169052505f61365e83670de0b6b3a76400006150f9565b845190915061367a906001600160801b03908116908316614616565b6001600160801b0316845264ffffffffff42166040850152612acb84613741565b5f5f198203613713576040516370a0823160e01b81526001600160a01b0385811660048301528416906370a0823190602401602060405180830381865afa1580156136e8573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061370c9190615085565b9050613716565b50805b805f036111cc5760405163fc2e7f8760e01b81526001600160a01b0384166004820152602401611371565b7fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4045460408201515f51602061520f5f395f51905f52919064ffffffffff167fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4035f6137ac600185614fd6565b815260208101919091526040015f206001015464ffffffffff160361384d5782600383015f6137dc600185614fd6565b815260208082019290925260409081015f2083518154938501516001600160681b0316600160801b026001600160e81b03199094166001600160801b039091161792909217825591909101516001909101805464ffffffffff90921664ffffffffff199092169190911790556138ca565b5f81815260038301602090815260409182902085518154928701516001600160681b0316600160801b026001600160e81b03199093166001600160801b0390911617919091178155908401516001918201805464ffffffffff90921664ffffffffff199092169190911790556138c4908290614fe9565b60048301555b508151815460208401516001600160681b0316600160801b026001600160e81b03199091166001600160801b03909216919091171781556040909101516001909101805464ffffffffff90921664ffffffffff19909216919091179055565b613931614712565b610e10420160c01b81177f9839bd1b7d13bef2e7a66ce106fd5e418f9f8fee5da4e55d26c2c33ef0bf480055610f1a5f33613da0565b611e4c614746565b6001600160a01b038381165f8181527f47ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e7902602090815260408083209487168352938152838220549282527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e402815290839020835160608101855281546001600160801b03808216808452600160801b9092046001600160681b031694830185905260019093015464ffffffffff169190950152909116915f5160206151ef5f395f51905f52918015613c385760ff607883901c165f80613a4b6144ee565b90925090505f613a6f6008613a678660ff607888901c16615118565b60ff1661478f565b6001600160a01b038b165f9081526001808a016020908152604080842060ff8a168552918290529092205492935090916001600160c01b0316905b8360ff168160ff1611613b1c575f8381613ac4848b615131565b60ff16815260208101919091526040015f20546001600160c01b031690508015613b0b57613afe816001600160c01b03168360ff1661479e565b613b0890846150da565b92505b50613b158161514a565b9050613aaa565b505f896002015f8f6001600160a01b03166001600160a01b031681526020019081526020015f205f8e6001600160a01b03166001600160a01b031681526020019081526020015f206001015f0160089054906101000a90046001600160c01b03169050806001600160c01b0316826001600160c01b03161115613be557613bd888613ba78385615168565b6001600160c01b0316613bd3670de0b6b3a76400006effffffffffffffffffffffffffffff8e1661501c565b614560565b613be2908c614fe9565b9a505b8b8015613bf157505f85115b15613c30575f613c008e612afd565b50905085613c18613c118b8461501c565b898d613df1565b613c229190615047565b613c2c908d614fe9565b9b50505b505050505050505b5050509392505050565b5f6111cc836001600160a01b03841661488e565b5f5f5f5f5f9050846060015164ffffffffff16421115613cb657846040015164ffffffffff16856060015164ffffffffff161015613c94575f613ca8565b84604001518560600151613ca89190615187565b64ffffffffff169150613cd7565b846040015164ffffffffff164203915042856060015164ffffffffff160390505b81856020015169ffffffffffffffffffff16613cf3919061501c565b81866020015169ffffffffffffffffffff16613d0f919061501c565b935093505050915091565b5f6111cc836001600160a01b038416614971565b611e4c6002612ebb565b6001600160a01b038116610f1a5760405163d92e233d60e01b815260040160405180910390fd5b6113256001600160a01b03841682845b6040516001600160a01b0383811660248301526044820183905261132591859182169063a9059cbb90606401612f5d565b80827f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f5fa3801560ff1b177f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a605005550565b5f60ff607883811c8216919085901c166effffffffffffffffffffffffffffff808516908616871580613e2957508360ff168360ff16105b80613e4057506008613e3b8585615118565b60ff16115b15613e4d575f9450613e70565b613e6d613e5b898385614560565b613e658686615118565b60ff1661479e565b94505b505050509392505050565b6060815f01805480602002602001604051908101604052809291908181526020018280548015613ec857602002820191905f5260205f20905b815481526020019060010190808311613eb4575b50505050509050919050565b638b78c6d8600c52825f526020600c20805483811783613ef5575080841681185b80835580600c5160601c7f715ad5ce61fc9595c7b415289d59cf203f23a94fa06f04af7e489a0a76e1fe265f5fa3505050505050565b80825d5050565b613f3a612faa565b6001600160a01b03811615610f1a575f613f52610ed1565b90505f613f5d611ed7565b82518151919250905f90613f719083614fe9565b9050805f03613f81575050505050565b5f5160206151ef5f395f51905f525f613f986144ee565b50905060ff607882901c165f5b8481101561425d575f868210613fdd5787613fc08884614fd6565b81518110613fd057613fd0614f8f565b6020026020010151613ff8565b888281518110613fef57613fef614f8f565b60200260200101515b6001600160a01b038b81165f90815260028801602090815260408083209385168352928152828220835160808101855281546001600160801b03808216838801908152600160801b9092041660608301528152845180860190955260019091015467ffffffffffffffff81168552600160401b90046001600160c01b0316848301529081019290925291925090614092908c90849061396f565b815f01515f01906001600160801b031690816001600160801b031681525050856001015f836001600160a01b03166001600160a01b031681526020019081526020015f205f8560ff1660ff1681526020019081526020015f205f9054906101000a90046001600160c01b03168160200151602001906001600160c01b031690816001600160c01b0316815250504281602001515f019067ffffffffffffffff16908167ffffffffffffffff168152505080866002015f8d6001600160a01b03166001600160a01b031681526020019081526020015f205f846001600160a01b03166001600160a01b031681526020019081526020015f205f820151815f015f820151815f015f6101000a8154816001600160801b0302191690836001600160801b031602179055506020820151815f0160106101000a8154816001600160801b0302191690836001600160801b0316021790555050506020820151816001015f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a8154816001600160c01b0302191690836001600160c01b03160217905550505090505050508080600101915050613fa5565b505050505050505050565b614271826149bd565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a28051156142b5576113258282614a40565b610f2f614ab2565b5f5f60205f8451602086015f885af1806142dc576040513d5f823e3d81fd5b50505f513d915081156142f3578060011415614300565b6001600160a01b0384163b155b15612fa457604051635274afe760e01b81526001600160a01b0385166004820152602401611371565b5f610e27825490565b8251614347906001600160601b031682614fe9565b5f8452606084015190915064ffffffffff1642106143ce5761437161436c8383615047565b614ad1565b69ffffffffffffffffffff166020840181905261438f90839061501c565b6143999082614fd6565b6001600160601b031683524264ffffffffff811660408501526143bd908390614fe9565b64ffffffffff166060840152505050565b5f82846060015164ffffffffff166143e69190614fd6565b6143f09042614fd6565b90505f81856020015169ffffffffffffffffffff1661440f919061501c565b905061441c83600a61501c565b61442782600961501c565b116144d257846040015185606001516144409190615187565b64ffffffffff16856020015169ffffffffffffffffffff16614462919061501c565b61446c9084614fe9565b925061447b61436c8585615047565b69ffffffffffffffffffff166020860181905261449990859061501c565b6144a39084614fd6565b6001600160601b031685526144b88442614fe9565b64ffffffffff9081166060870152421660408601526144e7565b6144db83614b0b565b6001600160601b031685525b5050505050565b604080516060810182525f51602061520f5f395f51905f52546001600160801b038116808352600160801b9091046001600160681b0316602083018190527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4015464ffffffffff16929093019190915291565b5f838302815f1985870982811083820303915050805f036145945783828161458a5761458a615033565b04925050506111cc565b8084116145ab576145ab6003851502601118614b3e565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f60ff607884901c166effffffffffffffffffffffffffffff84168381028281156146dd57670de0b6b3a764000082046b033b2e3c9fd0803ce80000008110156146d757633b9aca0081101561469b57600181101561468757600482019150670de0b6b3a7640000830292506146db565b600382019150633b9aca00830292506146db565b670de0b6b3a76400008110156146b6576002820191506146db565b600182019150633b9aca0083816146cf576146cf615033565b0492506146db565b8092505b505b607881901b6fff000000000000000000000000000000166effffffffffffffffffffffffffffff831617979650505050505050565b7f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a605005415611e4c57630dc149f05f526004601cfd5b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff16611e4c57604051631afcd79f60e31b815260040160405180910390fd5b5f8282188284100282186111cc565b5f5f60405180610120016040528060018152602001633b9aca008152602001670de0b6b3a764000081526020016b033b2e3c9fd0803ce800000081526020016ec097ce7bc90715b34b9f10000000008152602001722cd76fe086b93ce2f768a00b22a000000000008152602001760a70c3c40a64e6c51999090b65f67d924000000000000081526020017a026e4d30eccc3215dd8f3157d27e23acbdcfe6800000000000000081526020017d90e40fbeea1d3a4abc8955e946fe31cdcf66f634e1000000000000000000815250905080836009811061487f5761487f614f8f565b6020020151610ec99085615047565b5f8181526001830160205260408120548015614968575f6148b0600183614fd6565b85549091505f906148c390600190614fd6565b9050808214614922575f865f0182815481106148e1576148e1614f8f565b905f5260205f200154905080875f01848154811061490157614901614f8f565b5f918252602080832090910192909255918252600188019052604090208390555b8554869080614933576149336151a4565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050610e27565b5f915050610e27565b5f8181526001830160205260408120546149b657508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610e27565b505f610e27565b806001600160a01b03163b5f036149f257604051634c9c8ce360e01b81526001600160a01b0382166004820152602401611371565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b60605f5f846001600160a01b031684604051614a5c91906151b8565b5f60405180830381855af49150503d805f8114614a94576040519150601f19603f3d011682016040523d82523d5f602084013e614a99565b606091505b5091509150614aa9858383614b4f565b95945050505050565b3415611e4c5760405163b398979f60e01b815260040160405180910390fd5b5f69ffffffffffffffffffff821115614b07576040516306dfcc6560e41b81526050600482015260248101839052604401611371565b5090565b5f6001600160601b03821115614b07576040516306dfcc6560e41b81526060600482015260248101839052604401611371565b634e487b715f52806020526024601cfd5b606082614b6457614b5f82614bab565b6111cc565b8151158015614b7b57506001600160a01b0384163b155b15614ba457604051639996b31560e01b81526001600160a01b0385166004820152602401611371565b50806111cc565b805115614bbb5780518082602001fd5b60405163d6bda27560e01b815260040160405180910390fd5b5f60208284031215614be4575f5ffd5b81356001600160e01b0319811681146111cc575f5ffd5b80356001600160a01b0381168114614c11575f5ffd5b919050565b5f60208284031215614c26575f5ffd5b6111cc82614bfb565b602080825282518282018190525f918401906040840190835b81811015614c6f5783516001600160a01b0316835260209384019390920191600101614c48565b509095945050505050565b5f5f60408385031215614c8b575f5ffd5b614c9483614bfb565b9150614ca260208401614bfb565b90509250929050565b5f60208284031215614cbb575f5ffd5b5035919050565b5f5f60408385031215614cd3575f5ffd5b614cdc83614bfb565b946020939093013593505050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715614d2757614d27614cea565b604052919050565b5f5f60408385031215614d40575f5ffd5b614d4983614bfb565b9150602083013567ffffffffffffffff811115614d64575f5ffd5b8301601f81018513614d74575f5ffd5b803567ffffffffffffffff811115614d8e57614d8e614cea565b614da1601f8201601f1916602001614cfe565b818152866020838501011115614db5575f5ffd5b816020840160208301375f602083830101528093505050509250929050565b5f82601f830112614de3575f5ffd5b813567ffffffffffffffff811115614dfd57614dfd614cea565b8060051b614e0d60208201614cfe565b91825260208185018101929081019086841115614e28575f5ffd5b6020860192505b83831015612eb157614e4083614bfb565b825260209283019290910190614e2f565b5f60208284031215614e61575f5ffd5b813567ffffffffffffffff811115614e77575f5ffd5b610ec984828501614dd4565b5f5f60408385031215614e94575f5ffd5b614e9d83614bfb565b9150602083013567ffffffffffffffff811115614eb8575f5ffd5b614ec485828601614dd4565b9150509250929050565b5f5f60408385031215614edf575f5ffd5b50508035926020909101359150565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b5f5f5f60608486031215614f35575f5ffd5b83359250614f4560208501614bfb565b929592945050506040919091013590565b5f5f5f60608486031215614f68575f5ffd5b614f7184614bfb565b925060208401359150614f8660408501614bfb565b90509250925092565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b6001600160681b038181168382160190811115610e2757610e27614fa3565b81810381811115610e2757610e27614fa3565b80820180821115610e2757610e27614fa3565b67ffffffffffffffff8181168382160190811115610e2757610e27614fa3565b8082028115828204841417610e2757610e27614fa3565b634e487b7160e01b5f52601260045260245ffd5b5f8261506157634e487b7160e01b5f52601260045260245ffd5b500490565b6001600160681b038281168282160390811115610e2757610e27614fa3565b5f60208284031215615095575f5ffd5b5051919050565b6001600160801b038181168382160190811115610e2757610e27614fa3565b6001600160601b038181168382160190811115610e2757610e27614fa3565b6001600160c01b038181168382160190811115610e2757610e27614fa3565b6001600160801b038281168282160390811115610e2757610e27614fa3565b60ff8281168282160390811115610e2757610e27614fa3565b60ff8181168382160190811115610e2757610e27614fa3565b5f60ff821660ff810361515f5761515f614fa3565b60010192915050565b6001600160c01b038281168282160390811115610e2757610e27614fa3565b64ffffffffff8281168282160390811115610e2757610e27614fa3565b634e487b7160e01b5f52603160045260245ffd5b5f82518060208501845e5f92019182525091905056fee9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30047ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e7900cb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e400a2646970667358221220b0fc72ba6b94f082a8f3ccc2dc3fa9fec25897070a40bd69269aa99f9936ed2264736f6c634300081e0033000000000000000000000000880600e0c803d836e305b7c242fc095eed234a8f00000000000000000000000085730af3a7d7a872ee1d84306e0575f1e00c0980000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000deadbeef0000000000000000000000000000000000000000000000000000000000000e100000000000000000000000000000000000000000000000000000000000015f900000000000000000000000000000000000000000000000000000b5e620f48000
Deployed Bytecode
0x608060405260043610610350575f3560e01c80637db4e28f116101bd578063d40f482e116100f2578063dfcf3c2c11610092578063e63697c81161006d578063e63697c814610cf4578063e75c9a4e14610d13578063f2fde38b14610d46578063f4a73b9b14610d65575f5ffd5b8063dfcf3c2c14610c8e578063e1e158a514610ca2578063e46dbc9814610cd5575f5ffd5b8063dae254dd116100cd578063dae254dd14610c1d578063db02794614610c3c578063dbaf214514610c5b578063dc2c256f14610c6f575f5ffd5b8063d40f482e14610b98578063d4570c1c14610bcb578063d706200514610bea575f5ffd5b80639638dcb21161015d578063ad3cb1cc11610138578063ad3cb1cc14610aea578063bc157ac114610b27578063c319692114610b46578063c350a1b514610b79575f5ffd5b80639638dcb214610a60578063a3921f3014610aac578063a972985e14610acb575f5ffd5b80638c661b5d116101985780638c661b5d1461094c5780638d77ca57146109ca5780638da5cb5b146109fd5780638fb807c514610a30575f5ffd5b80637db4e28f146108ef5780637e256e411461090e578063838163ff1461092d575f5ffd5b80632de94807116102935780634f1ef2861161023357806352d1902d1161020e57806352d1902d146108465780636720a1201461085a5780636be2e80d1461089d5780636d750d80146108bc575f5ffd5b80634f1ef2861461078e578063514e62fc146107a157806351986813146107d6575f5ffd5b8063490b48f81161026e578063490b48f81461070b5780634a4ee7b11461071f5780634e71d92d1461073e5780634e7ceacb14610752575f5ffd5b80632de94807146105e757806331d7a2621461061857806348e5d9f81461064c575f5ffd5b8063183a4f6e116102fe5780631dbd2086116102d95780631dbd20861461051d5780631e83409a1461056657806321c0b3421461058557806324ebb13e146105a4575f5ffd5b8063183a4f6e146104a85780631c10893f146104c95780631cd64df4146104e8575f5ffd5b80630bf7bba51161032e5780630bf7bba5146103c95780630c9cbf0e146103ea57806316234de41461045d575f5ffd5b806301ffc9a71461035457806303c9f1301461038857806306b3efd6146103aa575b5f5ffd5b34801561035f575f5ffd5b5061037361036e366004614bd4565b610e0e565b60405190151581526020015b60405180910390f35b348015610393575f5ffd5b5061039c600881565b60405190815260200161037f565b3480156103b5575f5ffd5b5061039c6103c4366004614c16565b610e2d565b3480156103d4575f5ffd5b506103dd610ed1565b60405161037f9190614c2f565b3480156103f5575f5ffd5b5061039c610404366004614c7a565b6001600160a01b039182165f9081527f47ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e790260209081526040808320939094168252919091522054600160801b90046001600160801b031690565b348015610468575f5ffd5b506104907f00000000000000000000000085730af3a7d7a872ee1d84306e0575f1e00c098081565b6040516001600160a01b03909116815260200161037f565b3480156104b3575f5ffd5b506104c76104c2366004614cab565b610f10565b005b3480156104d4575f5ffd5b506104c76104e3366004614cc2565b610f1d565b3480156104f3575f5ffd5b50610373610502366004614cc2565b638b78c6d8600c9081525f9290925260209091205481161490565b348015610528575f5ffd5b506105507f0000000000000000000000000000000000000000000000000000000000093a8081565b60405164ffffffffff909116815260200161037f565b348015610571575f5ffd5b506104c7610580366004614c16565b610f33565b348015610590575f5ffd5b506104c761059f366004614c7a565b610f39565b3480156105af575f5ffd5b507fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e40754600160a01b90046001600160601b031661039c565b3480156105f2575f5ffd5b5061039c610601366004614c16565b638b78c6d8600c9081525f91909152602090205490565b348015610623575f5ffd5b50610637610632366004614c16565b610f9b565b6040805192835260208301919091520161037f565b348015610657575f5ffd5b506106eb610666366004614c16565b6001600160a01b03165f9081525f5160206151cf5f395f51905f526020908152604091829020825160808101845290546001600160601b03811680835269ffffffffffffffffffff600160601b83041693830184905264ffffffffff600160b01b83048116958401869052600160d81b90920490911660609092018290529293909290565b60408051948552602085019390935291830152606082015260800161037f565b348015610716575f5ffd5b5061039c600281565b34801561072a575f5ffd5b506104c7610739366004614cc2565b610fb0565b348015610749575f5ffd5b506104c7610fc2565b34801561075d575f5ffd5b507fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e407546001600160a01b0316610490565b6104c761079c366004614d2f565b610fcd565b3480156107ac575f5ffd5b506103736107bb366004614cc2565b638b78c6d8600c9081525f9290925260209091205416151590565b3480156107e1575f5ffd5b507f0000000000000000000000000000000000000000000000000000000000000e107f0000000000000000000000000000000000000000000000000000000000015f905b6040805167ffffffffffffffff93841681529290911660208301520161037f565b348015610851575f5ffd5b5061039c610fe8565b348015610865575f5ffd5b50610490610874366004614c16565b6001600160a01b039081165f9081525f5160206151ef5f395f51905f5260205260409020541690565b3480156108a8575f5ffd5b506104c76108b7366004614e51565b611016565b3480156108c7575f5ffd5b5061039c7f000000000000000000000000000000000000000000000000000000000000000181565b3480156108fa575f5ffd5b506104c7610909366004614cc2565b61109c565b348015610919575f5ffd5b50610373610928366004614c16565b611193565b348015610938575f5ffd5b506104c7610947366004614e83565b6111d3565b348015610957575f5ffd5b50610825610966366004614c16565b6001600160a01b03165f9081527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e406602090815260409182902082518084019093525467ffffffffffffffff808216808552600160401b909204169290910182905291565b3480156109d5575f5ffd5b5061039c7f000000000000000000000000000000000000000000000000000000000000000481565b348015610a08575f5ffd5b507f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a6050054610490565b348015610a3b575f5ffd5b505f51602061520f5f395f51905f5254600160801b90046001600160681b031661039c565b348015610a6b575f5ffd5b50610a937f0000000000000000000000000000000000000000000000000000000000000e1081565b60405167ffffffffffffffff909116815260200161037f565b348015610ab7575f5ffd5b506104c7610ac6366004614ece565b61124c565b348015610ad6575f5ffd5b506104c7610ae5366004614c16565b61132a565b348015610af5575f5ffd5b50610b1a604051806040016040528060058152602001640352e302e360dc1b81525081565b60405161037f9190614eee565b348015610b32575f5ffd5b5061039c610b41366004614f23565b611343565b348015610b51575f5ffd5b5061039c7f0000000000000000000000000000000000000000000000000000b5e620f4800081565b348015610b84575f5ffd5b506104c7610b93366004614f56565b6117ab565b348015610ba3575f5ffd5b50610a937f0000000000000000000000000000000000000000000000000000000000015f9081565b348015610bd6575f5ffd5b5061039c610be5366004614c7a565b611a4e565b348015610bf5575f5ffd5b506104907f0000000000000000000000005b66d86932ae5d9751da588d91d494950554061d81565b348015610c28575f5ffd5b506104c7610c37366004614c16565b611a5b565b348015610c47575f5ffd5b506104c7610c56366004614c16565b611ad8565b348015610c66575f5ffd5b506104c7611c88565b348015610c7a575f5ffd5b506104c7610c89366004614f56565b611e4e565b348015610c99575f5ffd5b506103dd611ed7565b348015610cad575f5ffd5b5061039c7f0000000000000000000000000000000000000000000000000000b5e620f4800081565b348015610ce0575f5ffd5b506104c7610cef366004614c16565b611f10565b348015610cff575f5ffd5b5061039c610d0e366004614f23565b611ffc565b348015610d1e575f5ffd5b507fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4055461039c565b348015610d51575f5ffd5b506104c7610d60366004614c16565b61266b565b348015610d70575f5ffd5b50610df1610d7f366004614cab565b5f9081527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4036020908152604091829020825160608101845281546001600160801b0381168252600160801b90046001600160681b031692810183905260019091015464ffffffffff1692018290529091565b6040805164ffffffffff909316835260208301919091520161037f565b5f610e1882612726565b80610e275750610e278261275a565b92915050565b6001600160a01b0381165f9081527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e40260209081526040808320815160608101835281546001600160801b03808216808452600160801b9092046001600160681b031695830186905260019093015464ffffffffff16938201939093525f51602061520f5f395f51905f52805490949193610ec99390911661277e565b949350505050565b60605f5160206151cf5f395f51905f52610f0a7fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30161278a565b91505090565b610f1a3382612796565b50565b610f256127a1565b610f2f82826127d6565b5050565b610f1a815f5b610f416127e2565b6001600160a01b0382163314801590610f6257506001600160a01b03811615155b15610f8057604051630894de8d60e01b815260040160405180910390fd5b610f898261284f565b610f938282612a2c565b610f2f612ad3565b5f5f610fa683612afd565b9094909350915050565b610fb86127a1565b610f2f8282612796565b33610f1a815f610f39565b610fd5612b8e565b610fde82612c45565b610f2f8282612c4d565b5f610ff1612d1c565b507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc90565b61101e6127e2565b335f5160206151ef5f395f51905f526110368261284f565b6001600160a01b038083165f9081526020839052604090205416806110585750815b5f5b8451811015611090576110878486838151811061107957611079614f8f565b602002602001015184612d65565b5060010161105a565b50505050610f1a612ad3565b7f00000000000000000000000000000000000000000000000000000000000000046110c681612ebb565b335f5160206151cf5f395f51905f526110ff7fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30186612f07565b61111c5760405163ad2882d360e01b815260040160405180910390fd5b8315611137576111376001600160a01b038616833087612f28565b61113f612faa565b6111498585613116565b846001600160a01b03167f4f7fd5c9e17300a4800fd572ea53fc291e2ee7470d73346d16b357faee4e72108560405161118491815260200190565b60405180910390a25050505050565b5f5f5160206151cf5f395f51905f526111cc7fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30184612f07565b9392505050565b6111db6127e2565b6111e48261284f565b6001600160a01b038281165f9081525f5160206151ef5f395f51905f526020819052604090912054909116806112175750825b5f5b8351811015611241576112388585838151811061107957611079614f8f565b50600101611219565b505050610f2f612ad3565b6002611257816132cc565b604080517f0000000000000000000000005b66d86932ae5d9751da588d91d494950554061d6001600160a01b039081168252602082018690527f00000000000000000000000085730af3a7d7a872ee1d84306e0575f1e00c098016818301526060810184905290517f3a487deef66df543d7641c7d8d3da7272a2658edd9f10ffe591214499517a2c89181900360800190a16112f25f61284f565b61131c7f00000000000000000000000085730af3a7d7a872ee1d84306e0575f1e00c0980836132f0565b6113258361347c565b505050565b6113326127e2565b61133b8161284f565b610f1a612ad3565b5f61134c6127e2565b6001600160a01b03831661137a57604051639cfea58360e01b81525f60048201526024015b60405180910390fd5b336113a6817f0000000000000000000000005b66d86932ae5d9751da588d91d494950554061d8761369b565b9150828210156113d357604051630525805560e21b81526004810183905260248101849052604401611371565b7f0000000000000000000000000000000000000000000000000000b5e620f4800082101561143d57604051630525805560e21b8152600481018390527f0000000000000000000000000000000000000000000000000000b5e620f480006024820152604401611371565b6001600160a01b0381165f9081527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e406602090815260409182902082518084019093525467ffffffffffffffff808216808552600160401b90920416918301919091525f51602061520f5f395f51905f529190158015906114d75750805f015167ffffffffffffffff16816020015167ffffffffffffffff16115b80156114f15750806020015167ffffffffffffffff164211155b1561157e576040805180820182525f80825260208083018281526001600160a01b0388168084526006880190925284832093518454915167ffffffffffffffff908116600160401b026fffffffffffffffffffffffffffffffff1990931691161717909255915190917f943970facef781cb8ed6d08ce322d6e16ccaac1b591098e21464910c69fe582191a25b856001600160a01b0316836001600160a01b03167f5548c837ab068cf56a2c2479df0882a4922fd203edb7517321831d95078c5f62866040516115c391815260200190565b60405180910390a36116006001600160a01b037f0000000000000000000000005b66d86932ae5d9751da588d91d494950554061d16843087612f28565b6116098661284f565b6040805160608101825283546001600160801b0381168252600160801b90046001600160681b031660208201818152600186015464ffffffffff16938301939093529091869161165a908390614fb7565b6001600160681b031690525064ffffffffff4216604082015261167c81613741565b6001600160a01b0387165f908152600284016020908152604091829020825160608101845281546001600160801b0381168252600160801b90046001600160681b031692810183815260019092015464ffffffffff169381019390935287916116e6908390614fb7565b6001600160681b039081169091526001600160a01b038a165f818152600288016020908152604080832087518154898501516001600160801b039092166001600160e81b031990911617600160801b91909716908102969096178155878201516001909101805464ffffffffff191664ffffffffff9092169190911790558051948552908401919091529092507f5fa7d0e13a31540b6d42936e522173de31fa0c53aa5aff71e63c60fe02b2b50e910160405180910390a250505050506111cc612ad3565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f811580156117f05750825b90505f8267ffffffffffffffff16600114801561180c5750303b155b90508115801561181a575080155b156118385760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561186757845468ff00000000000000001916600160401b1785555b61187088613929565b611878613967565b611880613967565b5f51602061520f5f395f51905f52670de0b6b3a76400008811156118ba5760405163179c637760e11b815260048101899052602401611371565b6001600160a01b0387166118ec5760405163e59c387160e01b81526001600160a01b0388166004820152602401611371565b6040805180820182526001600160a01b0389168082526001600160601b038b166020928301819052600160a01b0217600784015581516060810183526ec097ce7bc90715b34b9f100000000081525f91810182905290918101611950600142614fd6565b64ffffffffff90811690915281518454602080850180516001600160681b03908116600160801b9081026001600160e81b03199586166001600160801b0397881617178a55604080890180516001808e018054928c1664ffffffffff199384161790555f80805260038f019098529290962099518a549551909416909202939095169190951617178555915193810180549490931693909116929092179055600490920191909155508315611a4457845468ff000000000000000019168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050565b5f6111cc8383600161396f565b335f8181525f5160206151ef5f395f51905f5260208190526040808320805473ffffffffffffffffffffffffffffffffffffffff1981166001600160a01b0388811691821790935592519394911692839186917f49ddedcc7960d57ef16bbd5dda435520c8a203a051b3eb1a02f7e71e77478bf09190a450505050565b7f0000000000000000000000000000000000000000000000000000000000000001611b0281612ebb565b5f5160206151cf5f395f51905f52611b3a7fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30184613c42565b611b575760405163ad2882d360e01b815260040160405180910390fd5b6001600160a01b0383165f90815260208281526040808320815160808101835290546001600160601b038116825269ffffffffffffffffffff600160601b8204169382019390935264ffffffffff600160b01b8404811692820192909252600160d81b9092041660608201529080611bce83613c56565b915091507f0000000000000000000000000000000000000000000000000000000000093a8064ffffffffff16835f01516001600160601b03161015611c11575f83525b82516001600160601b03168201810115611c3e57604051630e6d89d360e21b815260040160405180910390fd5b50611c4e90506003830185613d1a565b506040516001600160a01b038516907fbfa4256e0ed8b426ac2df0a3469f79ee315552c50c46d123cfbc165252d8550e905f90a250505050565b611c906127e2565b335f51602061520f5f395f51905f5267ffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000015f90165f03611d3d57604051637561b6d160e01b815267ffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000e10811660048301527f0000000000000000000000000000000000000000000000000000000000015f90166024820152604401611371565b5f611d7267ffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000e101642614fe9565b90505f611d9f7f0000000000000000000000000000000000000000000000000000000000015f9083614ffc565b60408051808201825267ffffffffffffffff85811680835284821660208085018281526001600160a01b038c165f81815260068d0184528890209651875492518716600160401b026fffffffffffffffffffffffffffffffff19909316961695909517179094558451918252928101929092529293507fa548576ce23404fb1e2c1f9608435f4859f7d1b46d9497ba9c175554760607ce910160405180910390a250505050611e4c612ad3565b565b611e56613d2e565b611e5e6127e2565b611e6781613d38565b611e7230848461369b565b91508115611ecf57604080516001600160a01b0385811682526020820185905283168183015290517fbb3f74f3539ea7725781ff6810125a75c183f5c944318fc94873d1324f0482ae9181900360600190a1611ecf838383613d5f565b611325612ad3565b60605f5160206151cf5f395f51905f52610f0a7fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30361278a565b7f0000000000000000000000000000000000000000000000000000000000000001611f3a81612ebb565b6001600160a01b038216611f61576040516328346deb60e01b815260040160405180910390fd5b5f5160206151cf5f395f51905f52611f997fe9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30184613d1a565b611fb657604051638599b12960e01b815260040160405180910390fd5b611fc36003820184613c42565b506040516001600160a01b038416907ffc209c9379ca87c40c0d0b988d5a610ab04c00e2a5d79b765521bf7f1ee2e0f3905f90a2505050565b5f6120056127e2565b6001600160a01b03831661202e57604051639cfea58360e01b81525f6004820152602401611371565b5f51602061520f5f395f51905f52336120468161284f565b6001600160a01b0381165f818152600684016020908152604080832081518083018352905467ffffffffffffffff8082168352600160401b909104168184015293835260028601825291829020825160608101845281546001600160801b0381168252600160801b90046001600160681b03169281019290925260019081015464ffffffffff16928201929092529088016120f05780602001516001600160681b0316945061213a565b80602001516001600160681b0316881115612136576020810151604051632cd2c4c760e01b8152600481018a90526001600160681b039091166024820152604401611371565b8794505b845f0361215a576040516352c6c20960e11b815260040160405180910390fd5b85851015612185576040516345b648a360e01b81526004810186905260248101879052604401611371565b81515f90819067ffffffffffffffff16158015906121bd5750835f015167ffffffffffffffff16846020015167ffffffffffffffff16115b90505f8180156121d85750845167ffffffffffffffff164210155b80156121f25750846020015167ffffffffffffffff164211155b638b78c6d8600c9081525f8890526020902054909150600816151581158015612219575080155b15612260576007880154670de0b6b3a76400009061224790600160a01b90046001600160601b03168b61501c565b6122519190615047565b935061225d848a614fd6565b98505b6040805160608101825289546001600160801b0381168252600160801b90046001600160681b03166020820181905260018b015464ffffffffff1692820192909252907f0000000000000000000000000000000000000000000000000000b5e620f48000906122d0908c90614fd6565b10156123b1577f0000000000000000000000000000000000000000000000000000b5e620f4800081602001516001600160681b031661230f9190614fd6565b99507f0000000000000000000000000000000000000000000000000000b5e620f48000858b83602001516001600160681b031661234c9190614fd6565b6123569190614fd6565b10156123b1575f8a7f0000000000000000000000000000000000000000000000000000b5e620f4800083602001516001600160681b03166123979190614fd6565b6123a19190614fd6565b9050808611156123af578095505b505b8315612468576040805180820182525f80825260208083018281526001600160a01b038d1680845260068f0190925284832093518454915167ffffffffffffffff908116600160401b026fffffffffffffffffffffffffffffffff19909316911617179092558951925191927f9dc9167c6c5abda9be1c85b7408de345a2d3126d5eb09143aed42ecf9f2f798f9261245f929067ffffffffffffffff92831681529116602082015260400190565b60405180910390a25b8b6001600160a01b0316886001600160a01b03167f9b1bfa7fa9ee420a16e124f794c35ac9f90472acc99140eb2f6447c714cad8eb8c6040516124ad91815260200190565b60405180910390a3602081018051868c0190036001600160681b031690524264ffffffffff1660408201526124e181613741565b60208681018051878d0190036001600160681b0390811682526001600160a01b038b165f81815260028e01855260408082208c51815496516001600160801b039091166001600160e81b031990971696909617600160801b96909516958602949094178455808c01516001909401805464ffffffffff191664ffffffffff909516949094179093558251938452938301939093527f5fa7d0e13a31540b6d42936e522173de31fa0c53aa5aff71e63c60fe02b2b50e910160405180910390a26125d46001600160a01b037f0000000000000000000000005b66d86932ae5d9751da588d91d494950554061d168d8c613d6f565b841561265a576007890154612616906001600160a01b037f0000000000000000000000005b66d86932ae5d9751da588d91d494950554061d8116911687613d6f565b876001600160a01b03167f21dae94a123f67c07c94c892daa877636785a4c0d964b191ec90df8a48ff27fe8660405161265191815260200190565b60405180910390a25b5050505050505050506111cc612ad3565b7f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a60500543381146126a1576382b429005f526004601cfd5b7f9839bd1b7d13bef2e7a66ce106fd5e418f9f8fee5da4e55d26c2c33ef0bf4800547401ffffffffffffffffffffffffffffffffffffffff811683141560c082901c421117156126f857638cd65fff5f526004601cfd5b505f7f9839bd1b7d13bef2e7a66ce106fd5e418f9f8fee5da4e55d26c2c33ef0bf480055610f2f8183613da0565b5f6001600160e01b031982166307f5828d60e41b1480610e2757506301ffc9a760e01b6001600160e01b0319831614610e27565b5f6001600160e01b03198216632e1546ef60e01b1480610e275750610e2782612726565b5f610ec9848385613df1565b60605f6111cc83613e7b565b610f2f82825f613ed4565b7f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a60500543314611e4c576382b429005f526004601cfd5b610f2f82826001613ed4565b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005c1561282257604051633ee5aeb560e01b815260040160405180910390fd5b611e4c60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005b90613f2b565b5f51602061520f5f395f51905f5261286682613f32565b6001600160a01b03821615610f2f57604080516060808201835283546001600160801b0380821684526001600160681b03600160801b92839004811660208087019190915260018089015464ffffffffff908116888a01526001600160a01b038b165f90815260028b0184528981208a519889018b528054968716808a52979096049094169287018390529301549092169584019590955283519394929361290e929061277e565b905081602001516001600160681b0316816001600160681b03161461298d57846001600160a01b03167f5fa7d0e13a31540b6d42936e522173de31fa0c53aa5aff71e63c60fe02b2b50e828385602001516129699190615066565b604080516001600160681b0393841681529290911660208301520160405180910390a25b6040805160608101825293516001600160801b0390811685526001600160681b03928316602080870191825264ffffffffff4281168886019081526001600160a01b038b165f90815260028b0190935294909120965187549251909516600160801b026001600160e81b0319909216949092169390931792909217845551600190930180549390911664ffffffffff1990931692909217909155505050565b6001600160a01b038281165f9081525f5160206151ef5f395f51905f5260208190526040909120549091168015801590612a6d57506001600160a01b038316155b15612a76578092505b6001600160a01b038316612a88578392505b5f612a91610ed1565b90505f5b8151811015612acb57612ac286838381518110612ab457612ab4614f8f565b602002602001015187612d65565b50600101612a95565b505050505050565b611e4c5f7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00612849565b6001600160a01b0381165f9081525f5160206151cf5f395f51905f5260208181526040808420815160808101835290546001600160601b038116825269ffffffffffffffffffff600160601b8204169382019390935264ffffffffff600160b01b8404811692820192909252600160d81b909204166060820152829190612b8390613c56565b909590945092505050565b306001600160a01b037f00000000000000000000000033db7ed290eb2b8040396b759d25a79a3a7ff88e161480612c2757507f00000000000000000000000033db7ed290eb2b8040396b759d25a79a3a7ff88e6001600160a01b0316612c1b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b6001600160a01b031614155b15611e4c5760405163703e46dd60e11b815260040160405180910390fd5b610f1a6127a1565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015612ca7575060408051601f3d908101601f19168201909252612ca491810190615085565b60015b612ccf57604051634c9c8ce360e01b81526001600160a01b0383166004820152602401611371565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8114612d1257604051632a87526960e21b815260048101829052602401611371565b6113258383614268565b306001600160a01b037f00000000000000000000000033db7ed290eb2b8040396b759d25a79a3a7ff88e1614611e4c5760405163703e46dd60e11b815260040160405180910390fd5b6001600160a01b038381165f9081527f47ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e79026020908152604080832093861683529281528282208351808501909452546001600160801b03808216808652600160801b909204169184019190915290915f5160206151ef5f395f51905f52918015612eb1578151602083018051612dfb90839061509c565b6001600160801b039081169091525f8085526001600160a01b03808b1682526002870160209081526040808420928c168085529282529092208651928701518416600160801b029290931691909117909155612e5991508683613d6f565b846001600160a01b0316866001600160a01b0316886001600160a01b03167fc1405953cccdad6b442e266c84d66ad671e2534c6584f8e6ef92802f7ad294d584604051612ea891815260200190565b60405180910390a45b9695505050505050565b7f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a60500543314610f1a57638b78c6d8600c52335f52806020600c205416610f1a576382b429005f526004601cfd5b6001600160a01b0381165f90815260018301602052604081205415156111cc565b6040516001600160a01b038481166024830152838116604483015260648201839052612fa49186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506142bd565b50505050565b5f5160206151cf5f395f51905f527f0000000000000000000000000000000000000000000000000000000000093a8064ffffffffff161580612ff55750612ff381600101614329565b155b15612ffd5750565b5f61300a8260010161278a565b90505f5b8151811015611325575f82828151811061302a5761302a614f8f565b6020908102919091018101516001600160a01b0381165f9081528683526040808220815160808101835290546001600160601b038116825269ffffffffffffffffffff600160601b8204169582019590955264ffffffffff600160b01b8604811692820192909252600160d81b909404166060840152909250906130ad90613c56565b506001600160a01b0383165f90815260208790526040902080547fffffffffff0000000000ffffffffffffffffffffffffffffffffffffffffffff16600160b01b4264ffffffffff16021790559050801561310c5761310c82826132f0565b505060010161300e565b5f5160206151cf5f395f51905f5264ffffffffff7f0000000000000000000000000000000000000000000000000000000000093a80165f0361315c5761132583836132f0565b6001600160a01b0383165f9081526020828152604091829020825160808101845290546001600160601b038116825269ffffffffffffffffffff600160601b8204169282019290925264ffffffffff600160b01b8304811693820193909352600160d81b90910482166060820152906131f99082907f0000000000000000000000000000000000000000000000000000000000093a801685614332565b6001600160a01b0384165f908152602083815260409182902083518154928501519385015160609095015164ffffffffff908116600160d81b027affffffffffffffffffffffffffffffffffffffffffffffffffffff91909616600160b01b021675ffffffffffffffffffffffffffffffffffffffffffff69ffffffffffffffffffff909516600160601b027fffffffffffffffffffff000000000000000000000000000000000000000000009094166001600160601b0390921691909117929092179290921617919091179055505050565b638b78c6d8600c52335f52806020600c205416610f1a576382b429005f526004601cfd5b805f036132fb575050565b5f5f6133056144ee565b91509150805f0361337c578261333a856001600160a01b03165f9081525f5160206151cf5f395f51905f526020526040902090565b80545f906133529084906001600160601b03166150bb565b92506101000a8154816001600160601b0302191690836001600160601b0316021790555050505050565b6001600160a01b0384165f9081527f47ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e79016020908152604080832060ff607887901c168085529252909120545f5160206151ef5f395f51905f52906001600160c01b031661340b6133f3670de0b6b3a76400008861501c565b6effffffffffffffffffffffffffffff871686614560565b61341590826150da565b6001600160a01b039097165f90815260019092016020908152604080842060ff9095168452939052502080546001600160c01b039095167fffffffffffffffff00000000000000000000000000000000000000000000000090951694909417909355505050565b604080516060810182525f51602061520f5f395f51905f5280546001600160801b0381168352600160801b90046001600160681b0316602083018190527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4015464ffffffffff1693830193909352915f036134f557505050565b7f0000000000000000000000000000000000000000000000000000b5e620f4800081602001516001600160681b031661352e9190614fd6565b8310613570577f0000000000000000000000000000000000000000000000000000b5e620f4800081602001516001600160681b031661356d9190614fd6565b92505b825f0361357c57505050565b5f8061359085670de0b6b3a764000061501c565b9050836005015481116135be5780846005015f8282546135b09190614fd6565b909155505f925061362d9050565b5f8460050154826135cf9190614fd6565b60208501519091506001600160681b03166135eb600183614fd6565b6135f59190615047565b613600906001614fe9565b92508084602001516001600160681b03168461361c919061501c565b6136269190614fd6565b6005860155505b848360200181815161363f9190615066565b6001600160681b03169052505f61365e83670de0b6b3a76400006150f9565b845190915061367a906001600160801b03908116908316614616565b6001600160801b0316845264ffffffffff42166040850152612acb84613741565b5f5f198203613713576040516370a0823160e01b81526001600160a01b0385811660048301528416906370a0823190602401602060405180830381865afa1580156136e8573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061370c9190615085565b9050613716565b50805b805f036111cc5760405163fc2e7f8760e01b81526001600160a01b0384166004820152602401611371565b7fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4045460408201515f51602061520f5f395f51905f52919064ffffffffff167fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4035f6137ac600185614fd6565b815260208101919091526040015f206001015464ffffffffff160361384d5782600383015f6137dc600185614fd6565b815260208082019290925260409081015f2083518154938501516001600160681b0316600160801b026001600160e81b03199094166001600160801b039091161792909217825591909101516001909101805464ffffffffff90921664ffffffffff199092169190911790556138ca565b5f81815260038301602090815260409182902085518154928701516001600160681b0316600160801b026001600160e81b03199093166001600160801b0390911617919091178155908401516001918201805464ffffffffff90921664ffffffffff199092169190911790556138c4908290614fe9565b60048301555b508151815460208401516001600160681b0316600160801b026001600160e81b03199091166001600160801b03909216919091171781556040909101516001909101805464ffffffffff90921664ffffffffff19909216919091179055565b613931614712565b610e10420160c01b81177f9839bd1b7d13bef2e7a66ce106fd5e418f9f8fee5da4e55d26c2c33ef0bf480055610f1a5f33613da0565b611e4c614746565b6001600160a01b038381165f8181527f47ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e7902602090815260408083209487168352938152838220549282527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e402815290839020835160608101855281546001600160801b03808216808452600160801b9092046001600160681b031694830185905260019093015464ffffffffff169190950152909116915f5160206151ef5f395f51905f52918015613c385760ff607883901c165f80613a4b6144ee565b90925090505f613a6f6008613a678660ff607888901c16615118565b60ff1661478f565b6001600160a01b038b165f9081526001808a016020908152604080842060ff8a168552918290529092205492935090916001600160c01b0316905b8360ff168160ff1611613b1c575f8381613ac4848b615131565b60ff16815260208101919091526040015f20546001600160c01b031690508015613b0b57613afe816001600160c01b03168360ff1661479e565b613b0890846150da565b92505b50613b158161514a565b9050613aaa565b505f896002015f8f6001600160a01b03166001600160a01b031681526020019081526020015f205f8e6001600160a01b03166001600160a01b031681526020019081526020015f206001015f0160089054906101000a90046001600160c01b03169050806001600160c01b0316826001600160c01b03161115613be557613bd888613ba78385615168565b6001600160c01b0316613bd3670de0b6b3a76400006effffffffffffffffffffffffffffff8e1661501c565b614560565b613be2908c614fe9565b9a505b8b8015613bf157505f85115b15613c30575f613c008e612afd565b50905085613c18613c118b8461501c565b898d613df1565b613c229190615047565b613c2c908d614fe9565b9b50505b505050505050505b5050509392505050565b5f6111cc836001600160a01b03841661488e565b5f5f5f5f5f9050846060015164ffffffffff16421115613cb657846040015164ffffffffff16856060015164ffffffffff161015613c94575f613ca8565b84604001518560600151613ca89190615187565b64ffffffffff169150613cd7565b846040015164ffffffffff164203915042856060015164ffffffffff160390505b81856020015169ffffffffffffffffffff16613cf3919061501c565b81866020015169ffffffffffffffffffff16613d0f919061501c565b935093505050915091565b5f6111cc836001600160a01b038416614971565b611e4c6002612ebb565b6001600160a01b038116610f1a5760405163d92e233d60e01b815260040160405180910390fd5b6113256001600160a01b03841682845b6040516001600160a01b0383811660248301526044820183905261132591859182169063a9059cbb90606401612f5d565b80827f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f5fa3801560ff1b177f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a605005550565b5f60ff607883811c8216919085901c166effffffffffffffffffffffffffffff808516908616871580613e2957508360ff168360ff16105b80613e4057506008613e3b8585615118565b60ff16115b15613e4d575f9450613e70565b613e6d613e5b898385614560565b613e658686615118565b60ff1661479e565b94505b505050509392505050565b6060815f01805480602002602001604051908101604052809291908181526020018280548015613ec857602002820191905f5260205f20905b815481526020019060010190808311613eb4575b50505050509050919050565b638b78c6d8600c52825f526020600c20805483811783613ef5575080841681185b80835580600c5160601c7f715ad5ce61fc9595c7b415289d59cf203f23a94fa06f04af7e489a0a76e1fe265f5fa3505050505050565b80825d5050565b613f3a612faa565b6001600160a01b03811615610f1a575f613f52610ed1565b90505f613f5d611ed7565b82518151919250905f90613f719083614fe9565b9050805f03613f81575050505050565b5f5160206151ef5f395f51905f525f613f986144ee565b50905060ff607882901c165f5b8481101561425d575f868210613fdd5787613fc08884614fd6565b81518110613fd057613fd0614f8f565b6020026020010151613ff8565b888281518110613fef57613fef614f8f565b60200260200101515b6001600160a01b038b81165f90815260028801602090815260408083209385168352928152828220835160808101855281546001600160801b03808216838801908152600160801b9092041660608301528152845180860190955260019091015467ffffffffffffffff81168552600160401b90046001600160c01b0316848301529081019290925291925090614092908c90849061396f565b815f01515f01906001600160801b031690816001600160801b031681525050856001015f836001600160a01b03166001600160a01b031681526020019081526020015f205f8560ff1660ff1681526020019081526020015f205f9054906101000a90046001600160c01b03168160200151602001906001600160c01b031690816001600160c01b0316815250504281602001515f019067ffffffffffffffff16908167ffffffffffffffff168152505080866002015f8d6001600160a01b03166001600160a01b031681526020019081526020015f205f846001600160a01b03166001600160a01b031681526020019081526020015f205f820151815f015f820151815f015f6101000a8154816001600160801b0302191690836001600160801b031602179055506020820151815f0160106101000a8154816001600160801b0302191690836001600160801b0316021790555050506020820151816001015f820151815f015f6101000a81548167ffffffffffffffff021916908367ffffffffffffffff1602179055506020820151815f0160086101000a8154816001600160c01b0302191690836001600160c01b03160217905550505090505050508080600101915050613fa5565b505050505050505050565b614271826149bd565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a28051156142b5576113258282614a40565b610f2f614ab2565b5f5f60205f8451602086015f885af1806142dc576040513d5f823e3d81fd5b50505f513d915081156142f3578060011415614300565b6001600160a01b0384163b155b15612fa457604051635274afe760e01b81526001600160a01b0385166004820152602401611371565b5f610e27825490565b8251614347906001600160601b031682614fe9565b5f8452606084015190915064ffffffffff1642106143ce5761437161436c8383615047565b614ad1565b69ffffffffffffffffffff166020840181905261438f90839061501c565b6143999082614fd6565b6001600160601b031683524264ffffffffff811660408501526143bd908390614fe9565b64ffffffffff166060840152505050565b5f82846060015164ffffffffff166143e69190614fd6565b6143f09042614fd6565b90505f81856020015169ffffffffffffffffffff1661440f919061501c565b905061441c83600a61501c565b61442782600961501c565b116144d257846040015185606001516144409190615187565b64ffffffffff16856020015169ffffffffffffffffffff16614462919061501c565b61446c9084614fe9565b925061447b61436c8585615047565b69ffffffffffffffffffff166020860181905261449990859061501c565b6144a39084614fd6565b6001600160601b031685526144b88442614fe9565b64ffffffffff9081166060870152421660408601526144e7565b6144db83614b0b565b6001600160601b031685525b5050505050565b604080516060810182525f51602061520f5f395f51905f52546001600160801b038116808352600160801b9091046001600160681b0316602083018190527fcb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e4015464ffffffffff16929093019190915291565b5f838302815f1985870982811083820303915050805f036145945783828161458a5761458a615033565b04925050506111cc565b8084116145ab576145ab6003851502601118614b3e565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f60ff607884901c166effffffffffffffffffffffffffffff84168381028281156146dd57670de0b6b3a764000082046b033b2e3c9fd0803ce80000008110156146d757633b9aca0081101561469b57600181101561468757600482019150670de0b6b3a7640000830292506146db565b600382019150633b9aca00830292506146db565b670de0b6b3a76400008110156146b6576002820191506146db565b600182019150633b9aca0083816146cf576146cf615033565b0492506146db565b8092505b505b607881901b6fff000000000000000000000000000000166effffffffffffffffffffffffffffff831617979650505050505050565b7f61e0b85c03e2cf9c545bde2fb12d0bf5dd6eaae0af8b6909bd36e40f78a605005415611e4c57630dc149f05f526004601cfd5b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff16611e4c57604051631afcd79f60e31b815260040160405180910390fd5b5f8282188284100282186111cc565b5f5f60405180610120016040528060018152602001633b9aca008152602001670de0b6b3a764000081526020016b033b2e3c9fd0803ce800000081526020016ec097ce7bc90715b34b9f10000000008152602001722cd76fe086b93ce2f768a00b22a000000000008152602001760a70c3c40a64e6c51999090b65f67d924000000000000081526020017a026e4d30eccc3215dd8f3157d27e23acbdcfe6800000000000000081526020017d90e40fbeea1d3a4abc8955e946fe31cdcf66f634e1000000000000000000815250905080836009811061487f5761487f614f8f565b6020020151610ec99085615047565b5f8181526001830160205260408120548015614968575f6148b0600183614fd6565b85549091505f906148c390600190614fd6565b9050808214614922575f865f0182815481106148e1576148e1614f8f565b905f5260205f200154905080875f01848154811061490157614901614f8f565b5f918252602080832090910192909255918252600188019052604090208390555b8554869080614933576149336151a4565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050610e27565b5f915050610e27565b5f8181526001830160205260408120546149b657508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610e27565b505f610e27565b806001600160a01b03163b5f036149f257604051634c9c8ce360e01b81526001600160a01b0382166004820152602401611371565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b60605f5f846001600160a01b031684604051614a5c91906151b8565b5f60405180830381855af49150503d805f8114614a94576040519150601f19603f3d011682016040523d82523d5f602084013e614a99565b606091505b5091509150614aa9858383614b4f565b95945050505050565b3415611e4c5760405163b398979f60e01b815260040160405180910390fd5b5f69ffffffffffffffffffff821115614b07576040516306dfcc6560e41b81526050600482015260248101839052604401611371565b5090565b5f6001600160601b03821115614b07576040516306dfcc6560e41b81526060600482015260248101839052604401611371565b634e487b715f52806020526024601cfd5b606082614b6457614b5f82614bab565b6111cc565b8151158015614b7b57506001600160a01b0384163b155b15614ba457604051639996b31560e01b81526001600160a01b0385166004820152602401611371565b50806111cc565b805115614bbb5780518082602001fd5b60405163d6bda27560e01b815260040160405180910390fd5b5f60208284031215614be4575f5ffd5b81356001600160e01b0319811681146111cc575f5ffd5b80356001600160a01b0381168114614c11575f5ffd5b919050565b5f60208284031215614c26575f5ffd5b6111cc82614bfb565b602080825282518282018190525f918401906040840190835b81811015614c6f5783516001600160a01b0316835260209384019390920191600101614c48565b509095945050505050565b5f5f60408385031215614c8b575f5ffd5b614c9483614bfb565b9150614ca260208401614bfb565b90509250929050565b5f60208284031215614cbb575f5ffd5b5035919050565b5f5f60408385031215614cd3575f5ffd5b614cdc83614bfb565b946020939093013593505050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715614d2757614d27614cea565b604052919050565b5f5f60408385031215614d40575f5ffd5b614d4983614bfb565b9150602083013567ffffffffffffffff811115614d64575f5ffd5b8301601f81018513614d74575f5ffd5b803567ffffffffffffffff811115614d8e57614d8e614cea565b614da1601f8201601f1916602001614cfe565b818152866020838501011115614db5575f5ffd5b816020840160208301375f602083830101528093505050509250929050565b5f82601f830112614de3575f5ffd5b813567ffffffffffffffff811115614dfd57614dfd614cea565b8060051b614e0d60208201614cfe565b91825260208185018101929081019086841115614e28575f5ffd5b6020860192505b83831015612eb157614e4083614bfb565b825260209283019290910190614e2f565b5f60208284031215614e61575f5ffd5b813567ffffffffffffffff811115614e77575f5ffd5b610ec984828501614dd4565b5f5f60408385031215614e94575f5ffd5b614e9d83614bfb565b9150602083013567ffffffffffffffff811115614eb8575f5ffd5b614ec485828601614dd4565b9150509250929050565b5f5f60408385031215614edf575f5ffd5b50508035926020909101359150565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b5f5f5f60608486031215614f35575f5ffd5b83359250614f4560208501614bfb565b929592945050506040919091013590565b5f5f5f60608486031215614f68575f5ffd5b614f7184614bfb565b925060208401359150614f8660408501614bfb565b90509250925092565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b6001600160681b038181168382160190811115610e2757610e27614fa3565b81810381811115610e2757610e27614fa3565b80820180821115610e2757610e27614fa3565b67ffffffffffffffff8181168382160190811115610e2757610e27614fa3565b8082028115828204841417610e2757610e27614fa3565b634e487b7160e01b5f52601260045260245ffd5b5f8261506157634e487b7160e01b5f52601260045260245ffd5b500490565b6001600160681b038281168282160390811115610e2757610e27614fa3565b5f60208284031215615095575f5ffd5b5051919050565b6001600160801b038181168382160190811115610e2757610e27614fa3565b6001600160601b038181168382160190811115610e2757610e27614fa3565b6001600160c01b038181168382160190811115610e2757610e27614fa3565b6001600160801b038281168282160390811115610e2757610e27614fa3565b60ff8281168282160390811115610e2757610e27614fa3565b60ff8181168382160190811115610e2757610e27614fa3565b5f60ff821660ff810361515f5761515f614fa3565b60010192915050565b6001600160c01b038281168282160390811115610e2757610e27614fa3565b64ffffffffff8281168282160390811115610e2757610e27614fa3565b634e487b7160e01b5f52603160045260245ffd5b5f82518060208501845e5f92019182525091905056fee9dd8489e2940f6fb582767a094c112cfce2739b7a5f3357b085cab0a6a7d30047ddc56aaabfe9761e2e64ce86720771c5fd1fd7ef0605da74e07d71de0e7900cb62d703974340239a82baeadff6ad7af3673eb85d9779bde2587fc9e0e3e400a2646970667358221220b0fc72ba6b94f082a8f3ccc2dc3fa9fec25897070a40bd69269aa99f9936ed2264736f6c634300081e0033
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 34 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.