Source Code
Latest 25 from a total of 4,910 transactions
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Multicall | 44484144 | 4 days ago | IN | 0 ETH | 0.00000411 | ||||
| Claim Rewards | 44178232 | 11 days ago | IN | 0 ETH | 0.0000006 | ||||
| Claim Rewards | 44178222 | 11 days ago | IN | 0 ETH | 0.00000076 | ||||
| Claim Rewards | 44178215 | 11 days ago | IN | 0 ETH | 0.00000155 | ||||
| Claim Rewards | 44079735 | 14 days ago | IN | 0 ETH | 0.00000053 | ||||
| Claim Rewards | 44079728 | 14 days ago | IN | 0 ETH | 0.00000081 | ||||
| Multicall | 43887823 | 18 days ago | IN | 0 ETH | 0.0000187 | ||||
| Multicall | 43789281 | 20 days ago | IN | 0 ETH | 0.00000383 | ||||
| Multicall | 43715085 | 22 days ago | IN | 0 ETH | 0.0000143 | ||||
| Claim Rewards | 43715074 | 22 days ago | IN | 0 ETH | 0.00000188 | ||||
| Multicall | 43702582 | 22 days ago | IN | 0 ETH | 0.00001983 | ||||
| Multicall | 43639873 | 24 days ago | IN | 0 ETH | 0.00000319 | ||||
| Claim Rewards | 43639855 | 24 days ago | IN | 0 ETH | 0.00000102 | ||||
| Multicall | 43323997 | 31 days ago | IN | 0 ETH | 0.000024 | ||||
| Multicall | 43261954 | 33 days ago | IN | 0 ETH | 0.00001062 | ||||
| Multicall | 43021398 | 38 days ago | IN | 0 ETH | 0.00001715 | ||||
| Multicall | 42742682 | 45 days ago | IN | 0 ETH | 0.00001727 | ||||
| Claim Rewards | 42711922 | 45 days ago | IN | 0 ETH | 0.00000141 | ||||
| Claim Rewards | 42711903 | 45 days ago | IN | 0 ETH | 0.00000219 | ||||
| Claim Rewards | 42711890 | 45 days ago | IN | 0 ETH | 0.00000185 | ||||
| Multicall | 42701368 | 46 days ago | IN | 0 ETH | 0.0000222 | ||||
| Multicall | 42654250 | 47 days ago | IN | 0 ETH | 0.00000689 | ||||
| Multicall | 42623646 | 47 days ago | IN | 0 ETH | 0.00001928 | ||||
| Claim Rewards | 42555988 | 49 days ago | IN | 0 ETH | 0.00000083 | ||||
| Multicall | 42543778 | 49 days ago | IN | 0 ETH | 0.00000528 |
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.
Contract Name:
PrizePoolTwabRewards
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
No with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { IERC20 } from "openzeppelin-contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeCast } from "openzeppelin-contracts/utils/math/SafeCast.sol";
import { Multicall } from "openzeppelin-contracts/utils/Multicall.sol";
import { TwabController } from "pt-v5-twab-controller/TwabController.sol";
import { IPrizePool } from "./external/IPrizePool.sol";
import { IPrizePoolTwabRewards, Promotion } from "./interfaces/IPrizePoolTwabRewards.sol";
import { ITwabRewards } from "./interfaces/ITwabRewards.sol";
/* ============ Custom Errors ============ */
/// @notice Thrown when the TwabController address set in the constructor is the zero address.
error TwabControllerZeroAddress();
/// @notice Thrown when a promotion is created with an emission of zero tokens per epoch.
error ZeroTokensPerEpoch();
/// @notice Thrown when the number of epochs is zero when it must be greater than zero.
error ZeroEpochs();
/// @notice Thrown if the tokens received at the creation of a promotion is less than the expected amount.
/// @param received The amount of tokens received
/// @param expected The expected amount of tokens
error TokensReceivedLessThanExpected(uint256 received, uint256 expected);
/// @notice Thrown if the address to receive tokens from ending or destroying a promotion is the zero address.
error PayeeZeroAddress();
/// @notice Thrown if an action cannot be completed while the grace period is active.
/// @param gracePeriodEndTimestamp The end timestamp of the grace period
error GracePeriodActive(uint256 gracePeriodEndTimestamp);
/// @notice Thrown if a promotion extension would exceed the max number of epochs.
/// @param epochExtension The number of epochs to extend the promotion by
/// @param currentEpochs The current number of epochs in the promotion
/// @param maxEpochs The max number of epochs that a promotion can have
error ExceedsMaxEpochs(uint8 epochExtension, uint8 currentEpochs, uint8 maxEpochs);
/// @notice Thrown if a promotion is no longer active.
/// @param promotionId The ID of the promotion
error PromotionInactive(uint256 promotionId);
/// @notice Thrown if the sender is not the promotion creator on a creator-only action.
/// @param sender The address of the sender
/// @param creator The address of the creator
error OnlyPromotionCreator(address sender, address creator);
/// @notice Thrown if the rewards for an epoch are being claimed before the epoch is over.
/// @param epochEndTimestamp The time at which the epoch will end
error EpochNotOver(uint64 epochEndTimestamp);
/// @notice Thrown if an epoch is outside the range of epochs in a promotion.
/// @param epochId The ID of the epoch
/// @param numberOfEpochs The number of epochs in the promotion
error InvalidEpochId(uint8 epochId, uint8 numberOfEpochs);
/// @notice Thrown if the given prize pool address is zero
error PrizePoolZeroAddress();
/// @notice Thrown when the epoch duration is less than the draw period.
error EpochDurationLtDrawPeriod();
/// @notice Thrown when the epoch duration is not a multiple of the draw period.
error EpochDurationNotMultipleOfDrawPeriod();
/// @notice Thrown when the start time is less than the first draw opens at time.
error StartTimeLtFirstDrawOpensAt();
/// @notice Thrown when the start time is not aligned with the draws.
error StartTimeNotAlignedWithDraws();
/// @notice Thrown when there are no epochs available to claim
error NoEpochsToClaim(uint8 startEpochId, uint8 currentEpochId);
/**
* @title PoolTogether V5 PrizePoolTwabRewards
* @author G9 Software Inc.
* @notice Contract to distribute rewards to depositors across all vaults that contribute to a Prize Pool.
* The contract supports multiple reward "promotions". Each promotion can define a different reward token,
* start time, epoch duration, and number of epochs. Promotions divide time into evenly sized epochs; and users
* can claim rewards for each epoch. The amount each user gets is based on their portion of the Vault twab * vault contribution,
* where the vault contribution is fraction of prize pool prizes that the vault contributed during the epoch.
* @dev This contract does not support the use of fee on transfer tokens.
* @dev This contract does not support the use of rebasing tokens.
* @dev This contract does not support tokens with rounding errors on transfers (such as stETH)
*/
contract PrizePoolTwabRewards is IPrizePoolTwabRewards, Multicall {
using SafeERC20 for IERC20;
using SafeCast for uint256;
/* ============ Global Variables ============ */
/// @notice TwabController contract from which the promotions read time-weighted average balances from.
TwabController public immutable twabController;
/// @notice The Prize Pool used to compute the vault contributions.
IPrizePool public immutable prizePool;
/// @notice Cached draw period seconds from the prize pool.
uint48 internal immutable _drawPeriodSeconds;
/// @notice Cached first draw opens at timestamp from the prize pool.
uint48 internal immutable _firstDrawOpensAt;
/// @notice The special SPONSORSHIP address constant used in the TwabController.
address public constant SPONSORSHIP_ADDRESS = address(1);
/// @notice Period during which the promotion owner can't destroy a promotion.
uint32 public constant GRACE_PERIOD = 60 days;
/// @notice Settings of each promotion.
mapping(uint256 => Promotion) internal _promotions;
/// @notice Creator of each promotion
mapping(uint256 => address) public promotionCreators;
/**
* @notice Latest recorded promotion id.
* @dev Starts at 0 and is incremented by 1 for each new promotion. So the first promotion will have id 1, the second 2, etc.
*/
uint256 public latestPromotionId;
/**
* @notice Keeps track of claimed rewards per user.
* @dev claimedEpochs[promotionId][user] => claimedEpochs
* @dev We pack epochs claimed by a user into a uint256. So we can't store more than 256 epochs.
*/
mapping(uint256 promotionId => mapping(address vault => mapping(address user => bytes32 claimMask))) public claimedEpochs;
/**
* @notice Cache of each epoch total contribution amount.
* @dev Max number of epochs is 256, so limited it appropriately. Prize Pool draw contributions are stored as uint160, but 128 bits should give us plenty of overhead.
*/
mapping(uint256 promotionId => EpochCache[256]) internal _epochCaches;
/**
* @notice Cache of each vault's epoch total supply and contribution to the prize pool.
* @dev Max number of epochs is 256, so limited it appropriately. Twab Controller supply limit is 96bits, so we can store it in a uint96.
*/
mapping(uint256 promotionId => mapping(address vault => VaultEpochCache[256])) internal _vaultEpochCaches;
struct EpochCache {
uint128 totalContributed;
}
struct VaultEpochCache {
uint128 totalSupply;
uint128 contributed;
}
/* ============ Events ============ */
/**
* @notice Emitted when a promotion is created.
* @param promotionId Id of the newly created promotion
* @param token The token that will be rewarded from the promotion
* @param startTimestamp The timestamp at which the promotion starts
* @param tokensPerEpoch The number of tokens emitted per epoch
* @param epochDuration The duration of epoch in seconds
* @param initialNumberOfEpochs The initial number of epochs the promotion is set to run for
*/
event PromotionCreated(
uint256 indexed promotionId,
IERC20 indexed token,
uint40 startTimestamp,
uint104 tokensPerEpoch,
uint40 epochDuration,
uint8 initialNumberOfEpochs
);
/**
* @notice Emitted when a promotion is ended.
* @param promotionId Id of the promotion being ended
* @param recipient Address of the recipient that will receive the remaining rewards
* @param amount Amount of tokens transferred to the recipient
* @param epochNumber Epoch number at which the promotion ended
*/
event PromotionEnded(uint256 indexed promotionId, address indexed recipient, uint256 amount, uint8 epochNumber);
/**
* @notice Emitted when a promotion is destroyed.
* @param promotionId Id of the promotion being destroyed
* @param recipient Address of the recipient that will receive the unclaimed rewards
* @param amount Amount of tokens transferred to the recipient
*/
event PromotionDestroyed(uint256 indexed promotionId, address indexed recipient, uint256 amount);
/**
* @notice Emitted when a promotion is extended.
* @param promotionId Id of the promotion being extended
* @param numberOfEpochs Number of epochs the promotion has been extended by
*/
event PromotionExtended(uint256 indexed promotionId, uint256 numberOfEpochs);
/**
* @notice Emitted when rewards have been claimed.
* @param promotionId Id of the promotion for which epoch rewards were claimed
* @param epochClaimFlags Word representing which epochs were claimed
* @param user Address of the user for which the rewards were claimed
* @param amount Amount of tokens transferred to the recipient address
*/
event RewardsClaimed(uint256 indexed promotionId, bytes32 epochClaimFlags, address indexed vault, address indexed user, uint256 amount);
/* ============ Constructor ============ */
/**
* @notice Constructor of the contract.
* @param _twabController The TwabController contract to reference for vault balance and supply
* @param _prizePool The PrizePool contract to use for prize contributions
*/
constructor(TwabController _twabController, IPrizePool _prizePool) {
if (address(0) == address(_twabController)) revert TwabControllerZeroAddress();
if (address(0) == address(_prizePool)) revert PrizePoolZeroAddress();
twabController = _twabController;
prizePool = _prizePool;
_drawPeriodSeconds = prizePool.drawPeriodSeconds();
_firstDrawOpensAt = prizePool.firstDrawOpensAt();
}
/* ============ External Functions ============ */
/**
* @inheritdoc IPrizePoolTwabRewards
* @dev For sake of simplicity, `msg.sender` will be the creator of the promotion.
* @dev `_latestPromotionId` starts at 0 and is incremented by 1 for each new promotion.
* So the first promotion will have id 1, the second 2, etc.
* @dev The transaction will revert if the amount of reward tokens provided is not equal to `_tokensPerEpoch * _numberOfEpochs`.
* This scenario could happen if the token supplied is a fee on transfer one.
*/
function createPromotion(
IERC20 _token,
uint40 _startTimestamp,
uint104 _tokensPerEpoch,
uint40 _epochDuration,
uint8 _numberOfEpochs
) external override returns (uint256) {
if (_tokensPerEpoch == 0) revert ZeroTokensPerEpoch();
_requireNumberOfEpochs(_numberOfEpochs);
if (_epochDuration < _drawPeriodSeconds) revert EpochDurationLtDrawPeriod();
if (_epochDuration % _drawPeriodSeconds != 0) revert EpochDurationNotMultipleOfDrawPeriod();
if (_startTimestamp < _firstDrawOpensAt) revert StartTimeLtFirstDrawOpensAt();
if ((_startTimestamp - _firstDrawOpensAt) % _drawPeriodSeconds != 0) revert StartTimeNotAlignedWithDraws();
// ensure that this contract isn't eligible to win any prizes
if (twabController.delegateOf(address(_token), address(this)) != SPONSORSHIP_ADDRESS) {
twabController.delegate(address(_token), SPONSORSHIP_ADDRESS);
}
uint256 _nextPromotionId = latestPromotionId + 1;
latestPromotionId = _nextPromotionId;
uint112 unclaimedRewards = SafeCast.toUint112(uint(_tokensPerEpoch) * uint(_numberOfEpochs));
promotionCreators[_nextPromotionId] = msg.sender;
_promotions[_nextPromotionId] = Promotion({
startTimestamp: _startTimestamp,
numberOfEpochs: _numberOfEpochs,
epochDuration: _epochDuration,
createdAt: SafeCast.toUint40(block.timestamp),
token: _token,
tokensPerEpoch: _tokensPerEpoch,
rewardsUnclaimed: unclaimedRewards
});
uint256 _beforeBalance = _token.balanceOf(address(this));
_token.safeTransferFrom(msg.sender, address(this), unclaimedRewards);
uint256 _afterBalance = _token.balanceOf(address(this));
if (_afterBalance < _beforeBalance + unclaimedRewards)
revert TokensReceivedLessThanExpected(_afterBalance - _beforeBalance, unclaimedRewards);
emit PromotionCreated(
_nextPromotionId,
_token,
_startTimestamp,
_tokensPerEpoch,
_epochDuration,
_numberOfEpochs
);
return _nextPromotionId;
}
/// @inheritdoc IPrizePoolTwabRewards
function endPromotion(uint256 _promotionId, address _to) external override returns (bool) {
if (address(0) == _to) revert PayeeZeroAddress();
Promotion memory _promotion = _getPromotion(_promotionId);
_requirePromotionCreator(promotionCreators[_promotionId]);
_requirePromotionActive(_promotionId, _promotion);
uint8 _epochNumber = _getEpochIdNow(_promotion.startTimestamp, _promotion.epochDuration);
_promotions[_promotionId].numberOfEpochs = _epochNumber;
uint112 _remainingRewards = _getRemainingRewards(_promotion);
_promotions[_promotionId].rewardsUnclaimed = _promotion.rewardsUnclaimed - _remainingRewards;
_promotion.token.safeTransfer(_to, _remainingRewards);
emit PromotionEnded(_promotionId, _to, _remainingRewards, _epochNumber);
return true;
}
/// @inheritdoc IPrizePoolTwabRewards
function destroyPromotion(uint256 _promotionId, address _to) external override returns (bool) {
if (address(0) == _to) revert PayeeZeroAddress();
Promotion memory _promotion = _getPromotion(_promotionId);
_requirePromotionCreator(promotionCreators[_promotionId]);
uint256 _promotionEndTimestamp = _getPromotionEndTimestamp(_promotion);
uint256 _promotionCreatedAt = _promotion.createdAt;
uint256 _gracePeriodEndTimestamp = (
_promotionEndTimestamp < _promotionCreatedAt ? _promotionCreatedAt : _promotionEndTimestamp
) + GRACE_PERIOD;
if (block.timestamp < _gracePeriodEndTimestamp) revert GracePeriodActive(_gracePeriodEndTimestamp);
uint256 _rewardsUnclaimed = _promotion.rewardsUnclaimed;
delete _promotions[_promotionId];
_promotion.token.safeTransfer(_to, _rewardsUnclaimed);
emit PromotionDestroyed(_promotionId, _to, _rewardsUnclaimed);
return true;
}
/// @inheritdoc IPrizePoolTwabRewards
function extendPromotion(uint256 _promotionId, uint8 _numberOfEpochs) external override returns (bool) {
_requireNumberOfEpochs(_numberOfEpochs);
Promotion memory _promotion = _getPromotion(_promotionId);
_requirePromotionActive(_promotionId, _promotion);
uint8 _currentNumberOfEpochs = _promotion.numberOfEpochs;
if (_numberOfEpochs > (type(uint8).max - _currentNumberOfEpochs))
revert ExceedsMaxEpochs(_numberOfEpochs, _currentNumberOfEpochs, type(uint8).max);
_promotions[_promotionId].numberOfEpochs = _currentNumberOfEpochs + _numberOfEpochs;
uint112 _amount = SafeCast.toUint112(uint(_numberOfEpochs) * uint(_promotion.tokensPerEpoch));
_promotions[_promotionId].rewardsUnclaimed = _promotion.rewardsUnclaimed + _amount;
_promotion.token.safeTransferFrom(msg.sender, address(this), _amount);
emit PromotionExtended(_promotionId, _numberOfEpochs);
return true;
}
/// @inheritdoc IPrizePoolTwabRewards
function claimRewards(
address _vault,
address _user,
uint256 _promotionId,
uint8[] calldata _epochIds
) external override returns (uint256) {
bytes32 _epochClaimFlags = epochIdArrayToBytes(_epochIds);
return _claimRewards(_vault, _user, _promotionId, _epochClaimFlags, 0);
}
/**
* @notice Pass through to claim regular Twab Rewards. This is intended to allow single tx claiming by EOAs using the built-in Multicall
* @param _twabRewards TwabRewards contract to claim rewards from
* @param _user User to claim rewards for
* @param _promotionId Promotion to claim rewards for
* @param _epochIds Epoch ids to claim rewards for
* @return Total amount of rewards claimed
*/
function claimTwabRewards(
ITwabRewards _twabRewards, address _user, uint256 _promotionId, uint8[] calldata _epochIds
) external returns (uint256) {
return _twabRewards.claimRewards(_user, _promotionId, _epochIds);
}
/// @inheritdoc IPrizePoolTwabRewards
function claimRewardedEpochs(
address _vault,
address _user,
uint256 _promotionId,
uint8 _startEpochId
) public returns (uint256) {
bytes32 _epochClaimFlags;
uint8 endEpochId = getEpochIdNow(_promotionId);
if (!(endEpochId > _startEpochId)) revert NoEpochsToClaim(_startEpochId, endEpochId);
for (uint8 index = _startEpochId; index < endEpochId; index++) {
_epochClaimFlags = _setBit(_epochClaimFlags, index);
}
return _claimRewards(_vault, _user, _promotionId, _epochClaimFlags, _startEpochId);
}
/**
* @notice Calculate rewards for a given vault, user, promotion and epoch ids.
* @param _vault Vault to calculate rewards for
* @param _user User to calculate rewards for
* @param _promotionId Promotion to calculate rewards for
* @param _epochIds Epoch ids to calculate rewards for
* @return rewards Array of reward amounts for each epoch
*/
function calculateRewards(
address _vault,
address _user,
uint256 _promotionId,
uint8[] calldata _epochIds
) external returns (uint256[] memory rewards) {
rewards = new uint256[](_epochIds.length);
Promotion memory promotion = _getPromotion(_promotionId);
for (uint256 index = 0; index < _epochIds.length; ++index) {
rewards[index] = _calculateRewardAmount(_vault, _user, _promotionId, promotion, _epochIds[index]);
}
}
/**
* @notice Get reward amount for a given vault
* @dev Rewards can only be calculated once the epoch is over.
* @dev Will revert if `_epochId` is not in the past.
* @param _vault Vault to get reward amount for
* @param _promotionId Promotion from which the epoch is
* @param _epochId Epoch id to get reward amount for
* @return Reward amount
*/
function getVaultRewardAmount(
address _vault,
uint256 _promotionId,
uint8 _epochId
) public returns (uint128) {
Promotion memory promotion = _getPromotion(_promotionId);
(
uint48 _epochStartTimestamp,
uint48 _epochEndTimestamp,
uint24 _epochStartDrawId,
uint24 _epochEndDrawId
) = epochRanges(promotion.startTimestamp, promotion.epochDuration, _epochId);
_validateEpoch(_epochId, promotion.numberOfEpochs, _epochEndTimestamp);
VaultEpochCache memory vaultEpochCache = _getVaultEpochCache(_promotionId, _epochId, _vault, _epochStartTimestamp, _epochEndTimestamp, _epochStartDrawId, _epochEndDrawId);
if (vaultEpochCache.contributed == 0) {
return 0;
}
EpochCache memory epochCache = _getEpochCache(_promotionId, _epochId, _epochStartDrawId, _epochEndDrawId);
uint256 numerator = uint256(promotion.tokensPerEpoch) * uint256(vaultEpochCache.contributed);
uint256 denominator = uint256(epochCache.totalContributed);
return SafeCast.toUint128(numerator / denominator);
}
/// @inheritdoc IPrizePoolTwabRewards
function getPromotion(uint256 _promotionId) external view override returns (Promotion memory) {
return _getPromotion(_promotionId);
}
/// @inheritdoc IPrizePoolTwabRewards
/// @dev Epoch ids and their boolean values are tightly packed and stored in a uint256, so epoch id starts at 0.
function getEpochIdNow(uint256 _promotionId) public view override returns (uint8) {
Promotion memory _promotion = _getPromotion(_promotionId);
return _getEpochIdNow(_promotion.startTimestamp, _promotion.epochDuration);
}
/// @inheritdoc IPrizePoolTwabRewards
function getEpochIdAt(uint256 _promotionId, uint256 _timestamp) public view override returns (uint8) {
Promotion memory _promotion = _getPromotion(_promotionId);
return _getEpochIdAt(_promotion.startTimestamp, _promotion.epochDuration, _timestamp);
}
/// @inheritdoc IPrizePoolTwabRewards
function getRemainingRewards(uint256 _promotionId) external view override returns (uint128) {
return _getRemainingRewards(_getPromotion(_promotionId));
}
/**
* @notice Calculate the draw id at a specific timestamp. Draw ids start at 1.
* @param _timestamp Timestamp to calculate the draw id at
* @return Draw id
*/
function calculateDrawIdAt(uint64 _timestamp) public view returns (uint24) {
// NOTE: Prize Pool draw ids start at 1; that's why we have to add one below.
if (_timestamp < _firstDrawOpensAt) return 0;
else return uint24((_timestamp - _firstDrawOpensAt) / _drawPeriodSeconds) + 1;
}
/**
* @notice Get the time and draw ranges for an epoch
* @param _promotionId Id of the promotion
* @param _epochId Id of the epoch to get the ranges for
* @return epochStartTimestamp Start timestamp of the epoch
* @return epochEndTimestamp End timestamp of the epoch
* @return epochStartDrawId Start draw id of the epoch
* @return epochEndDrawId End draw id of the epoch
*/
function epochRangesForPromotion(
uint256 _promotionId,
uint8 _epochId
) public view returns (
uint48 epochStartTimestamp,
uint48 epochEndTimestamp,
uint24 epochStartDrawId,
uint24 epochEndDrawId
) {
Promotion memory promotion = _promotions[_promotionId];
return epochRanges(promotion.startTimestamp, promotion.epochDuration, _epochId);
}
/**
* @notice Get the time and draw ranges for an epoch
* @param _promotionStartTimestamp Start timestamp of the promotion
* @param _promotionEpochDuration Duration of an epoch in the promotion
* @param _epochId Id of the epoch to get the ranges for
* @return epochStartTimestamp Start timestamp of the epoch
* @return epochEndTimestamp End timestamp of the epoch
* @return epochStartDrawId Start draw id of the epoch
* @return epochEndDrawId End draw id of the epoch
*/
function epochRanges(
uint48 _promotionStartTimestamp,
uint48 _promotionEpochDuration,
uint8 _epochId
) public view returns (
uint48 epochStartTimestamp,
uint48 epochEndTimestamp,
uint24 epochStartDrawId,
uint24 epochEndDrawId
) {
epochStartTimestamp = _promotionStartTimestamp + (_promotionEpochDuration * _epochId);
epochEndTimestamp = epochStartTimestamp + _promotionEpochDuration;
epochStartDrawId = calculateDrawIdAt(epochStartTimestamp);
epochEndDrawId = epochStartDrawId + uint24(_promotionEpochDuration / _drawPeriodSeconds) - 1;
}
/**
* @notice Convert an array of epoch ids to a bytes32 word.
* @param _epochIds Array of epoch ids to convert
* @return Tightly Word where each bit represents an epoch
*/
function epochIdArrayToBytes(uint8[] calldata _epochIds) public pure returns (bytes32) {
bytes32 _epochClaimFlags;
for (uint256 index = 0; index < _epochIds.length; ++index) {
_epochClaimFlags = _setBit(_epochClaimFlags, _epochIds[index]);
}
return _epochClaimFlags;
}
/**
* @notice Converts a bytes32 to an array of epoch ids
* @param _epochClaimFlags Word where each bit represents an epoch
* @return Array of epoch ids
*/
function epochBytesToIdArray(bytes32 _epochClaimFlags) public pure returns (uint8[] memory) {
uint8 count;
for (uint256 epoch = 0; epoch < 256; ++epoch) {
if (_isBitSet(_epochClaimFlags, uint8(epoch))) {
++count;
}
}
uint8[] memory _epochIds = new uint8[](count);
uint8 idsIndex = 0;
for (uint256 epoch = 0; epoch < 256; ++epoch) {
if (_isBitSet(_epochClaimFlags, uint8(epoch))) {
_epochIds[idsIndex++] = uint8(epoch);
}
}
return _epochIds;
}
/* ============ Internal Functions ============ */
/**
* @notice Claim rewards for a given promotion and epoch.
* @param _vault Address of the vault
* @param _user Address of the user
* @param _promotionId Id of the promotion
* @param _epochsToClaim Word representing which epochs to claim
* @param startEpochId Id of the epoch to start claiming rewards from
* @return Amount of tokens transferred to the recipient address
*/
function _claimRewards(
address _vault,
address _user,
uint256 _promotionId,
bytes32 _epochsToClaim,
uint8 startEpochId
) internal returns (uint256) {
Promotion memory _promotion = _promotions[_promotionId];
uint256 _rewardsAmount;
bytes32 _alreadyClaimedEpochs = claimedEpochs[_promotionId][_vault][_user];
// Ignore epochs already claimed
_epochsToClaim = _epochsToClaim & ~_alreadyClaimedEpochs;
for (uint256 index = startEpochId; index < 256; ++index) {
if (_isBitSet(_epochsToClaim, uint8(index))) {
_rewardsAmount += _calculateRewardAmount(_vault, _user, _promotionId, _promotion, uint8(index));
}
}
claimedEpochs[_promotionId][_vault][_user] = _alreadyClaimedEpochs | _epochsToClaim;
_promotions[_promotionId].rewardsUnclaimed = SafeCast.toUint112(uint(_promotion.rewardsUnclaimed) - uint(_rewardsAmount));
_promotion.token.safeTransfer(_user, _rewardsAmount);
emit RewardsClaimed(_promotionId, _epochsToClaim, _vault, _user, _rewardsAmount);
return _rewardsAmount;
}
/**
* @notice Allow a promotion to be created or extended only by a positive number of epochs.
* @param _numberOfEpochs Number of epochs to check
*/
function _requireNumberOfEpochs(uint8 _numberOfEpochs) internal pure {
if (0 == _numberOfEpochs) revert ZeroEpochs();
}
/**
* @notice Requires that a promotion is active.
* @param _promotion Promotion to check
*/
function _requirePromotionActive(uint256 _promotionId, Promotion memory _promotion) internal view {
if (_getPromotionEndTimestamp(_promotion) <= block.timestamp) revert PromotionInactive(_promotionId);
}
/**
* @notice Requires that msg.sender is the promotion creator.
* @param creator Creator of the promotion
*/
function _requirePromotionCreator(address creator) internal view {
if (msg.sender != creator) revert OnlyPromotionCreator(msg.sender, creator);
}
/**
* @notice Get settings for a specific promotion.
* @dev Will revert if the promotion does not exist.
* @param _promotionId Promotion id to get settings for
* @return Promotion settings
*/
function _getPromotion(uint256 _promotionId) internal view returns (Promotion memory) {
Promotion memory _promotion = _promotions[_promotionId];
return _promotion;
}
/**
* @notice Compute promotion end timestamp.
* @param _promotion Promotion to compute end timestamp for
* @return Promotion end timestamp
*/
function _getPromotionEndTimestamp(Promotion memory _promotion) internal pure returns (uint256) {
unchecked {
return _promotion.startTimestamp + (_promotion.epochDuration * _promotion.numberOfEpochs);
}
}
/**
* @notice Get the current epoch id of a promotion.
* @dev Epoch ids and their boolean values are tightly packed and stored in a uint256, so epoch id starts at 0.
* @dev We return the current epoch id if the promotion has not ended.
* If the current timestamp is before the promotion start timestamp, we return 0.
* Otherwise, we return the epoch id at the current timestamp. This could be greater than the number of epochs of the promotion.
* @param _promotionStartTimestamp Start timestamp of the promotion
* @param _promotionEpochDuration Duration of an epoch for the promotion
* @return Epoch id
*/
function _getEpochIdNow(uint256 _promotionStartTimestamp, uint256 _promotionEpochDuration) internal view returns (uint8) {
return _getEpochIdAt(_promotionStartTimestamp, _promotionEpochDuration, block.timestamp);
}
/**
* @notice Get the epoch id at a specific timestamp.
* @param _promotionStartTimestamp Start timestamp of the promotion
* @param _promotionEpochDuration Duration of an epoch for the promotion
* @param _timestamp Timestamp to get the epoch id for
*/
function _getEpochIdAt(uint256 _promotionStartTimestamp, uint256 _promotionEpochDuration, uint256 _timestamp) internal pure returns (uint8) {
uint256 _currentEpochId;
if (_timestamp > _promotionStartTimestamp) {
unchecked {
_currentEpochId = (_timestamp - _promotionStartTimestamp) / _promotionEpochDuration;
}
}
return _currentEpochId > type(uint8).max ? type(uint8).max : uint8(_currentEpochId);
}
/**
* @notice Get reward amount for a specific user.
* @dev Rewards can only be calculated once the epoch is over.
* @dev Will revert if `_epochId` is not in the past.
* @dev Will return 0 if the user average balance in the vault is 0.
* @param _vault Vault to get reward amount for
* @param _user User to get reward amount for
* @param _promotion Promotion from which the epoch is
* @param _epochId Epoch id to get reward amount for
* @return Reward amount
*/
function _calculateRewardAmount(
address _vault,
address _user,
uint256 _promotionId,
Promotion memory _promotion,
uint8 _epochId
) internal returns (uint256) {
(
uint48 _epochStartTimestamp,
uint48 _epochEndTimestamp,
uint24 _epochStartDrawId,
uint24 _epochEndDrawId
) = epochRanges(_promotion.startTimestamp, _promotion.epochDuration, _epochId);
_validateEpoch(_epochId, _promotion.numberOfEpochs, _epochEndTimestamp);
uint256 _userAverage = twabController.getTwabBetween(
_vault,
_user,
_epochStartTimestamp,
_epochEndTimestamp
);
if (_userAverage > 0) {
VaultEpochCache memory vaultEpochCache = _getVaultEpochCache(_promotionId, _epochId, _vault, _epochStartTimestamp, _epochEndTimestamp, _epochStartDrawId, _epochEndDrawId);
if (vaultEpochCache.contributed == 0) {
return 0;
}
EpochCache memory epochCache = _getEpochCache(_promotionId, _epochId, _epochStartDrawId, _epochEndDrawId);
uint vaultPortion = uint256(_promotion.tokensPerEpoch) * uint256(vaultEpochCache.contributed) / epochCache.totalContributed;
uint userPortion = uint256(_userAverage) * uint256(vaultPortion) / uint256(vaultEpochCache.totalSupply);
return userPortion;
}
return 0;
}
/**
* @notice Retrieve the contributed amount for the vault, and the vaults total supply for the given epoch
* @param _promotionId Promotion id
* @param _epochId Epoch id
* @param _vault Vault address
* @param _epochStartTimestamp Start timestamp of the epoch
* @param _epochEndTimestamp End timestamp of the epoch
* @param _epochStartDrawId Start draw id of the epoch
* @param _epochEndDrawId End draw id of the epoch
* @return vaultEpochCache VaultEpochCache struct
*/
function _getVaultEpochCache(
uint256 _promotionId,
uint8 _epochId,
address _vault,
uint48 _epochStartTimestamp,
uint48 _epochEndTimestamp,
uint24 _epochStartDrawId,
uint24 _epochEndDrawId
) internal returns (VaultEpochCache memory vaultEpochCache) {
vaultEpochCache = _vaultEpochCaches[_promotionId][_vault][_epochId];
if (vaultEpochCache.contributed == 0) {
vaultEpochCache.contributed = SafeCast.toUint128(prizePool.getContributedBetween(_vault, _epochStartDrawId, _epochEndDrawId));
vaultEpochCache.totalSupply = SafeCast.toUint128(twabController.getTotalSupplyTwabBetween(
_vault,
_epochStartTimestamp,
_epochEndTimestamp
));
_vaultEpochCaches[_promotionId][_vault][_epochId] = vaultEpochCache;
}
}
function _validateEpoch(uint8 _epochId, uint8 _numberOfEpochs, uint64 _epochEndTimestamp) internal view {
if (block.timestamp < _epochEndTimestamp) revert EpochNotOver(_epochEndTimestamp);
if (_epochId >= _numberOfEpochs) revert InvalidEpochId(_epochId, _numberOfEpochs);
}
/**
* @notice Retrieve the total contributed amount for the epoch
* @param _promotionId Promotion id
* @param _epochId Epoch id
* @param _epochStartDrawId Start draw id of the epoch
* @param _epochEndDrawId End draw id of the epoch
* @return epochCache EpochCache struct
*/
function _getEpochCache(
uint256 _promotionId,
uint8 _epochId,
uint24 _epochStartDrawId,
uint24 _epochEndDrawId
) internal returns (EpochCache memory epochCache) {
epochCache = _epochCaches[_promotionId][_epochId];
if (epochCache.totalContributed == 0) {
epochCache.totalContributed = SafeCast.toUint128(prizePool.getTotalContributedBetween(_epochStartDrawId, _epochEndDrawId));
_epochCaches[_promotionId][_epochId] = epochCache;
}
}
/**
* @notice Get the total amount of tokens left to be rewarded.
* @param _promotion Promotion to get the total amount of tokens left to be rewarded for
* @return Amount of tokens left to be rewarded
*/
function _getRemainingRewards(Promotion memory _promotion) internal view returns (uint112) {
if (block.timestamp >= _getPromotionEndTimestamp(_promotion)) {
return 0;
}
return _promotion.tokensPerEpoch * (_promotion.numberOfEpochs - _getEpochIdNow(_promotion.startTimestamp, _promotion.epochDuration));
}
/**
* @notice Flips a bit in a packed word of bits
* @dev Bits are stored in a uint256 from right to left.
Let's take the example of the following 8 bits word. 0110 0011
To set the boolean value to 1 for the bit index 2, we need to create a mask by shifting 1 to the left by 2 bits.
We get: 0000 0001 << 2 = 0000 0100
We then OR the mask with the word to set the value.
We get: 0110 0011 | 0000 0100 = 0110 0111
* @param _packedBits Tightly packed epoch ids with their boolean values
* @param _bitIndex Index of the bit to flip
* @return Tightly packed epoch ids with the newly boolean value set
*/
function _setBit(bytes32 _packedBits, uint8 _bitIndex) internal pure returns (bytes32) {
return _packedBits | (bytes32(uint256(1)) << _bitIndex);
}
/**
* @notice Check if a bit in a word is set
* @dev Bits are stored in a uint256 from right to left.
Let's take the example of the following 8 bits word. 0110 0111
To retrieve the boolean value for the epoch id 2, we need to shift the word to the right by 2 bits.
We get: 0110 0111 >> 2 = 0001 1001
We then get the value of the last bit by masking with 1.
We get: 0001 1001 & 0000 0001 = 0000 0001 = 1
We then return the boolean value true since the last bit is 1.
* @param _packedBits Word of bits to check (256 bits)
* @param _bitIndex Bit to check
* @return true if the rewards have already been claimed for the given epoch, false otherwise
*/
function _isBitSet(bytes32 _packedBits, uint8 _bitIndex) internal pure returns (bool) {
bool value = (uint256(_packedBits) >> _bitIndex) & uint256(1) == 1;
return value;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.5) (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./Address.sol";
import "./Context.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* Consider any assumption about calldata validation performed by the sender may be violated if it's not especially
* careful about sending transactions invoking {multicall}. For example, a relay address that filters function
* selectors won't filter calls nested within a {multicall} operation.
*
* NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}).
* If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`
* to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of
* {_msgSender} are not propagated to subcalls.
*
* _Available since v4.1._
*/
abstract contract Multicall is Context {
/**
* @dev Receives and executes a batch of function calls on this contract.
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
bytes memory context = msg.sender == _msgSender()
? new bytes(0)
: msg.data[msg.data.length - _contextSuffixLength():];
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));
}
return results;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import { SafeCast } from "openzeppelin/utils/math/SafeCast.sol";
import { TwabLib } from "./libraries/TwabLib.sol";
import { ObservationLib } from "./libraries/ObservationLib.sol";
/// @notice Emitted when an account already points to the same delegate address that is being set
error SameDelegateAlreadySet(address delegate);
/// @notice Emitted when an account tries to transfer to the sponsorship address
error CannotTransferToSponsorshipAddress();
/// @notice Emitted when the period length is too short
error PeriodLengthTooShort();
/// @notice Emitted when the period offset is not in the past.
/// @param periodOffset The period offset that was passed in
error PeriodOffsetInFuture(uint32 periodOffset);
/// @notice Emitted when a user tries to mint or transfer to the zero address
error TransferToZeroAddress();
// The minimum period length
uint32 constant MINIMUM_PERIOD_LENGTH = 1 hours;
// Allows users to revoke their chances to win by delegating to the sponsorship address.
address constant SPONSORSHIP_ADDRESS = address(1);
/**
* @title PoolTogether V5 Time-Weighted Average Balance Controller
* @author PoolTogether Inc. & G9 Software Inc.
* @dev Time-Weighted Average Balance Controller for ERC20 tokens.
* @notice This TwabController uses the TwabLib to provide token balances and on-chain historical
lookups to a user(s) time-weighted average balance. Each user is mapped to an
Account struct containing the TWAB history (ring buffer) and ring buffer parameters.
Every token.transfer() creates a new TWAB observation. The new TWAB observation is
stored in the circular ring buffer as either a new observation or rewriting a
previous observation with new parameters. One observation per period is stored.
The TwabLib guarantees minimum 1 year of search history if a period is a day.
*/
contract TwabController {
using SafeCast for uint256;
/// @notice Sets the minimum period length for Observations. When a period elapses, a new Observation is recorded, otherwise the most recent Observation is updated.
uint32 public immutable PERIOD_LENGTH;
/// @notice Sets the beginning timestamp for the first period. This allows us to maximize storage as well as line up periods with a chosen timestamp.
/// @dev Ensure that the PERIOD_OFFSET is in the past.
uint32 public immutable PERIOD_OFFSET;
/* ============ State ============ */
/// @notice Record of token holders TWABs for each account for each vault.
mapping(address => mapping(address => TwabLib.Account)) internal userObservations;
/// @notice Record of tickets total supply and ring buff parameters used for observation.
mapping(address => TwabLib.Account) internal totalSupplyObservations;
/// @notice vault => user => delegate.
mapping(address => mapping(address => address)) internal delegates;
/* ============ Events ============ */
/**
* @notice Emitted when a balance or delegateBalance is increased.
* @param vault the vault for which the balance increased
* @param user the users whose balance increased
* @param amount the amount the balance increased by
* @param delegateAmount the amount the delegateBalance increased by
*/
event IncreasedBalance(
address indexed vault,
address indexed user,
uint96 amount,
uint96 delegateAmount
);
/**
* @notice Emitted when a balance or delegateBalance is decreased.
* @param vault the vault for which the balance decreased
* @param user the users whose balance decreased
* @param amount the amount the balance decreased by
* @param delegateAmount the amount the delegateBalance decreased by
*/
event DecreasedBalance(
address indexed vault,
address indexed user,
uint96 amount,
uint96 delegateAmount
);
/**
* @notice Emitted when an Observation is recorded to the Ring Buffer.
* @param vault the vault for which the Observation was recorded
* @param user the users whose Observation was recorded
* @param balance the resulting balance
* @param delegateBalance the resulting delegated balance
* @param isNew whether the observation is new or not
* @param observation the observation that was created or updated
*/
event ObservationRecorded(
address indexed vault,
address indexed user,
uint96 balance,
uint96 delegateBalance,
bool isNew,
ObservationLib.Observation observation
);
/**
* @notice Emitted when a user delegates their balance to another address.
* @param vault the vault for which the balance was delegated
* @param delegator the user who delegated their balance
* @param delegate the user who received the delegated balance
*/
event Delegated(address indexed vault, address indexed delegator, address indexed delegate);
/**
* @notice Emitted when the total supply or delegateTotalSupply is increased.
* @param vault the vault for which the total supply increased
* @param amount the amount the total supply increased by
* @param delegateAmount the amount the delegateTotalSupply increased by
*/
event IncreasedTotalSupply(address indexed vault, uint96 amount, uint96 delegateAmount);
/**
* @notice Emitted when the total supply or delegateTotalSupply is decreased.
* @param vault the vault for which the total supply decreased
* @param amount the amount the total supply decreased by
* @param delegateAmount the amount the delegateTotalSupply decreased by
*/
event DecreasedTotalSupply(address indexed vault, uint96 amount, uint96 delegateAmount);
/**
* @notice Emitted when a Total Supply Observation is recorded to the Ring Buffer.
* @param vault the vault for which the Observation was recorded
* @param balance the resulting balance
* @param delegateBalance the resulting delegated balance
* @param isNew whether the observation is new or not
* @param observation the observation that was created or updated
*/
event TotalSupplyObservationRecorded(
address indexed vault,
uint96 balance,
uint96 delegateBalance,
bool isNew,
ObservationLib.Observation observation
);
/* ============ Constructor ============ */
/**
* @notice Construct a new TwabController.
* @dev Reverts if the period offset is in the future.
* @param _periodLength Sets the minimum period length for Observations. When a period elapses, a new Observation
* is recorded, otherwise the most recent Observation is updated.
* @param _periodOffset Sets the beginning timestamp for the first period. This allows us to maximize storage as well
* as line up periods with a chosen timestamp.
*/
constructor(uint32 _periodLength, uint32 _periodOffset) {
if (_periodLength < MINIMUM_PERIOD_LENGTH) {
revert PeriodLengthTooShort();
}
if (_periodOffset > block.timestamp) {
revert PeriodOffsetInFuture(_periodOffset);
}
PERIOD_LENGTH = _periodLength;
PERIOD_OFFSET = _periodOffset;
}
/* ============ External Read Functions ============ */
/**
* @notice Returns whether the TwabController has been shutdown at the given timestamp
* If the twab is queried at or after this time, whether an absolute timestamp or time range, it will return 0.
* @dev This function will return true for any timestamp after the lastObservationAt()
* @param timestamp The timestamp to check
* @return True if the TwabController is shutdown at the given timestamp, false otherwise.
*/
function isShutdownAt(uint256 timestamp) external view returns (bool) {
return TwabLib.isShutdownAt(timestamp, PERIOD_LENGTH, PERIOD_OFFSET);
}
/**
* @notice Computes the timestamp after which no more observations will be made.
* @return The largest timestamp at which the TwabController can record a new observation.
*/
function lastObservationAt() external view returns (uint256) {
return TwabLib.lastObservationAt(PERIOD_LENGTH, PERIOD_OFFSET);
}
/**
* @notice Loads the current TWAB Account data for a specific vault stored for a user.
* @dev Note this is a very expensive function
* @param vault the vault for which the data is being queried
* @param user the user whose data is being queried
* @return The current TWAB Account data of the user
*/
function getAccount(address vault, address user) external view returns (TwabLib.Account memory) {
return userObservations[vault][user];
}
/**
* @notice Loads the current total supply TWAB Account data for a specific vault.
* @dev Note this is a very expensive function
* @param vault the vault for which the data is being queried
* @return The current total supply TWAB Account data
*/
function getTotalSupplyAccount(address vault) external view returns (TwabLib.Account memory) {
return totalSupplyObservations[vault];
}
/**
* @notice The current token balance of a user for a specific vault.
* @param vault the vault for which the balance is being queried
* @param user the user whose balance is being queried
* @return The current token balance of the user
*/
function balanceOf(address vault, address user) external view returns (uint256) {
return userObservations[vault][user].details.balance;
}
/**
* @notice The total supply of tokens for a vault.
* @param vault the vault for which the total supply is being queried
* @return The total supply of tokens for a vault
*/
function totalSupply(address vault) external view returns (uint256) {
return totalSupplyObservations[vault].details.balance;
}
/**
* @notice The total delegated amount of tokens for a vault.
* @dev Delegated balance is not 1:1 with the token total supply. Users may delegate their
* balance to the sponsorship address, which will result in those tokens being subtracted
* from the total.
* @param vault the vault for which the total delegated supply is being queried
* @return The total delegated amount of tokens for a vault
*/
function totalSupplyDelegateBalance(address vault) external view returns (uint256) {
return totalSupplyObservations[vault].details.delegateBalance;
}
/**
* @notice The current delegate of a user for a specific vault.
* @param vault the vault for which the delegate balance is being queried
* @param user the user whose delegate balance is being queried
* @return The current delegate balance of the user
*/
function delegateOf(address vault, address user) external view returns (address) {
return _delegateOf(vault, user);
}
/**
* @notice The current delegateBalance of a user for a specific vault.
* @dev the delegateBalance is the sum of delegated balance to this user
* @param vault the vault for which the delegateBalance is being queried
* @param user the user whose delegateBalance is being queried
* @return The current delegateBalance of the user
*/
function delegateBalanceOf(address vault, address user) external view returns (uint256) {
return userObservations[vault][user].details.delegateBalance;
}
/**
* @notice Looks up a users balance at a specific time in the past.
* @param vault the vault for which the balance is being queried
* @param user the user whose balance is being queried
* @param periodEndOnOrAfterTime The time in the past for which the balance is being queried. The time will be snapped to a period end time on or after the timestamp.
* @return The balance of the user at the target time
*/
function getBalanceAt(
address vault,
address user,
uint256 periodEndOnOrAfterTime
) external view returns (uint256) {
TwabLib.Account storage _account = userObservations[vault][user];
return
TwabLib.getBalanceAt(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account.observations,
_account.details,
_periodEndOnOrAfter(periodEndOnOrAfterTime)
);
}
/**
* @notice Looks up the total supply at a specific time in the past.
* @param vault the vault for which the total supply is being queried
* @param periodEndOnOrAfterTime The time in the past for which the balance is being queried. The time will be snapped to a period end time on or after the timestamp.
* @return The total supply at the target time
*/
function getTotalSupplyAt(
address vault,
uint256 periodEndOnOrAfterTime
) external view returns (uint256) {
TwabLib.Account storage _account = totalSupplyObservations[vault];
return
TwabLib.getBalanceAt(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account.observations,
_account.details,
_periodEndOnOrAfter(periodEndOnOrAfterTime)
);
}
/**
* @notice Looks up the average balance of a user between two timestamps.
* @dev Timestamps are Unix timestamps denominated in seconds
* @param vault the vault for which the average balance is being queried
* @param user the user whose average balance is being queried
* @param startTime the start of the time range for which the average balance is being queried. The time will be snapped to a period end time on or after the timestamp.
* @param endTime the end of the time range for which the average balance is being queried. The time will be snapped to a period end time on or after the timestamp.
* @return The average balance of the user between the two timestamps
*/
function getTwabBetween(
address vault,
address user,
uint256 startTime,
uint256 endTime
) external view returns (uint256) {
TwabLib.Account storage _account = userObservations[vault][user];
// We snap the timestamps to the period end on or after the timestamp because the total supply records will be sparsely populated.
// if two users update during a period, then the total supply observation will only exist for the last one.
return
TwabLib.getTwabBetween(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account.observations,
_account.details,
_periodEndOnOrAfter(startTime),
_periodEndOnOrAfter(endTime)
);
}
/**
* @notice Looks up the average total supply between two timestamps.
* @dev Timestamps are Unix timestamps denominated in seconds
* @param vault the vault for which the average total supply is being queried
* @param startTime the start of the time range for which the average total supply is being queried
* @param endTime the end of the time range for which the average total supply is being queried
* @return The average total supply between the two timestamps
*/
function getTotalSupplyTwabBetween(
address vault,
uint256 startTime,
uint256 endTime
) external view returns (uint256) {
TwabLib.Account storage _account = totalSupplyObservations[vault];
// We snap the timestamps to the period end on or after the timestamp because the total supply records will be sparsely populated.
// if two users update during a period, then the total supply observation will only exist for the last one.
return
TwabLib.getTwabBetween(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account.observations,
_account.details,
_periodEndOnOrAfter(startTime),
_periodEndOnOrAfter(endTime)
);
}
/**
* @notice Computes the period end timestamp on or after the given timestamp.
* @param _timestamp The timestamp to check
* @return The end timestamp of the period that ends on or immediately after the given timestamp
*/
function periodEndOnOrAfter(uint256 _timestamp) external view returns (uint256) {
return _periodEndOnOrAfter(_timestamp);
}
/**
* @notice Computes the period end timestamp on or after the given timestamp.
* @param _timestamp The timestamp to compute the period end time for
* @return A period end time.
*/
function _periodEndOnOrAfter(uint256 _timestamp) internal view returns (uint256) {
if (_timestamp < PERIOD_OFFSET) {
return PERIOD_OFFSET;
}
if ((_timestamp - PERIOD_OFFSET) % PERIOD_LENGTH == 0) {
return _timestamp;
}
uint256 period = TwabLib.getTimestampPeriod(PERIOD_LENGTH, PERIOD_OFFSET, _timestamp);
return TwabLib.getPeriodEndTime(PERIOD_LENGTH, PERIOD_OFFSET, period);
}
/**
* @notice Looks up the newest observation for a user.
* @param vault the vault for which the observation is being queried
* @param user the user whose observation is being queried
* @return index The index of the observation
* @return observation The observation of the user
*/
function getNewestObservation(
address vault,
address user
) external view returns (uint16, ObservationLib.Observation memory) {
TwabLib.Account storage _account = userObservations[vault][user];
return TwabLib.getNewestObservation(_account.observations, _account.details);
}
/**
* @notice Looks up the oldest observation for a user.
* @param vault the vault for which the observation is being queried
* @param user the user whose observation is being queried
* @return index The index of the observation
* @return observation The observation of the user
*/
function getOldestObservation(
address vault,
address user
) external view returns (uint16, ObservationLib.Observation memory) {
TwabLib.Account storage _account = userObservations[vault][user];
return TwabLib.getOldestObservation(_account.observations, _account.details);
}
/**
* @notice Looks up the newest total supply observation for a vault.
* @param vault the vault for which the observation is being queried
* @return index The index of the observation
* @return observation The total supply observation
*/
function getNewestTotalSupplyObservation(
address vault
) external view returns (uint16, ObservationLib.Observation memory) {
TwabLib.Account storage _account = totalSupplyObservations[vault];
return TwabLib.getNewestObservation(_account.observations, _account.details);
}
/**
* @notice Looks up the oldest total supply observation for a vault.
* @param vault the vault for which the observation is being queried
* @return index The index of the observation
* @return observation The total supply observation
*/
function getOldestTotalSupplyObservation(
address vault
) external view returns (uint16, ObservationLib.Observation memory) {
TwabLib.Account storage _account = totalSupplyObservations[vault];
return TwabLib.getOldestObservation(_account.observations, _account.details);
}
/**
* @notice Calculates the period a timestamp falls into.
* @param time The timestamp to check
* @return period The period the timestamp falls into
*/
function getTimestampPeriod(uint256 time) external view returns (uint256) {
return TwabLib.getTimestampPeriod(PERIOD_LENGTH, PERIOD_OFFSET, time);
}
/**
* @notice Checks if the given timestamp is before the current overwrite period.
* @param time The timestamp to check
* @return True if the given time is finalized, false if it's during the current overwrite period.
*/
function hasFinalized(uint256 time) external view returns (bool) {
return TwabLib.hasFinalized(PERIOD_LENGTH, PERIOD_OFFSET, time);
}
/**
* @notice Computes the timestamp at which the current overwrite period started.
* @dev The overwrite period is the period during which observations are collated.
* @return period The timestamp at which the current overwrite period started.
*/
function currentOverwritePeriodStartedAt() external view returns (uint256) {
return TwabLib.currentOverwritePeriodStartedAt(PERIOD_LENGTH, PERIOD_OFFSET);
}
/* ============ External Write Functions ============ */
/**
* @notice Mints new balance and delegateBalance for a given user.
* @dev Note that if the provided user to mint to is delegating that the delegate's
* delegateBalance will be updated.
* @dev Mint is expected to be called by the Vault.
* @param _to The address to mint balance and delegateBalance to
* @param _amount The amount to mint
*/
function mint(address _to, uint96 _amount) external {
if (_to == address(0)) {
revert TransferToZeroAddress();
}
_transferBalance(msg.sender, address(0), _to, _amount);
}
/**
* @notice Burns balance and delegateBalance for a given user.
* @dev Note that if the provided user to burn from is delegating that the delegate's
* delegateBalance will be updated.
* @dev Burn is expected to be called by the Vault.
* @param _from The address to burn balance and delegateBalance from
* @param _amount The amount to burn
*/
function burn(address _from, uint96 _amount) external {
_transferBalance(msg.sender, _from, address(0), _amount);
}
/**
* @notice Transfers balance and delegateBalance from a given user.
* @dev Note that if the provided user to transfer from is delegating that the delegate's
* delegateBalance will be updated.
* @param _from The address to transfer the balance and delegateBalance from
* @param _to The address to transfer balance and delegateBalance to
* @param _amount The amount to transfer
*/
function transfer(address _from, address _to, uint96 _amount) external {
if (_to == address(0)) {
revert TransferToZeroAddress();
}
_transferBalance(msg.sender, _from, _to, _amount);
}
/**
* @notice Sets a delegate for a user which forwards the delegateBalance tied to the user's
* balance to the delegate's delegateBalance.
* @param _vault The vault for which the delegate is being set
* @param _to the address to delegate to
*/
function delegate(address _vault, address _to) external {
_delegate(_vault, msg.sender, _to);
}
/**
* @notice Delegate user balance to the sponsorship address.
* @dev Must only be called by the Vault contract.
* @param _from Address of the user delegating their balance to the sponsorship address.
*/
function sponsor(address _from) external {
_delegate(msg.sender, _from, SPONSORSHIP_ADDRESS);
}
/* ============ Internal Functions ============ */
/**
* @notice Transfers a user's vault balance from one address to another.
* @dev If the user is delegating, their delegate's delegateBalance is also updated.
* @dev If we are minting or burning tokens then the total supply is also updated.
* @param _vault the vault for which the balance is being transferred
* @param _from the address from which the balance is being transferred
* @param _to the address to which the balance is being transferred
* @param _amount the amount of balance being transferred
*/
function _transferBalance(address _vault, address _from, address _to, uint96 _amount) internal {
if (_to == SPONSORSHIP_ADDRESS) {
revert CannotTransferToSponsorshipAddress();
}
if (_from == _to) {
return;
}
// If we are transferring tokens from a delegated account to an undelegated account
address _fromDelegate = _delegateOf(_vault, _from);
address _toDelegate = _delegateOf(_vault, _to);
if (_from != address(0)) {
bool _isFromDelegate = _fromDelegate == _from;
_decreaseBalances(_vault, _from, _amount, _isFromDelegate ? _amount : 0);
// If the user is not delegating to themself, decrease the delegate's delegateBalance
// If the user is delegating to the sponsorship address, don't adjust the delegateBalance
if (!_isFromDelegate && _fromDelegate != SPONSORSHIP_ADDRESS) {
_decreaseBalances(_vault, _fromDelegate, 0, _amount);
}
// Burn balance if we're transferring to address(0)
// Burn delegateBalance if we're transferring to address(0) and burning from an address that is not delegating to the sponsorship address
// Burn delegateBalance if we're transferring to an address delegating to the sponsorship address from an address that isn't delegating to the sponsorship address
if (
_to == address(0) ||
(_toDelegate == SPONSORSHIP_ADDRESS && _fromDelegate != SPONSORSHIP_ADDRESS)
) {
// If the user is delegating to the sponsorship address, don't adjust the total supply delegateBalance
_decreaseTotalSupplyBalances(
_vault,
_to == address(0) ? _amount : 0,
(_to == address(0) && _fromDelegate != SPONSORSHIP_ADDRESS) ||
(_toDelegate == SPONSORSHIP_ADDRESS && _fromDelegate != SPONSORSHIP_ADDRESS)
? _amount
: 0
);
}
}
// If we are transferring tokens to an address other than address(0)
if (_to != address(0)) {
bool _isToDelegate = _toDelegate == _to;
// If the user is delegating to themself, increase their delegateBalance
_increaseBalances(_vault, _to, _amount, _isToDelegate ? _amount : 0);
// Otherwise, increase their delegates delegateBalance if it is not the sponsorship address
if (!_isToDelegate && _toDelegate != SPONSORSHIP_ADDRESS) {
_increaseBalances(_vault, _toDelegate, 0, _amount);
}
// Mint balance if we're transferring from address(0)
// Mint delegateBalance if we're transferring from address(0) and to an address not delegating to the sponsorship address
// Mint delegateBalance if we're transferring from an address delegating to the sponsorship address to an address that isn't delegating to the sponsorship address
if (
_from == address(0) ||
(_fromDelegate == SPONSORSHIP_ADDRESS && _toDelegate != SPONSORSHIP_ADDRESS)
) {
_increaseTotalSupplyBalances(
_vault,
_from == address(0) ? _amount : 0,
(_from == address(0) && _toDelegate != SPONSORSHIP_ADDRESS) ||
(_fromDelegate == SPONSORSHIP_ADDRESS && _toDelegate != SPONSORSHIP_ADDRESS)
? _amount
: 0
);
}
}
}
/**
* @notice Looks up the delegate of a user.
* @param _vault the vault for which the user's delegate is being queried
* @param _user the address to query the delegate of
* @return The address of the user's delegate
*/
function _delegateOf(address _vault, address _user) internal view returns (address) {
address _userDelegate;
if (_user != address(0)) {
_userDelegate = delegates[_vault][_user];
// If the user has not delegated, then the user is the delegate
if (_userDelegate == address(0)) {
_userDelegate = _user;
}
}
return _userDelegate;
}
/**
* @notice Transfers a user's vault delegateBalance from one address to another.
* @param _vault the vault for which the delegateBalance is being transferred
* @param _fromDelegate the address from which the delegateBalance is being transferred
* @param _toDelegate the address to which the delegateBalance is being transferred
* @param _amount the amount of delegateBalance being transferred
*/
function _transferDelegateBalance(
address _vault,
address _fromDelegate,
address _toDelegate,
uint96 _amount
) internal {
// If we are transferring tokens from a delegated account to an undelegated account
if (_fromDelegate != address(0) && _fromDelegate != SPONSORSHIP_ADDRESS) {
_decreaseBalances(_vault, _fromDelegate, 0, _amount);
// If we are delegating to the zero address, decrease total supply
// If we are delegating to the sponsorship address, decrease total supply
if (_toDelegate == address(0) || _toDelegate == SPONSORSHIP_ADDRESS) {
_decreaseTotalSupplyBalances(_vault, 0, _amount);
}
}
// If we are transferring tokens from an undelegated account to a delegated account
if (_toDelegate != address(0) && _toDelegate != SPONSORSHIP_ADDRESS) {
_increaseBalances(_vault, _toDelegate, 0, _amount);
// If we are removing delegation from the zero address, increase total supply
// If we are removing delegation from the sponsorship address, increase total supply
if (_fromDelegate == address(0) || _fromDelegate == SPONSORSHIP_ADDRESS) {
_increaseTotalSupplyBalances(_vault, 0, _amount);
}
}
}
/**
* @notice Sets a delegate for a user which forwards the delegateBalance tied to the user's
* balance to the delegate's delegateBalance. "Sponsoring" means the funds aren't delegated
* to anyone; this can be done by passing address(0) or the SPONSORSHIP_ADDRESS as the delegate.
* @param _vault The vault for which the delegate is being set
* @param _from the address to delegate from
* @param _to the address to delegate to
*/
function _delegate(address _vault, address _from, address _to) internal {
address _currentDelegate = _delegateOf(_vault, _from);
// address(0) is interpreted as sponsoring, so they don't need to know the sponsorship address.
address to = _to == address(0) ? SPONSORSHIP_ADDRESS : _to;
if (to == _currentDelegate) {
revert SameDelegateAlreadySet(to);
}
delegates[_vault][_from] = to;
_transferDelegateBalance(
_vault,
_currentDelegate,
_to,
SafeCast.toUint96(userObservations[_vault][_from].details.balance)
);
emit Delegated(_vault, _from, to);
}
/**
* @notice Increases a user's balance and delegateBalance for a specific vault.
* @param _vault the vault for which the balance is being increased
* @param _user the address of the user whose balance is being increased
* @param _amount the amount of balance being increased
* @param _delegateAmount the amount of delegateBalance being increased
*/
function _increaseBalances(
address _vault,
address _user,
uint96 _amount,
uint96 _delegateAmount
) internal {
TwabLib.Account storage _account = userObservations[_vault][_user];
(
ObservationLib.Observation memory _observation,
bool _isNewObservation,
bool _isObservationRecorded,
TwabLib.AccountDetails memory accountDetails
) = TwabLib.increaseBalances(PERIOD_LENGTH, PERIOD_OFFSET, _account, _amount, _delegateAmount);
// Always emit the balance change event
if (_amount != 0 || _delegateAmount != 0) {
emit IncreasedBalance(_vault, _user, _amount, _delegateAmount);
}
// Conditionally emit the observation recorded event
if (_isObservationRecorded) {
emit ObservationRecorded(
_vault,
_user,
accountDetails.balance,
accountDetails.delegateBalance,
_isNewObservation,
_observation
);
}
}
/**
* @notice Decreases the a user's balance and delegateBalance for a specific vault.
* @param _vault the vault for which the totalSupply balance is being decreased
* @param _amount the amount of balance being decreased
* @param _delegateAmount the amount of delegateBalance being decreased
*/
function _decreaseBalances(
address _vault,
address _user,
uint96 _amount,
uint96 _delegateAmount
) internal {
TwabLib.Account storage _account = userObservations[_vault][_user];
(
ObservationLib.Observation memory _observation,
bool _isNewObservation,
bool _isObservationRecorded,
TwabLib.AccountDetails memory accountDetails
) = TwabLib.decreaseBalances(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account,
_amount,
_delegateAmount,
"TC/observation-burn-lt-delegate-balance"
);
// Always emit the balance change event
if (_amount != 0 || _delegateAmount != 0) {
emit DecreasedBalance(_vault, _user, _amount, _delegateAmount);
}
// Conditionally emit the observation recorded event
if (_isObservationRecorded) {
emit ObservationRecorded(
_vault,
_user,
accountDetails.balance,
accountDetails.delegateBalance,
_isNewObservation,
_observation
);
}
}
/**
* @notice Decreases the totalSupply balance and delegateBalance for a specific vault.
* @param _vault the vault for which the totalSupply balance is being decreased
* @param _amount the amount of balance being decreased
* @param _delegateAmount the amount of delegateBalance being decreased
*/
function _decreaseTotalSupplyBalances(
address _vault,
uint96 _amount,
uint96 _delegateAmount
) internal {
TwabLib.Account storage _account = totalSupplyObservations[_vault];
(
ObservationLib.Observation memory _observation,
bool _isNewObservation,
bool _isObservationRecorded,
TwabLib.AccountDetails memory accountDetails
) = TwabLib.decreaseBalances(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account,
_amount,
_delegateAmount,
"TC/burn-amount-exceeds-total-supply-balance"
);
// Always emit the balance change event
if (_amount != 0 || _delegateAmount != 0) {
emit DecreasedTotalSupply(_vault, _amount, _delegateAmount);
}
// Conditionally emit the observation recorded event
if (_isObservationRecorded) {
emit TotalSupplyObservationRecorded(
_vault,
accountDetails.balance,
accountDetails.delegateBalance,
_isNewObservation,
_observation
);
}
}
/**
* @notice Increases the totalSupply balance and delegateBalance for a specific vault.
* @param _vault the vault for which the totalSupply balance is being increased
* @param _amount the amount of balance being increased
* @param _delegateAmount the amount of delegateBalance being increased
*/
function _increaseTotalSupplyBalances(
address _vault,
uint96 _amount,
uint96 _delegateAmount
) internal {
TwabLib.Account storage _account = totalSupplyObservations[_vault];
(
ObservationLib.Observation memory _observation,
bool _isNewObservation,
bool _isObservationRecorded,
TwabLib.AccountDetails memory accountDetails
) = TwabLib.increaseBalances(PERIOD_LENGTH, PERIOD_OFFSET, _account, _amount, _delegateAmount);
// Always emit the balance change event
if (_amount != 0 || _delegateAmount != 0) {
emit IncreasedTotalSupply(_vault, _amount, _delegateAmount);
}
// Conditionally emit the observation recorded event
if (_isObservationRecorded) {
emit TotalSupplyObservationRecorded(
_vault,
accountDetails.balance,
accountDetails.delegateBalance,
_isNewObservation,
_observation
);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface IPrizePool {
function getTotalContributedBetween(
uint24 _startDrawIdInclusive,
uint24 _endDrawIdInclusive
) external view returns (uint256);
function getContributedBetween(
address _vault,
uint24 _startDrawIdInclusive,
uint24 _endDrawIdInclusive
) external view returns (uint256);
function drawPeriodSeconds() external view returns (uint48);
function firstDrawOpensAt() external view returns (uint48);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import { IERC20 } from "openzeppelin-contracts/token/ERC20/IERC20.sol";
/**
* @notice Struct to keep track of each promotion's settings.
* @param token Address of the token to be distributed as reward
* @param epochDuration Duration of one epoch in draws
* @param createdAt Timestamp at which the promotion was created
* @param numberOfEpochs Number of epochs the promotion will last for
* @param startTimestamp Timestamp at which the promotion starts
* @param tokensPerEpoch Number of tokens to be distributed per epoch
* @param rewardsUnclaimed Amount of rewards that have not been claimed yet
*/
struct Promotion {
IERC20 token;
uint40 epochDuration;
uint40 createdAt;
uint8 numberOfEpochs;
// first word ends
uint40 startTimestamp;
uint104 tokensPerEpoch;
uint112 rewardsUnclaimed;
// second word ends
}
/**
* @title PoolTogether V5 IPrizePoolTwabRewards
* @author PoolTogether Inc. & G9 Software Inc.
* @notice PrizePoolTwabRewards contract interface.
*/
interface IPrizePoolTwabRewards {
/**
* @notice Returns the id of the latest created promotion. Will be 0 if no promotions have been created yet.
* @return Id of the latest created promotion
*/
function latestPromotionId() external view returns (uint256);
/**
* @notice Creates a new promotion.
* @param token Address of the token to be distributed
* @param startTimestamp Timestamp at which the promotion starts. MUST be aligned with the Prize Pool's draw start or end times.
* @param tokensPerEpoch Number of tokens to be distributed per epoch
* @param epochDuration Duration of one epoch in seconds.
* @param numberOfEpochs Number of epochs the promotion will last for
* @return Id of the newly created promotion
*/
function createPromotion(
IERC20 token,
uint40 startTimestamp,
uint104 tokensPerEpoch,
uint40 epochDuration,
uint8 numberOfEpochs
) external returns (uint256);
/**
* @notice End currently active promotion and send promotion tokens for remaining epochs back to the creator.
* @param promotionId Promotion id to end
* @param to Address that will receive any remaining tokens
* @return True if operation was successful
*/
function endPromotion(uint256 promotionId, address to) external returns (bool);
/**
* @notice Delete an inactive promotion and sends back any unclaimed tokens to the creator.
* @dev This function will revert if the promotion is still active.
* @dev This function will revert if the grace period is not over yet.
* @param promotionId Promotion id to destroy
* @param to Address that will receive any remaining tokens
* @return True if operation was successful
*/
function destroyPromotion(uint256 promotionId, address to) external returns (bool);
/**
* @notice Extend promotion by adding more epochs. The caller must have approved the contract to transfer the tokens (numberOfEpochs * tokensPerEpoch).
* @param promotionId Id of the promotion to extend
* @param numberOfEpochs Number of epochs to add
* @return True if the operation was successful
*/
function extendPromotion(uint256 promotionId, uint8 numberOfEpochs) external returns (bool);
/**
* @notice Claim rewards for a given promotion and epoch.
* @dev Rewards can be claimed on behalf of a user.
* @dev Rewards can only be claimed for a past epoch.
* @param user Address of the user to claim rewards for
* @param promotionId Id of the promotion to claim rewards for
* @param epochIds Epoch ids to claim rewards for
* @return Total amount of rewards claimed
*/
function claimRewards(address vault, address user, uint256 promotionId, uint8[] calldata epochIds) external returns (uint256);
/**
* @notice Claim rewards for all epochs from `_startEpochId` to the most recently ended epoch.
* @param _vault Address of the vault
* @param _user Address of the user
* @param _promotionId Id of the promotion
* @param _startEpochId Id of the epoch to start claiming rewards from
* @return Amount of tokens transferred to the recipient address
*/
function claimRewardedEpochs(address _vault, address _user, uint256 _promotionId, uint8 _startEpochId) external returns (uint256);
/**
* @notice Get settings for a specific promotion.
* @param promotionId Id of the promotion to get settings for
* @return Promotion settings
*/
function getPromotion(uint256 promotionId) external view returns (Promotion memory);
/**
* @notice Get the current epoch id of a promotion.
* @param promotionId Id of the promotion to get current epoch for
* @return Current epoch id of the promotion
*/
function getEpochIdNow(uint256 promotionId) external view returns (uint8);
/**
* @notice Get the epoch id of a promotion given a timestamp
* @param promotionId Id of the promotion to get current epoch for
* @param timestamp Timestamp to get the epoch id for
* @return Current epoch id of the promotion
*/
function getEpochIdAt(uint256 promotionId, uint256 timestamp) external view returns (uint8);
/**
* @notice Get the total amount of tokens left to be rewarded.
* @param promotionId Id of the promotion to get the total amount of tokens left to be rewarded for
* @return Amount of tokens left to be rewarded
*/
function getRemainingRewards(uint256 promotionId) external view returns (uint128);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/**
* @title PoolTogether V5 ITwabRewards
* @author PoolTogether Inc. & G9 Software Inc.
* @notice TwabRewards contract interface.
*/
interface ITwabRewards {
/**
* @notice Claim rewards for a given promotion and epoch.
* @dev Rewards can be claimed on behalf of a user.
* @dev Rewards can only be claimed for a past epoch.
* @param user Address of the user to claim rewards for
* @param promotionId Id of the promotion to claim rewards for
* @param epochIds Epoch ids to claim rewards for
* @return Total amount of rewards claimed
*/
function claimRewards(address user, uint256 promotionId, uint8[] calldata epochIds) external returns (uint256);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "ring-buffer-lib/RingBufferLib.sol";
import { ObservationLib, MAX_CARDINALITY } from "./ObservationLib.sol";
type PeriodOffsetRelativeTimestamp is uint32;
/// @notice Emitted when a balance is decreased by an amount that exceeds the amount available.
/// @param balance The current balance of the account
/// @param amount The amount being decreased from the account's balance
/// @param message An additional message describing the error
error BalanceLTAmount(uint96 balance, uint96 amount, string message);
/// @notice Emitted when a delegate balance is decreased by an amount that exceeds the amount available.
/// @param delegateBalance The current delegate balance of the account
/// @param delegateAmount The amount being decreased from the account's delegate balance
/// @param message An additional message describing the error
error DelegateBalanceLTAmount(uint96 delegateBalance, uint96 delegateAmount, string message);
/// @notice Emitted when a request is made for a twab that is not yet finalized.
/// @param timestamp The requested timestamp
/// @param currentOverwritePeriodStartedAt The current overwrite period start time
error TimestampNotFinalized(uint256 timestamp, uint256 currentOverwritePeriodStartedAt);
/// @notice Emitted when a TWAB time range start is after the end.
/// @param start The start time
/// @param end The end time
error InvalidTimeRange(uint256 start, uint256 end);
/// @notice Emitted when there is insufficient history to lookup a twab time range
/// @param requestedTimestamp The timestamp requested
/// @param oldestTimestamp The oldest timestamp that can be read
error InsufficientHistory(
PeriodOffsetRelativeTimestamp requestedTimestamp,
PeriodOffsetRelativeTimestamp oldestTimestamp
);
/**
* @title PoolTogether V5 TwabLib (Library)
* @author PoolTogether Inc. & G9 Software Inc.
* @dev Time-Weighted Average Balance Library for ERC20 tokens.
* @notice This TwabLib adds on-chain historical lookups to a user(s) time-weighted average balance.
* Each user is mapped to an Account struct containing the TWAB history (ring buffer) and
* ring buffer parameters. Every token.transfer() creates a new TWAB checkpoint. The new
* TWAB checkpoint is stored in the circular ring buffer, as either a new checkpoint or
* rewriting a previous checkpoint with new parameters. One checkpoint per day is stored.
* The TwabLib guarantees minimum 1 year of search history.
* @notice There are limitations to the Observation data structure used. Ensure your token is
* compatible before using this library. Ensure the date ranges you're relying on are
* within safe boundaries.
*/
library TwabLib {
/**
* @notice Struct ring buffer parameters for single user Account.
* @param balance Current token balance for an Account
* @param delegateBalance Current delegate balance for an Account (active balance for chance)
* @param nextObservationIndex Next uninitialized or updatable ring buffer checkpoint storage slot
* @param cardinality Current total "initialized" ring buffer checkpoints for single user Account.
* Used to set initial boundary conditions for an efficient binary search.
*/
struct AccountDetails {
uint96 balance;
uint96 delegateBalance;
uint16 nextObservationIndex;
uint16 cardinality;
}
/**
* @notice Account details and historical twabs.
* @dev The size of observations is MAX_CARDINALITY from the ObservationLib.
* @param details The account details
* @param observations The history of observations for this account
*/
struct Account {
AccountDetails details;
ObservationLib.Observation[17520] observations;
}
/**
* @notice Increase a user's balance and delegate balance by a given amount.
* @dev This function mutates the provided account.
* @param PERIOD_LENGTH The length of an overwrite period
* @param PERIOD_OFFSET The offset of the first period
* @param _account The account to update
* @param _amount The amount to increase the balance by
* @param _delegateAmount The amount to increase the delegate balance by
* @return observation The new/updated observation
* @return isNew Whether or not the observation is new or overwrote a previous one
* @return isObservationRecorded Whether or not an observation was recorded to storage
*/
function increaseBalances(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
Account storage _account,
uint96 _amount,
uint96 _delegateAmount
)
internal
returns (
ObservationLib.Observation memory observation,
bool isNew,
bool isObservationRecorded,
AccountDetails memory accountDetails
)
{
accountDetails = _account.details;
// record a new observation if the delegateAmount is non-zero and time has not overflowed.
isObservationRecorded =
_delegateAmount != uint96(0) &&
block.timestamp <= lastObservationAt(PERIOD_LENGTH, PERIOD_OFFSET);
accountDetails.balance += _amount;
accountDetails.delegateBalance += _delegateAmount;
// Only record a new Observation if the users delegateBalance has changed.
if (isObservationRecorded) {
(observation, isNew, accountDetails) = _recordObservation(
PERIOD_LENGTH,
PERIOD_OFFSET,
accountDetails,
_account
);
}
_account.details = accountDetails;
}
/**
* @notice Decrease a user's balance and delegate balance by a given amount.
* @dev This function mutates the provided account.
* @param PERIOD_LENGTH The length of an overwrite period
* @param PERIOD_OFFSET The offset of the first period
* @param _account The account to update
* @param _amount The amount to decrease the balance by
* @param _delegateAmount The amount to decrease the delegate balance by
* @param _revertMessage The revert message to use if the balance is insufficient
* @return observation The new/updated observation
* @return isNew Whether or not the observation is new or overwrote a previous one
* @return isObservationRecorded Whether or not the observation was recorded to storage
*/
function decreaseBalances(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
Account storage _account,
uint96 _amount,
uint96 _delegateAmount,
string memory _revertMessage
)
internal
returns (
ObservationLib.Observation memory observation,
bool isNew,
bool isObservationRecorded,
AccountDetails memory accountDetails
)
{
accountDetails = _account.details;
if (accountDetails.balance < _amount) {
revert BalanceLTAmount(accountDetails.balance, _amount, _revertMessage);
}
if (accountDetails.delegateBalance < _delegateAmount) {
revert DelegateBalanceLTAmount(
accountDetails.delegateBalance,
_delegateAmount,
_revertMessage
);
}
// record a new observation if the delegateAmount is non-zero and time has not overflowed.
isObservationRecorded =
_delegateAmount != uint96(0) &&
block.timestamp <= lastObservationAt(PERIOD_LENGTH, PERIOD_OFFSET);
unchecked {
accountDetails.balance -= _amount;
accountDetails.delegateBalance -= _delegateAmount;
}
// Only record a new Observation if the users delegateBalance has changed.
if (isObservationRecorded) {
(observation, isNew, accountDetails) = _recordObservation(
PERIOD_LENGTH,
PERIOD_OFFSET,
accountDetails,
_account
);
}
_account.details = accountDetails;
}
/**
* @notice Looks up the oldest observation in the circular buffer.
* @param _observations The circular buffer of observations
* @param _accountDetails The account details to query with
* @return index The index of the oldest observation
* @return observation The oldest observation in the circular buffer
*/
function getOldestObservation(
ObservationLib.Observation[MAX_CARDINALITY] storage _observations,
AccountDetails memory _accountDetails
) internal view returns (uint16 index, ObservationLib.Observation memory observation) {
// If the circular buffer has not been fully populated, we go to the beginning of the buffer at index 0.
if (_accountDetails.cardinality < MAX_CARDINALITY) {
index = 0;
observation = _observations[0];
} else {
index = _accountDetails.nextObservationIndex;
observation = _observations[index];
}
}
/**
* @notice Looks up the newest observation in the circular buffer.
* @param _observations The circular buffer of observations
* @param _accountDetails The account details to query with
* @return index The index of the newest observation
* @return observation The newest observation in the circular buffer
*/
function getNewestObservation(
ObservationLib.Observation[MAX_CARDINALITY] storage _observations,
AccountDetails memory _accountDetails
) internal view returns (uint16 index, ObservationLib.Observation memory observation) {
index = uint16(
RingBufferLib.newestIndex(_accountDetails.nextObservationIndex, MAX_CARDINALITY)
);
observation = _observations[index];
}
/**
* @notice Looks up a users balance at a specific time in the past. The time must be before the current overwrite period.
* @dev Ensure timestamps are safe using requireFinalized
* @param PERIOD_LENGTH The length of an overwrite period
* @param PERIOD_OFFSET The offset of the first period
* @param _observations The circular buffer of observations
* @param _accountDetails The account details to query with
* @param _targetTime The time to look up the balance at
* @return balance The balance at the target time
*/
function getBalanceAt(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
ObservationLib.Observation[MAX_CARDINALITY] storage _observations,
AccountDetails memory _accountDetails,
uint256 _targetTime
) internal view requireFinalized(PERIOD_LENGTH, PERIOD_OFFSET, _targetTime) returns (uint256) {
if (_targetTime < PERIOD_OFFSET) {
return 0;
}
// if this is for an overflowed time period, return 0
if (isShutdownAt(_targetTime, PERIOD_LENGTH, PERIOD_OFFSET)) {
return 0;
}
ObservationLib.Observation memory prevOrAtObservation = _getPreviousOrAtObservation(
_observations,
_accountDetails,
PeriodOffsetRelativeTimestamp.wrap(uint32(_targetTime - PERIOD_OFFSET))
);
return prevOrAtObservation.balance;
}
/**
* @notice Returns whether the TwabController has been shutdown at the given timestamp
* If the twab is queried at or after this time, whether an absolute timestamp or time range, it will return 0.
* @param timestamp The timestamp to check
* @param PERIOD_OFFSET The offset of the first period
* @return True if the TwabController is shutdown at the given timestamp, false otherwise.
*/
function isShutdownAt(
uint256 timestamp,
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET
) internal pure returns (bool) {
return timestamp > lastObservationAt(PERIOD_LENGTH, PERIOD_OFFSET);
}
/**
* @notice Computes the largest timestamp at which the TwabController can record a new observation.
* @param PERIOD_OFFSET The offset of the first period
* @return The largest timestamp at which the TwabController can record a new observation.
*/
function lastObservationAt(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET
) internal pure returns (uint256) {
return uint256(PERIOD_OFFSET) + (type(uint32).max / PERIOD_LENGTH) * PERIOD_LENGTH;
}
/**
* @notice Looks up a users TWAB for a time range. The time must be before the current overwrite period.
* @dev If the timestamps in the range are not exact matches of observations, the balance is extrapolated using the previous observation.
* @param PERIOD_LENGTH The length of an overwrite period
* @param PERIOD_OFFSET The offset of the first period
* @param _observations The circular buffer of observations
* @param _accountDetails The account details to query with
* @param _startTime The start of the time range
* @param _endTime The end of the time range
* @return twab The TWAB for the time range
*/
function getTwabBetween(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
ObservationLib.Observation[MAX_CARDINALITY] storage _observations,
AccountDetails memory _accountDetails,
uint256 _startTime,
uint256 _endTime
) internal view requireFinalized(PERIOD_LENGTH, PERIOD_OFFSET, _endTime) returns (uint256) {
if (_endTime < _startTime) {
revert InvalidTimeRange(_startTime, _endTime);
}
// if the range extends into the shutdown period, return 0
if (isShutdownAt(_endTime, PERIOD_LENGTH, PERIOD_OFFSET)) {
return 0;
}
uint256 offsetStartTime = _startTime - PERIOD_OFFSET;
uint256 offsetEndTime = _endTime - PERIOD_OFFSET;
ObservationLib.Observation memory endObservation = _getPreviousOrAtObservation(
_observations,
_accountDetails,
PeriodOffsetRelativeTimestamp.wrap(uint32(offsetEndTime))
);
if (offsetStartTime == offsetEndTime) {
return endObservation.balance;
}
ObservationLib.Observation memory startObservation = _getPreviousOrAtObservation(
_observations,
_accountDetails,
PeriodOffsetRelativeTimestamp.wrap(uint32(offsetStartTime))
);
if (startObservation.timestamp != offsetStartTime) {
startObservation = _calculateTemporaryObservation(
startObservation,
PeriodOffsetRelativeTimestamp.wrap(uint32(offsetStartTime))
);
}
if (endObservation.timestamp != offsetEndTime) {
endObservation = _calculateTemporaryObservation(
endObservation,
PeriodOffsetRelativeTimestamp.wrap(uint32(offsetEndTime))
);
}
// Difference in amount / time
return
(endObservation.cumulativeBalance - startObservation.cumulativeBalance) /
(offsetEndTime - offsetStartTime);
}
/**
* @notice Given an AccountDetails with updated balances, either updates the latest Observation or records a new one
* @param PERIOD_LENGTH The overwrite period length
* @param PERIOD_OFFSET The overwrite period offset
* @param _accountDetails The updated account details
* @param _account The account to update
* @return observation The new/updated observation
* @return isNew Whether or not the observation is new or overwrote a previous one
* @return newAccountDetails The new account details
*/
function _recordObservation(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
AccountDetails memory _accountDetails,
Account storage _account
)
internal
returns (
ObservationLib.Observation memory observation,
bool isNew,
AccountDetails memory newAccountDetails
)
{
PeriodOffsetRelativeTimestamp currentTime = PeriodOffsetRelativeTimestamp.wrap(
uint32(block.timestamp - PERIOD_OFFSET)
);
uint16 nextIndex;
ObservationLib.Observation memory newestObservation;
(nextIndex, newestObservation, isNew) = _getNextObservationIndex(
PERIOD_LENGTH,
PERIOD_OFFSET,
_account.observations,
_accountDetails
);
if (isNew) {
// If the index is new, then we increase the next index to use
_accountDetails.nextObservationIndex = uint16(
RingBufferLib.nextIndex(uint256(nextIndex), MAX_CARDINALITY)
);
// Prevent the Account specific cardinality from exceeding the MAX_CARDINALITY.
// The ring buffer length is limited by MAX_CARDINALITY. IF the account.cardinality
// exceeds the max cardinality, new observations would be incorrectly set or the
// observation would be out of "bounds" of the ring buffer. Once reached the
// Account.cardinality will continue to be equal to max cardinality.
_accountDetails.cardinality = _accountDetails.cardinality < MAX_CARDINALITY
? _accountDetails.cardinality + 1
: MAX_CARDINALITY;
}
observation = ObservationLib.Observation({
cumulativeBalance: _extrapolateFromBalance(newestObservation, currentTime),
balance: _accountDetails.delegateBalance,
timestamp: PeriodOffsetRelativeTimestamp.unwrap(currentTime)
});
// Write to storage
_account.observations[nextIndex] = observation;
newAccountDetails = _accountDetails;
}
/**
* @notice Calculates a temporary observation for a given time using the previous observation.
* @dev This is used to extrapolate a balance for any given time.
* @param _observation The previous observation
* @param _time The time to extrapolate to
*/
function _calculateTemporaryObservation(
ObservationLib.Observation memory _observation,
PeriodOffsetRelativeTimestamp _time
) private pure returns (ObservationLib.Observation memory) {
return
ObservationLib.Observation({
cumulativeBalance: _extrapolateFromBalance(_observation, _time),
balance: _observation.balance,
timestamp: PeriodOffsetRelativeTimestamp.unwrap(_time)
});
}
/**
* @notice Looks up the next observation index to write to in the circular buffer.
* @dev If the current time is in the same period as the newest observation, we overwrite it.
* @dev If the current time is in a new period, we increment the index and write a new observation.
* @param PERIOD_LENGTH The length of an overwrite period
* @param PERIOD_OFFSET The offset of the first period
* @param _observations The circular buffer of observations
* @param _accountDetails The account details to query with
* @return index The index of the next observation slot to overwrite
* @return newestObservation The newest observation in the circular buffer
* @return isNew True if the observation slot is new, false if we're overwriting
*/
function _getNextObservationIndex(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
ObservationLib.Observation[MAX_CARDINALITY] storage _observations,
AccountDetails memory _accountDetails
)
private
view
returns (uint16 index, ObservationLib.Observation memory newestObservation, bool isNew)
{
uint16 newestIndex;
(newestIndex, newestObservation) = getNewestObservation(_observations, _accountDetails);
uint256 currentPeriod = getTimestampPeriod(PERIOD_LENGTH, PERIOD_OFFSET, block.timestamp);
uint256 newestObservationPeriod = getTimestampPeriod(
PERIOD_LENGTH,
PERIOD_OFFSET,
PERIOD_OFFSET + uint256(newestObservation.timestamp)
);
// Create a new Observation if it's the first period or the current time falls within a new period
if (_accountDetails.cardinality == 0 || currentPeriod > newestObservationPeriod) {
return (_accountDetails.nextObservationIndex, newestObservation, true);
}
// Otherwise, we're overwriting the current newest Observation
return (newestIndex, newestObservation, false);
}
/**
* @notice Computes the start time of the current overwrite period
* @param PERIOD_LENGTH The length of an overwrite period
* @param PERIOD_OFFSET The offset of the first period
* @return The start time of the current overwrite period
*/
function _currentOverwritePeriodStartedAt(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET
) private view returns (uint256) {
uint256 period = getTimestampPeriod(PERIOD_LENGTH, PERIOD_OFFSET, block.timestamp);
return getPeriodStartTime(PERIOD_LENGTH, PERIOD_OFFSET, period);
}
/**
* @notice Calculates the next cumulative balance using a provided Observation and timestamp.
* @param _observation The observation to extrapolate from
* @param _offsetTimestamp The timestamp to extrapolate to
* @return cumulativeBalance The cumulative balance at the timestamp
*/
function _extrapolateFromBalance(
ObservationLib.Observation memory _observation,
PeriodOffsetRelativeTimestamp _offsetTimestamp
) private pure returns (uint128) {
// new cumulative balance = provided cumulative balance (or zero) + (current balance * elapsed seconds)
unchecked {
return
uint128(
uint256(_observation.cumulativeBalance) +
uint256(_observation.balance) *
(PeriodOffsetRelativeTimestamp.unwrap(_offsetTimestamp) - _observation.timestamp)
);
}
}
/**
* @notice Computes the overwrite period start time given the current time
* @param PERIOD_LENGTH The length of an overwrite period
* @param PERIOD_OFFSET The offset of the first period
* @return The start time for the current overwrite period.
*/
function currentOverwritePeriodStartedAt(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET
) internal view returns (uint256) {
return _currentOverwritePeriodStartedAt(PERIOD_LENGTH, PERIOD_OFFSET);
}
/**
* @notice Calculates the period a timestamp falls within.
* @dev Timestamp prior to the PERIOD_OFFSET are considered to be in period 0.
* @param PERIOD_LENGTH The length of an overwrite period
* @param PERIOD_OFFSET The offset of the first period
* @param _timestamp The timestamp to calculate the period for
* @return period The period
*/
function getTimestampPeriod(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
uint256 _timestamp
) internal pure returns (uint256) {
if (_timestamp <= PERIOD_OFFSET) {
return 0;
}
return (_timestamp - PERIOD_OFFSET) / uint256(PERIOD_LENGTH);
}
/**
* @notice Calculates the start timestamp for a period
* @param PERIOD_LENGTH The period length to use to calculate the period
* @param PERIOD_OFFSET The period offset to use to calculate the period
* @param _period The period to check
* @return _timestamp The timestamp at which the period starts
*/
function getPeriodStartTime(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
uint256 _period
) internal pure returns (uint256) {
return _period * PERIOD_LENGTH + PERIOD_OFFSET;
}
/**
* @notice Calculates the last timestamp for a period
* @param PERIOD_LENGTH The period length to use to calculate the period
* @param PERIOD_OFFSET The period offset to use to calculate the period
* @param _period The period to check
* @return _timestamp The timestamp at which the period ends
*/
function getPeriodEndTime(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
uint256 _period
) internal pure returns (uint256) {
return (_period + 1) * PERIOD_LENGTH + PERIOD_OFFSET;
}
/**
* @notice Looks up the newest observation before or at a given timestamp.
* @dev If an observation is available at the target time, it is returned. Otherwise, the newest observation before the target time is returned.
* @param PERIOD_OFFSET The period offset to use to calculate the period
* @param _observations The circular buffer of observations
* @param _accountDetails The account details to query with
* @param _targetTime The timestamp to look up
* @return prevOrAtObservation The observation
*/
function getPreviousOrAtObservation(
uint32 PERIOD_OFFSET,
ObservationLib.Observation[MAX_CARDINALITY] storage _observations,
AccountDetails memory _accountDetails,
uint256 _targetTime
) internal view returns (ObservationLib.Observation memory prevOrAtObservation) {
if (_targetTime < PERIOD_OFFSET) {
return ObservationLib.Observation({ cumulativeBalance: 0, balance: 0, timestamp: 0 });
}
uint256 offsetTargetTime = _targetTime - PERIOD_OFFSET;
// if this is for an overflowed time period, return 0
if (offsetTargetTime > type(uint32).max) {
return
ObservationLib.Observation({
cumulativeBalance: 0,
balance: 0,
timestamp: type(uint32).max
});
}
prevOrAtObservation = _getPreviousOrAtObservation(
_observations,
_accountDetails,
PeriodOffsetRelativeTimestamp.wrap(uint32(offsetTargetTime))
);
}
/**
* @notice Looks up the newest observation before or at a given timestamp.
* @dev If an observation is available at the target time, it is returned. Otherwise, the newest observation before the target time is returned.
* @param _observations The circular buffer of observations
* @param _accountDetails The account details to query with
* @param _offsetTargetTime The timestamp to look up (offset by the period offset)
* @return prevOrAtObservation The observation
*/
function _getPreviousOrAtObservation(
ObservationLib.Observation[MAX_CARDINALITY] storage _observations,
AccountDetails memory _accountDetails,
PeriodOffsetRelativeTimestamp _offsetTargetTime
) private view returns (ObservationLib.Observation memory prevOrAtObservation) {
// If there are no observations, return a zeroed observation
if (_accountDetails.cardinality == 0) {
return ObservationLib.Observation({ cumulativeBalance: 0, balance: 0, timestamp: 0 });
}
uint16 oldestTwabIndex;
(oldestTwabIndex, prevOrAtObservation) = getOldestObservation(_observations, _accountDetails);
// if the requested time is older than the oldest observation
if (PeriodOffsetRelativeTimestamp.unwrap(_offsetTargetTime) < prevOrAtObservation.timestamp) {
// if the user didn't have any activity prior to the oldest observation, then we know they had a zero balance
if (_accountDetails.cardinality < MAX_CARDINALITY) {
return
ObservationLib.Observation({
cumulativeBalance: 0,
balance: 0,
timestamp: PeriodOffsetRelativeTimestamp.unwrap(_offsetTargetTime)
});
} else {
// if we are missing their history, we must revert
revert InsufficientHistory(
_offsetTargetTime,
PeriodOffsetRelativeTimestamp.wrap(prevOrAtObservation.timestamp)
);
}
}
// We know targetTime >= oldestObservation.timestamp because of the above if statement, so we can return here.
if (_accountDetails.cardinality == 1) {
return prevOrAtObservation;
}
// Find the newest observation
(
uint16 newestTwabIndex,
ObservationLib.Observation memory afterOrAtObservation
) = getNewestObservation(_observations, _accountDetails);
// if the target time is at or after the newest, return it
if (PeriodOffsetRelativeTimestamp.unwrap(_offsetTargetTime) >= afterOrAtObservation.timestamp) {
return afterOrAtObservation;
}
// if we know there is only 1 observation older than the newest
if (_accountDetails.cardinality == 2) {
return prevOrAtObservation;
}
// Otherwise, we perform a binarySearch to find the observation before or at the timestamp
(prevOrAtObservation, oldestTwabIndex, afterOrAtObservation, newestTwabIndex) = ObservationLib
.binarySearch(
_observations,
newestTwabIndex,
oldestTwabIndex,
PeriodOffsetRelativeTimestamp.unwrap(_offsetTargetTime),
_accountDetails.cardinality
);
// If the afterOrAt is at, we can skip a temporary Observation computation by returning it here
if (afterOrAtObservation.timestamp == PeriodOffsetRelativeTimestamp.unwrap(_offsetTargetTime)) {
return afterOrAtObservation;
}
return prevOrAtObservation;
}
/**
* @notice Checks if the given timestamp is safe to perform a historic balance lookup on.
* @dev A timestamp is safe if it is before the current overwrite period
* @param PERIOD_LENGTH The period length to use to calculate the period
* @param PERIOD_OFFSET The period offset to use to calculate the period
* @param _time The timestamp to check
* @return isSafe Whether or not the timestamp is safe
*/
function hasFinalized(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
uint256 _time
) internal view returns (bool) {
return _hasFinalized(PERIOD_LENGTH, PERIOD_OFFSET, _time);
}
/**
* @notice Checks if the given timestamp is safe to perform a historic balance lookup on.
* @dev A timestamp is safe if it is on or before the current overwrite period start time
* @param PERIOD_LENGTH The period length to use to calculate the period
* @param PERIOD_OFFSET The period offset to use to calculate the period
* @param _time The timestamp to check
* @return isSafe Whether or not the timestamp is safe
*/
function _hasFinalized(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
uint256 _time
) private view returns (bool) {
// It's safe if equal to the overwrite period start time, because the cumulative balance won't be impacted
return _time <= _currentOverwritePeriodStartedAt(PERIOD_LENGTH, PERIOD_OFFSET);
}
/**
* @notice Checks if the given timestamp is safe to perform a historic balance lookup on.
* @param PERIOD_LENGTH The period length to use to calculate the period
* @param PERIOD_OFFSET The period offset to use to calculate the period
* @param _timestamp The timestamp to check
*/
modifier requireFinalized(
uint32 PERIOD_LENGTH,
uint32 PERIOD_OFFSET,
uint256 _timestamp
) {
// The current period can still be changed; so the start of the period marks the beginning of unsafe timestamps.
uint256 overwritePeriodStartTime = _currentOverwritePeriodStartedAt(
PERIOD_LENGTH,
PERIOD_OFFSET
);
// timestamp == overwritePeriodStartTime doesn't matter, because the cumulative balance won't be impacted
if (_timestamp > overwritePeriodStartTime) {
revert TimestampNotFinalized(_timestamp, overwritePeriodStartTime);
}
_;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "ring-buffer-lib/RingBufferLib.sol";
/**
* @dev Sets max ring buffer length in the Account.observations Observation list.
* As users transfer/mint/burn tickets new Observation checkpoints are recorded.
* The current `MAX_CARDINALITY` guarantees a one year minimum, of accurate historical lookups.
* @dev The user Account.Account.cardinality parameter can NOT exceed the max cardinality variable.
* Preventing "corrupted" ring buffer lookup pointers and new observation checkpoints.
*/
uint16 constant MAX_CARDINALITY = 17520; // with min period of 1 hour, this allows for minimum two years of history
/**
* @title PoolTogether V5 Observation Library
* @author PoolTogether Inc. & G9 Software Inc.
* @notice This library allows one to store an array of timestamped values and efficiently search them.
* @dev Largely pulled from Uniswap V3 Oracle.sol: https://github.com/Uniswap/v3-core/blob/c05a0e2c8c08c460fb4d05cfdda30b3ad8deeaac/contracts/libraries/Oracle.sol
*/
library ObservationLib {
/**
* @notice Observation, which includes an amount and timestamp.
* @param cumulativeBalance the cumulative time-weighted balance at `timestamp`.
* @param balance `balance` at `timestamp`.
* @param timestamp Recorded `timestamp`.
*/
struct Observation {
uint128 cumulativeBalance;
uint96 balance;
uint32 timestamp;
}
/**
* @notice Fetches Observations `beforeOrAt` and `afterOrAt` a `_target`, eg: where [`beforeOrAt`, `afterOrAt`] is satisfied.
* The result may be the same Observation, or adjacent Observations.
* @dev The _target must fall within the boundaries of the provided _observations.
* Meaning the _target must be: older than the most recent Observation and younger, or the same age as, the oldest Observation.
* @dev If `_newestObservationIndex` is less than `_oldestObservationIndex`, it means that we've wrapped around the circular buffer.
* So the most recent observation will be at `_oldestObservationIndex + _cardinality - 1`, at the beginning of the circular buffer.
* @param _observations List of Observations to search through.
* @param _newestObservationIndex Index of the newest Observation. Right side of the circular buffer.
* @param _oldestObservationIndex Index of the oldest Observation. Left side of the circular buffer.
* @param _target Timestamp at which we are searching the Observation.
* @param _cardinality Cardinality of the circular buffer we are searching through.
* @return beforeOrAt Observation recorded before, or at, the target.
* @return beforeOrAtIndex Index of observation recorded before, or at, the target.
* @return afterOrAt Observation recorded at, or after, the target.
* @return afterOrAtIndex Index of observation recorded at, or after, the target.
*/
function binarySearch(
Observation[MAX_CARDINALITY] storage _observations,
uint24 _newestObservationIndex,
uint24 _oldestObservationIndex,
uint32 _target,
uint16 _cardinality
)
internal
view
returns (
Observation memory beforeOrAt,
uint16 beforeOrAtIndex,
Observation memory afterOrAt,
uint16 afterOrAtIndex
)
{
uint256 leftSide = _oldestObservationIndex;
uint256 rightSide = _newestObservationIndex < leftSide
? leftSide + _cardinality - 1
: _newestObservationIndex;
uint256 currentIndex;
while (true) {
// We start our search in the middle of the `leftSide` and `rightSide`.
// After each iteration, we narrow down the search to the left or the right side while still starting our search in the middle.
currentIndex = (leftSide + rightSide) / 2;
beforeOrAtIndex = uint16(RingBufferLib.wrap(currentIndex, _cardinality));
beforeOrAt = _observations[beforeOrAtIndex];
uint32 beforeOrAtTimestamp = beforeOrAt.timestamp;
afterOrAtIndex = uint16(RingBufferLib.nextIndex(currentIndex, _cardinality));
afterOrAt = _observations[afterOrAtIndex];
bool targetAfterOrAt = beforeOrAtTimestamp <= _target;
// Check if we've found the corresponding Observation.
if (targetAfterOrAt && _target <= afterOrAt.timestamp) {
break;
}
// If `beforeOrAtTimestamp` is greater than `_target`, then we keep searching lower. To the left of the current index.
if (!targetAfterOrAt) {
rightSide = currentIndex - 1;
} else {
// Otherwise, we keep searching higher. To the right of the current index.
leftSide = currentIndex + 1;
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/**
* NOTE: There is a difference in meaning between "cardinality" and "count":
* - cardinality is the physical size of the ring buffer (i.e. max elements).
* - count is the number of elements in the buffer, which may be less than cardinality.
*/
library RingBufferLib {
/**
* @notice Returns wrapped TWAB index.
* @dev In order to navigate the TWAB circular buffer, we need to use the modulo operator.
* @dev For example, if `_index` is equal to 32 and the TWAB circular buffer is of `_cardinality` 32,
* it will return 0 and will point to the first element of the array.
* @param _index Index used to navigate through the TWAB circular buffer.
* @param _cardinality TWAB buffer cardinality.
* @return TWAB index.
*/
function wrap(uint256 _index, uint256 _cardinality) internal pure returns (uint256) {
return _index % _cardinality;
}
/**
* @notice Computes the negative offset from the given index, wrapped by the cardinality.
* @dev We add `_cardinality` to `_index` to be able to offset even if `_amount` is superior to `_cardinality`.
* @param _index The index from which to offset
* @param _amount The number of indices to offset. This is subtracted from the given index.
* @param _count The number of elements in the ring buffer
* @return Offsetted index.
*/
function offset(
uint256 _index,
uint256 _amount,
uint256 _count
) internal pure returns (uint256) {
return wrap(_index + _count - _amount, _count);
}
/// @notice Returns the index of the last recorded TWAB
/// @param _nextIndex The next available twab index. This will be recorded to next.
/// @param _count The count of the TWAB history.
/// @return The index of the last recorded TWAB
function newestIndex(uint256 _nextIndex, uint256 _count)
internal
pure
returns (uint256)
{
if (_count == 0) {
return 0;
}
return wrap(_nextIndex + _count - 1, _count);
}
function oldestIndex(uint256 _nextIndex, uint256 _count, uint256 _cardinality)
internal
pure
returns (uint256)
{
if (_count < _cardinality) {
return 0;
} else {
return wrap(_nextIndex + _cardinality, _cardinality);
}
}
/// @notice Computes the ring buffer index that follows the given one, wrapped by cardinality
/// @param _index The index to increment
/// @param _cardinality The number of elements in the Ring Buffer
/// @return The next index relative to the given index. Will wrap around to 0 if the next index == cardinality
function nextIndex(uint256 _index, uint256 _cardinality)
internal
pure
returns (uint256)
{
return wrap(_index + 1, _cardinality);
}
/// @notice Computes the ring buffer index that preceeds the given one, wrapped by cardinality
/// @param _index The index to increment
/// @param _cardinality The number of elements in the Ring Buffer
/// @return The prev index relative to the given index. Will wrap around to the end if the prev index == 0
function prevIndex(uint256 _index, uint256 _cardinality)
internal
pure
returns (uint256)
{
return _index == 0 ? _cardinality - 1 : _index - 1;
}
}{
"remappings": [
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
"pt-v5-twab-controller/=lib/pt-v5-twab-controller/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/",
"ring-buffer-lib/=lib/pt-v5-twab-controller/lib/ring-buffer-lib/src/"
],
"optimizer": {
"enabled": false,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false,
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"contract TwabController","name":"_twabController","type":"address"},{"internalType":"contract IPrizePool","name":"_prizePool","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"EpochDurationLtDrawPeriod","type":"error"},{"inputs":[],"name":"EpochDurationNotMultipleOfDrawPeriod","type":"error"},{"inputs":[{"internalType":"uint64","name":"epochEndTimestamp","type":"uint64"}],"name":"EpochNotOver","type":"error"},{"inputs":[{"internalType":"uint8","name":"epochExtension","type":"uint8"},{"internalType":"uint8","name":"currentEpochs","type":"uint8"},{"internalType":"uint8","name":"maxEpochs","type":"uint8"}],"name":"ExceedsMaxEpochs","type":"error"},{"inputs":[{"internalType":"uint256","name":"gracePeriodEndTimestamp","type":"uint256"}],"name":"GracePeriodActive","type":"error"},{"inputs":[{"internalType":"uint8","name":"epochId","type":"uint8"},{"internalType":"uint8","name":"numberOfEpochs","type":"uint8"}],"name":"InvalidEpochId","type":"error"},{"inputs":[{"internalType":"uint8","name":"startEpochId","type":"uint8"},{"internalType":"uint8","name":"currentEpochId","type":"uint8"}],"name":"NoEpochsToClaim","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"creator","type":"address"}],"name":"OnlyPromotionCreator","type":"error"},{"inputs":[],"name":"PayeeZeroAddress","type":"error"},{"inputs":[],"name":"PrizePoolZeroAddress","type":"error"},{"inputs":[{"internalType":"uint256","name":"promotionId","type":"uint256"}],"name":"PromotionInactive","type":"error"},{"inputs":[],"name":"StartTimeLtFirstDrawOpensAt","type":"error"},{"inputs":[],"name":"StartTimeNotAlignedWithDraws","type":"error"},{"inputs":[{"internalType":"uint256","name":"received","type":"uint256"},{"internalType":"uint256","name":"expected","type":"uint256"}],"name":"TokensReceivedLessThanExpected","type":"error"},{"inputs":[],"name":"TwabControllerZeroAddress","type":"error"},{"inputs":[],"name":"ZeroEpochs","type":"error"},{"inputs":[],"name":"ZeroTokensPerEpoch","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"promotionId","type":"uint256"},{"indexed":true,"internalType":"contract IERC20","name":"token","type":"address"},{"indexed":false,"internalType":"uint40","name":"startTimestamp","type":"uint40"},{"indexed":false,"internalType":"uint104","name":"tokensPerEpoch","type":"uint104"},{"indexed":false,"internalType":"uint40","name":"epochDuration","type":"uint40"},{"indexed":false,"internalType":"uint8","name":"initialNumberOfEpochs","type":"uint8"}],"name":"PromotionCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"promotionId","type":"uint256"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"PromotionDestroyed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"promotionId","type":"uint256"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint8","name":"epochNumber","type":"uint8"}],"name":"PromotionEnded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"promotionId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"numberOfEpochs","type":"uint256"}],"name":"PromotionExtended","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"promotionId","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"epochClaimFlags","type":"bytes32"},{"indexed":true,"internalType":"address","name":"vault","type":"address"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"RewardsClaimed","type":"event"},{"inputs":[],"name":"GRACE_PERIOD","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SPONSORSHIP_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint64","name":"_timestamp","type":"uint64"}],"name":"calculateDrawIdAt","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_vault","type":"address"},{"internalType":"address","name":"_user","type":"address"},{"internalType":"uint256","name":"_promotionId","type":"uint256"},{"internalType":"uint8[]","name":"_epochIds","type":"uint8[]"}],"name":"calculateRewards","outputs":[{"internalType":"uint256[]","name":"rewards","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_vault","type":"address"},{"internalType":"address","name":"_user","type":"address"},{"internalType":"uint256","name":"_promotionId","type":"uint256"},{"internalType":"uint8","name":"_startEpochId","type":"uint8"}],"name":"claimRewardedEpochs","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_vault","type":"address"},{"internalType":"address","name":"_user","type":"address"},{"internalType":"uint256","name":"_promotionId","type":"uint256"},{"internalType":"uint8[]","name":"_epochIds","type":"uint8[]"}],"name":"claimRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ITwabRewards","name":"_twabRewards","type":"address"},{"internalType":"address","name":"_user","type":"address"},{"internalType":"uint256","name":"_promotionId","type":"uint256"},{"internalType":"uint8[]","name":"_epochIds","type":"uint8[]"}],"name":"claimTwabRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"promotionId","type":"uint256"},{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"user","type":"address"}],"name":"claimedEpochs","outputs":[{"internalType":"bytes32","name":"claimMask","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"_token","type":"address"},{"internalType":"uint40","name":"_startTimestamp","type":"uint40"},{"internalType":"uint104","name":"_tokensPerEpoch","type":"uint104"},{"internalType":"uint40","name":"_epochDuration","type":"uint40"},{"internalType":"uint8","name":"_numberOfEpochs","type":"uint8"}],"name":"createPromotion","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_promotionId","type":"uint256"},{"internalType":"address","name":"_to","type":"address"}],"name":"destroyPromotion","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_promotionId","type":"uint256"},{"internalType":"address","name":"_to","type":"address"}],"name":"endPromotion","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_epochClaimFlags","type":"bytes32"}],"name":"epochBytesToIdArray","outputs":[{"internalType":"uint8[]","name":"","type":"uint8[]"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint8[]","name":"_epochIds","type":"uint8[]"}],"name":"epochIdArrayToBytes","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint48","name":"_promotionStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"_promotionEpochDuration","type":"uint48"},{"internalType":"uint8","name":"_epochId","type":"uint8"}],"name":"epochRanges","outputs":[{"internalType":"uint48","name":"epochStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"epochEndTimestamp","type":"uint48"},{"internalType":"uint24","name":"epochStartDrawId","type":"uint24"},{"internalType":"uint24","name":"epochEndDrawId","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_promotionId","type":"uint256"},{"internalType":"uint8","name":"_epochId","type":"uint8"}],"name":"epochRangesForPromotion","outputs":[{"internalType":"uint48","name":"epochStartTimestamp","type":"uint48"},{"internalType":"uint48","name":"epochEndTimestamp","type":"uint48"},{"internalType":"uint24","name":"epochStartDrawId","type":"uint24"},{"internalType":"uint24","name":"epochEndDrawId","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_promotionId","type":"uint256"},{"internalType":"uint8","name":"_numberOfEpochs","type":"uint8"}],"name":"extendPromotion","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_promotionId","type":"uint256"},{"internalType":"uint256","name":"_timestamp","type":"uint256"}],"name":"getEpochIdAt","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_promotionId","type":"uint256"}],"name":"getEpochIdNow","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_promotionId","type":"uint256"}],"name":"getPromotion","outputs":[{"components":[{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"uint40","name":"epochDuration","type":"uint40"},{"internalType":"uint40","name":"createdAt","type":"uint40"},{"internalType":"uint8","name":"numberOfEpochs","type":"uint8"},{"internalType":"uint40","name":"startTimestamp","type":"uint40"},{"internalType":"uint104","name":"tokensPerEpoch","type":"uint104"},{"internalType":"uint112","name":"rewardsUnclaimed","type":"uint112"}],"internalType":"struct Promotion","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_promotionId","type":"uint256"}],"name":"getRemainingRewards","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_vault","type":"address"},{"internalType":"uint256","name":"_promotionId","type":"uint256"},{"internalType":"uint8","name":"_epochId","type":"uint8"}],"name":"getVaultRewardAmount","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"latestPromotionId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"prizePool","outputs":[{"internalType":"contract IPrizePool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"promotionCreators","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"twabController","outputs":[{"internalType":"contract TwabController","name":"","type":"address"}],"stateMutability":"view","type":"function"}]Contract Creation Code
61010060405234801562000011575f80fd5b50604051620057943803806200579483398181016040528101906200003791906200033f565b8173ffffffffffffffffffffffffffffffffffffffff165f73ffffffffffffffffffffffffffffffffffffffff16036200009d576040517f337302ae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff165f73ffffffffffffffffffffffffffffffffffffffff160362000103576040517f1761cbcc00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b8173ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff16815250508073ffffffffffffffffffffffffffffffffffffffff1660a08173ffffffffffffffffffffffffffffffffffffffff168152505060a05173ffffffffffffffffffffffffffffffffffffffff1663ed88b77f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015620001b7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620001dd9190620003c4565b65ffffffffffff1660c08165ffffffffffff168152505060a05173ffffffffffffffffffffffffffffffffffffffff1663c052b56e6040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000240573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620002669190620003c4565b65ffffffffffff1660e08165ffffffffffff16815250505050620003f4565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f620002b48262000289565b9050919050565b5f620002c782620002a8565b9050919050565b620002d981620002bb565b8114620002e4575f80fd5b50565b5f81519050620002f781620002ce565b92915050565b5f6200030982620002a8565b9050919050565b6200031b81620002fd565b811462000326575f80fd5b50565b5f81519050620003398162000310565b92915050565b5f806040838503121562000358576200035762000285565b5b5f6200036785828601620002e7565b92505060206200037a8582860162000329565b9150509250929050565b5f65ffffffffffff82169050919050565b620003a08162000384565b8114620003ab575f80fd5b50565b5f81519050620003be8162000395565b92915050565b5f60208284031215620003dc57620003db62000285565b5b5f620003eb84828501620003ae565b91505092915050565b60805160a05160c05160e051615311620004835f395f8181610870015281816108dd015281816117f1015261187c01525f81816108b4015281816117150152818161177f0152818161185b0152611f1301525f818161100c01528181612c340152612f6701525f818161166801528181611910015281816119c5015281816128950152612d0701526153115ff3fe608060405234801561000f575f80fd5b506004361061018c575f3560e01c8063719ce73e116100dc578063ac9650d811610095578063b7f9779b1161006f578063b7f9779b1461056b578063be4120071461059b578063be6ccf87146105cb578063c1a287e2146105fe5761018c565b8063ac9650d8146104ed578063ae4143cb1461051d578063b0812d7b1461054d5761018c565b8063719ce73e146103dc5780637dbf0a51146103fa57806381c84f7f1461042a5780638346e96b1461045a578063a3dc5b921461048a578063a4958845146104bd5761018c565b806320555db1116101495780635bbf224f116101235780635bbf224f1461032e5780635ffe152d1461035e57806362f0c0fe1461038e5780636aa72a67146103be5761018c565b806320555db11461029e57806339fe3913146102ce5780634c340e60146102fe5761018c565b806308ec9dcf14610190578063095d488a146101c0578063096fe668146101de5780630ea90ff51461020e578063120468a01461023e57806314fdecca1461026e575b5f80fd5b6101aa60048036038101906101a591906136b2565b61061c565b6040516101b79190613745565b60405180910390f35b6101c86106a7565b6040516101d5919061376d565b60405180910390f35b6101f860048036038101906101f391906137bc565b6106ac565b6040516102059190613814565b60405180910390f35b6102286004803603810190610223919061386a565b61086d565b60405161023591906138b2565b60405180910390f35b610258600480360381019061025391906138cb565b61092b565b6040516102659190613814565b60405180910390f35b61028860048036038101906102839190613909565b610b2b565b6040516102959190613a98565b60405180910390f35b6102b860048036038101906102b391906138cb565b610b43565b6040516102c59190613814565b60405180910390f35b6102e860048036038101906102e39190613909565b610de9565b6040516102f59190613ac0565b60405180910390f35b61031860048036038101906103139190613ad9565b610e1e565b6040516103259190613b41565b60405180910390f35b61034860048036038101906103439190613b5a565b610e49565b6040516103559190613745565b60405180910390f35b61037860048036038101906103739190613bbe565b610ee9565b6040516103859190613745565b60405180910390f35b6103a860048036038101906103a39190613c6c565b610f10565b6040516103b59190613d3f565b60405180910390f35b6103c6611004565b6040516103d39190613745565b60405180910390f35b6103e461100a565b6040516103f19190613d7f565b60405180910390f35b610414600480360381019061040f9190613bbe565b61102e565b6040516104219190613e4f565b60405180910390f35b610444600480360381019061043f9190613909565b611100565b604051610451919061376d565b60405180910390f35b610474600480360381019061046f9190613e6f565b611130565b6040516104819190613b41565b60405180910390f35b6104a4600480360381019061049f91906137bc565b611188565b6040516104b49493929190613eda565b60405180910390f35b6104d760048036038101906104d29190613909565b61134a565b6040516104e49190613f47565b60405180910390f35b61050760048036038101906105029190613fb5565b611373565b6040516105149190614145565b60405180910390f35b61053760048036038101906105329190614165565b611551565b6040516105449190613f47565b60405180910390f35b610555611666565b60405161056291906141d5565b60405180910390f35b610585600480360381019061058091906141ee565b61168a565b6040516105929190613ac0565b60405180910390f35b6105b560048036038101906105b091906142bb565b6116c1565b6040516105c29190613745565b60405180910390f35b6105e560048036038101906105e0919061435c565b611ece565b6040516105f59493929190613eda565b60405180910390f35b610606611f5d565b60405161061391906143ca565b60405180910390f35b5f8573ffffffffffffffffffffffffffffffffffffffff1663b2456c3a868686866040518563ffffffff1660e01b815260040161065c9493929190614469565b6020604051808303815f875af1158015610678573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061069c91906144bb565b905095945050505050565b600181565b5f6106b682611f64565b5f6106c084611fa3565b90506106cc848261213f565b5f816060015190508060ff6106e19190614513565b60ff168460ff16111561073057838160ff6040517fa5bd653500000000000000000000000000000000000000000000000000000000815260040161072793929190614547565b60405180910390fd5b838161073c919061457c565b5f808781526020019081526020015f205f01601e6101000a81548160ff021916908360ff1602179055505f6107918360a001516cffffffffffffffffffffffffff168660ff1661078c91906145b0565b61218f565b9050808360c001516107a391906145f1565b5f808881526020019081526020015f2060010160126101000a8154816dffffffffffffffffffffffffffff02191690836dffffffffffffffffffffffffffff1602179055506108283330836dffffffffffffffffffffffffffff16865f015173ffffffffffffffffffffffffffffffffffffffff166121eb909392919063ffffffff16565b857fa9527ed49c1c2ab5449cfef5b611076ce228a0a0de4534874963b83abb6e7b46866040516108589190614662565b60405180910390a26001935050505092915050565b5f7f000000000000000000000000000000000000000000000000000000000000000065ffffffffffff168267ffffffffffffffff1610156108b0575f9050610926565b60017f000000000000000000000000000000000000000000000000000000000000000065ffffffffffff167f000000000000000000000000000000000000000000000000000000000000000065ffffffffffff168461090f919061467b565b61091991906146e3565b6109239190614713565b90505b919050565b5f8173ffffffffffffffffffffffffffffffffffffffff165f73ffffffffffffffffffffffffffffffffffffffff1603610991576040517f07b6dbc700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f61099b84611fa3565b90506109d660015f8681526020019081526020015f205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16612274565b6109e0848261213f565b5f610a01826080015164ffffffffff16836020015164ffffffffff166122e9565b9050805f808781526020019081526020015f205f01601e6101000a81548160ff021916908360ff1602179055505f610a38836122fd565b9050808360c00151610a4a9190614749565b5f808881526020019081526020015f2060010160126101000a8154816dffffffffffffffffffffffffffff02191690836dffffffffffffffffffffffffffff160217905550610acd85826dffffffffffffffffffffffffffff16855f015173ffffffffffffffffffffffffffffffffffffffff1661236d9092919063ffffffff16565b8473ffffffffffffffffffffffffffffffffffffffff16867f98f89153fa6ee40b2edcd2e1ce4a5a9edfb2f74818016fc24e6cfe7b6fcd12a98385604051610b169291906147ba565b60405180910390a36001935050505092915050565b610b3361349e565b610b3c82611fa3565b9050919050565b5f8173ffffffffffffffffffffffffffffffffffffffff165f73ffffffffffffffffffffffffffffffffffffffff1603610ba9576040517f07b6dbc700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f610bb384611fa3565b9050610bee60015f8681526020019081526020015f205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16612274565b5f610bf8826123f3565b90505f826040015164ffffffffff1690505f624f1a0063ffffffff16828410610c215783610c23565b825b610c2d91906147e1565b905080421015610c7457806040517f948fa73e000000000000000000000000000000000000000000000000000000008152600401610c6b9190613745565b60405180910390fd5b5f8460c001516dffffffffffffffffffffffffffff1690505f808981526020019081526020015f205f8082015f6101000a81549073ffffffffffffffffffffffffffffffffffffffff02191690555f820160146101000a81549064ffffffffff02191690555f820160196101000a81549064ffffffffff02191690555f8201601e6101000a81549060ff0219169055600182015f6101000a81549064ffffffffff02191690556001820160056101000a8154906cffffffffffffffffffffffffff02191690556001820160126101000a8154906dffffffffffffffffffffffffffff02191690555050610d8b8782875f015173ffffffffffffffffffffffffffffffffffffffff1661236d9092919063ffffffff16565b8673ffffffffffffffffffffffffffffffffffffffff16887f6f804f2ef186cd4b2a6740c084b86f557a497a1fcf3a6b073068a55c51187b6f83604051610dd29190613745565b60405180910390a360019550505050505092915050565b5f80610df483611fa3565b9050610e16816080015164ffffffffff16826020015164ffffffffff166122e9565b915050919050565b6003602052825f5260405f20602052815f5260405f20602052805f5260405f205f9250925050505481565b5f805f610e5585610de9565b90508360ff168160ff1611610ea35783816040517fb53dc8f5000000000000000000000000000000000000000000000000000000008152600401610e9a929190614814565b60405180910390fd5b5f8490505b8160ff168160ff161015610ecf57610ec08382612416565b92508080600101915050610ea8565b50610edd878787858861242b565b92505050949350505050565b5f80610ef58484611130565b9050610f04878787845f61242b565b91505095945050505050565b60605f805f90505b610100811015610f4957610f2c8482612831565b15610f3e5781610f3b9061483b565b91505b806001019050610f18565b505f8160ff1667ffffffffffffffff811115610f6857610f67614863565b5b604051908082528060200260200182016040528015610f965781602001602082028036833780820191505090505b5090505f805b610100811015610ff857610fb08682612831565b15610fed5780838380610fc29061483b565b945060ff1681518110610fd857610fd7614890565b5b602002602001019060ff16908160ff16815250505b806001019050610f9c565b50819350505050919050565b60025481565b7f000000000000000000000000000000000000000000000000000000000000000081565b60608282905067ffffffffffffffff81111561104d5761104c614863565b5b60405190808252806020026020018201604052801561107b5781602001602082028036833780820191505090505b5090505f61108885611fa3565b90505f5b848490508110156110f5576110cb888888858989878181106110b1576110b0614890565b5b90506020020160208101906110c691906148bd565b61284d565b8382815181106110de576110dd614890565b5b60200260200101818152505080600101905061108c565b505095945050505050565b6001602052805f5260405f205f915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b5f805f5b8484905081101561117d576111708286868481811061115657611155614890565b5b905060200201602081019061116b91906148bd565b612416565b9150806001019050611134565b508091505092915050565b5f805f805f805f8881526020019081526020015f206040518060e00160405290815f82015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020015f820160149054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f820160199054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f8201601e9054906101000a900460ff1660ff1660ff168152602001600182015f9054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020016001820160059054906101000a90046cffffffffffffffffffffffffff166cffffffffffffffffffffffffff166cffffffffffffffffffffffffff1681526020016001820160129054906101000a90046dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff16815250509050611338816080015164ffffffffff16826020015164ffffffffff1688611ece565b94509450945094505092959194509250565b5f61135c61135783611fa3565b6122fd565b6dffffffffffffffffffffffffffff169050919050565b60605f61137e612a31565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461141e575f366113ba612a38565b5f3690506113c891906148e8565b9080926113d793929190614923565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f81840152601f19601f8201169050808301925050505050505061146c565b5f67ffffffffffffffff81111561143857611437614863565b5b6040519080825280601f01601f19166020018201604052801561146a5781602001600182028036833780820191505090505b505b90508383905067ffffffffffffffff81111561148b5761148a614863565b5b6040519080825280602002602001820160405280156114be57816020015b60608152602001906001900390816114a95790505b5091505f5b848490508110156115495761151e308686848181106114e5576114e4614890565b5b90506020028101906114f79190614969565b8560405160200161150a93929190614a37565b604051602081830303815290604052612a3c565b83828151811061153157611530614890565b5b602002602001018190525080806001019150506114c3565b505092915050565b5f8061155c84611fa3565b90505f805f80611583856080015164ffffffffff16866020015164ffffffffff1689611ece565b93509350935093506115a28786606001518565ffffffffffff16612a69565b5f6115b289898c88888888612b09565b90505f81602001516fffffffffffffffffffffffffffffffff16036115df575f965050505050505061165f565b5f6115ec8a8a8686612ec1565b90505f82602001516fffffffffffffffffffffffffffffffff168860a001516cffffffffffffffffffffffffff1661162491906145b0565b90505f825f01516fffffffffffffffffffffffffffffffff169050611653818361164e9190614a5c565b6130a3565b99505050505050505050505b9392505050565b7f000000000000000000000000000000000000000000000000000000000000000081565b5f8061169584611fa3565b90506116b8816080015164ffffffffff16826020015164ffffffffff1685613101565b91505092915050565b5f80846cffffffffffffffffffffffffff160361170a576040517f9e0bcf1b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61171382611f64565b7f000000000000000000000000000000000000000000000000000000000000000065ffffffffffff168364ffffffffff16101561177c576040517f9ea02d5d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f7f00000000000000000000000000000000000000000000000000000000000000008464ffffffffff166117b09190614a8c565b65ffffffffffff16146117ef576040517f51a845f600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000065ffffffffffff168564ffffffffff161015611858576040517f17c409d000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f7f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000008764ffffffffff166118ad9190614abc565b6118b79190614a8c565b65ffffffffffff16146118f6576040517f3bd76d4800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600173ffffffffffffffffffffffffffffffffffffffff167f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663b5f783a888306040518363ffffffff1660e01b8152600401611969929190614af5565b602060405180830381865afa158015611984573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119a89190614b30565b73ffffffffffffffffffffffffffffffffffffffff1614611a4d577f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16638ab656868760016040518363ffffffff1660e01b8152600401611a1f929190614af5565b5f604051808303815f87803b158015611a36575f80fd5b505af1158015611a48573d5f803e3d5ffd5b505050505b5f6001600254611a5d91906147e1565b9050806002819055505f611a8d8460ff16876cffffffffffffffffffffffffff16611a8891906145b0565b61218f565b90503360015f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040518060e001604052808973ffffffffffffffffffffffffffffffffffffffff1681526020018664ffffffffff168152602001611b1b4261313e565b64ffffffffff1681526020018560ff1681526020018864ffffffffff168152602001876cffffffffffffffffffffffffff168152602001826dffffffffffffffffffffffffffff168152505f808481526020019081526020015f205f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548164ffffffffff021916908364ffffffffff1602179055506040820151815f0160196101000a81548164ffffffffff021916908364ffffffffff1602179055506060820151815f01601e6101000a81548160ff021916908360ff1602179055506080820151816001015f6101000a81548164ffffffffff021916908364ffffffffff16021790555060a08201518160010160056101000a8154816cffffffffffffffffffffffffff02191690836cffffffffffffffffffffffffff16021790555060c08201518160010160126101000a8154816dffffffffffffffffffffffffffff02191690836dffffffffffffffffffffffffffff1602179055509050505f8873ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401611d03919061376d565b602060405180830381865afa158015611d1e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d4291906144bb565b9050611d813330846dffffffffffffffffffffffffffff168c73ffffffffffffffffffffffffffffffffffffffff166121eb909392919063ffffffff16565b5f8973ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401611dbb919061376d565b602060405180830381865afa158015611dd6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dfa91906144bb565b9050826dffffffffffffffffffffffffffff1682611e1891906147e1565b811015611e69578181611e2b91906148e8565b836040517f4512ed95000000000000000000000000000000000000000000000000000000008152600401611e60929190614b5b565b60405180910390fd5b8973ffffffffffffffffffffffffffffffffffffffff16847f3f5ba8197aa0b8fc2ed9032b8078309a0b00dd1e94618cdfb3748900d63e09a28b8b8b8b604051611eb69493929190614ba0565b60405180910390a38394505050505095945050505050565b5f805f808460ff1686611ee19190614be3565b87611eec9190614c1f565b93508584611efa9190614c1f565b9250611f0d8465ffffffffffff1661086d565b915060017f000000000000000000000000000000000000000000000000000000000000000087611f3d9190614c58565b83611f489190614713565b611f529190614c88565b905093509350935093565b624f1a0081565b8060ff165f03611fa0576040517fa36a16cf00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50565b611fab61349e565b5f805f8481526020019081526020015f206040518060e00160405290815f82015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020015f820160149054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f820160199054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f8201601e9054906101000a900460ff1660ff1660ff168152602001600182015f9054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020016001820160059054906101000a90046cffffffffffffffffffffffffff166cffffffffffffffffffffffffff166cffffffffffffffffffffffffff1681526020016001820160129054906101000a90046dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff1681525050905080915050919050565b42612149826123f3565b1161218b57816040517f1bffb7630000000000000000000000000000000000000000000000000000000081526004016121829190613745565b60405180910390fd5b5050565b5f6dffffffffffffffffffffffffffff80168211156121e3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016121da90614d3e565b60405180910390fd5b819050919050565b61226e846323b872dd60e01b85858560405160240161220c93929190614d5c565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050613191565b50505050565b8073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146122e65733816040517fe9d5e7b00000000000000000000000000000000000000000000000000000000081526004016122dd929190614af5565b60405180910390fd5b50565b5f6122f5838342613101565b905092915050565b5f612307826123f3565b4210612315575f9050612368565b612335826080015164ffffffffff16836020015164ffffffffff166122e9565b82606001516123449190614513565b60ff168260a001516123569190614d91565b6cffffffffffffffffffffffffff1690505b919050565b6123ee8363a9059cbb60e01b848460405160240161238c929190614dcd565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050613191565b505050565b5f816060015160ff1682602001510282608001510164ffffffffff169050919050565b5f8160ff1660015f1b901b8317905092915050565b5f805f808681526020019081526020015f206040518060e00160405290815f82015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020015f820160149054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f820160199054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f8201601e9054906101000a900460ff1660ff1660ff168152602001600182015f9054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020016001820160059054906101000a90046cffffffffffffffffffffffffff166cffffffffffffffffffffffffff166cffffffffffffffffffffffffff1681526020016001820160129054906101000a90046dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff168152505090505f8060035f8881526020019081526020015f205f8a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205490508019861695505f8560ff1690505b610100811015612690576126658782612831565b15612685576126778a8a8a878561284d565b8361268291906147e1565b92505b806001019050612651565b5085811760035f8981526020019081526020015f205f8b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550612747828460c001516dffffffffffffffffffffffffffff1661274291906148e8565b61218f565b5f808981526020019081526020015f2060010160126101000a8154816dffffffffffffffffffffffffffff02191690836dffffffffffffffffffffffffffff1602179055506127ba8883855f015173ffffffffffffffffffffffffffffffffffffffff1661236d9092919063ffffffff16565b8773ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff16887f6271dc4eb75db30bd9dad309127dd75e1f8e1f8deb6efc3300ad7da6f4b7c024898660405161281a929190614df4565b60405180910390a481935050505095945050505050565b5f806001808460ff16865f1c901c161490508091505092915050565b5f805f805f612873876080015164ffffffffff16886020015164ffffffffff1688611ece565b93509350935093506128928688606001518565ffffffffffff16612a69565b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663bb35799a8c8c88886040518563ffffffff1660e01b81526004016128f29493929190614e4b565b602060405180830381865afa15801561290d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061293191906144bb565b90505f811115612a1f575f61294b8a898e89898989612b09565b90505f81602001516fffffffffffffffffffffffffffffffff1603612978575f9650505050505050612a28565b5f6129858b8a8787612ec1565b90505f815f01516fffffffffffffffffffffffffffffffff1683602001516fffffffffffffffffffffffffffffffff168c60a001516cffffffffffffffffffffffffff166129d391906145b0565b6129dd9190614a5c565b90505f835f01516fffffffffffffffffffffffffffffffff168286612a0291906145b0565b612a0c9190614a5c565b9050809950505050505050505050612a28565b5f955050505050505b95945050505050565b5f33905090565b5f90565b6060612a6183836040518060600160405280602781526020016152b560279139613257565b905092915050565b8067ffffffffffffffff16421015612ab857806040517facb91bdb000000000000000000000000000000000000000000000000000000008152600401612aaf9190614e9d565b60405180910390fd5b8160ff168360ff1610612b045782826040517f5f62d754000000000000000000000000000000000000000000000000000000008152600401612afb929190614814565b60405180910390fd5b505050565b612b11613521565b60055f8981526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f208760ff166101008110612b7357612b72614890565b5b016040518060400160405290815f82015f9054906101000a90046fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff1681526020015f820160109054906101000a90046fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff168152505090505f81602001516fffffffffffffffffffffffffffffffff1603612eb657612cd37f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663a84037b68886866040518463ffffffff1660e01b8152600401612c8f93929190614eb6565b602060405180830381865afa158015612caa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612cce91906144bb565b6130a3565b81602001906fffffffffffffffffffffffffffffffff1690816fffffffffffffffffffffffffffffffff1681525050612da67f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff1663e7d7b2258888886040518463ffffffff1660e01b8152600401612d6293929190614eeb565b602060405180830381865afa158015612d7d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612da191906144bb565b6130a3565b815f01906fffffffffffffffffffffffffffffffff1690816fffffffffffffffffffffffffffffffff16815250508060055f8a81526020019081526020015f205f8873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f208860ff166101008110612e3757612e36614890565b5b015f820151815f015f6101000a8154816fffffffffffffffffffffffffffffffff02191690836fffffffffffffffffffffffffffffffff1602179055506020820151815f0160106101000a8154816fffffffffffffffffffffffffffffffff02191690836fffffffffffffffffffffffffffffffff1602179055509050505b979650505050505050565b612ec961355d565b60045f8681526020019081526020015f208460ff166101008110612ef057612eef614890565b5b016040518060200160405290815f82015f9054906101000a90046fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff168152505090505f815f01516fffffffffffffffffffffffffffffffff160361309b576130047f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166302abcc1e85856040518363ffffffff1660e01b8152600401612fc0929190614f20565b602060405180830381865afa158015612fdb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612fff91906144bb565b6130a3565b815f01906fffffffffffffffffffffffffffffffff1690816fffffffffffffffffffffffffffffffff16815250508060045f8781526020019081526020015f208560ff16610100811061305a57613059614890565b5b015f820151815f015f6101000a8154816fffffffffffffffffffffffffffffffff02191690836fffffffffffffffffffffffffffffffff1602179055509050505b949350505050565b5f6fffffffffffffffffffffffffffffffff80168211156130f9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016130f090614fb7565b60405180910390fd5b819050919050565b5f808483111561312157838584038161311d5761311c6146b6565b5b0490505b60ff801681116131315780613134565b60ff5b9150509392505050565b5f64ffffffffff8016821115613189576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161318090615045565b60405180910390fd5b819050919050565b5f6131f2826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c65648152508573ffffffffffffffffffffffffffffffffffffffff166132d99092919063ffffffff16565b90505f81511480613213575080806020019051810190613212919061508d565b5b613252576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161324990615128565b60405180910390fd5b505050565b60605f808573ffffffffffffffffffffffffffffffffffffffff16856040516132809190615146565b5f60405180830381855af49150503d805f81146132b8576040519150601f19603f3d011682016040523d82523d5f602084013e6132bd565b606091505b50915091506132ce868383876132f0565b925050509392505050565b60606132e784845f85613364565b90509392505050565b60608315613351575f835103613349576133098561342d565b613348576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161333f906151a6565b60405180910390fd5b5b82905061335c565b61335b838361344f565b5b949350505050565b6060824710156133a9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016133a090615234565b60405180910390fd5b5f808673ffffffffffffffffffffffffffffffffffffffff1685876040516133d19190615146565b5f6040518083038185875af1925050503d805f811461340b576040519150601f19603f3d011682016040523d82523d5f602084013e613410565b606091505b5091509150613421878383876132f0565b92505050949350505050565b5f808273ffffffffffffffffffffffffffffffffffffffff163b119050919050565b5f825111156134615781518083602001fd5b806040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016134959190615294565b60405180910390fd5b6040518060e001604052805f73ffffffffffffffffffffffffffffffffffffffff1681526020015f64ffffffffff1681526020015f64ffffffffff1681526020015f60ff1681526020015f64ffffffffff1681526020015f6cffffffffffffffffffffffffff1681526020015f6dffffffffffffffffffffffffffff1681525090565b60405180604001604052805f6fffffffffffffffffffffffffffffffff1681526020015f6fffffffffffffffffffffffffffffffff1681525090565b60405180602001604052805f6fffffffffffffffffffffffffffffffff1681525090565b5f80fd5b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6135b282613589565b9050919050565b5f6135c3826135a8565b9050919050565b6135d3816135b9565b81146135dd575f80fd5b50565b5f813590506135ee816135ca565b92915050565b6135fd816135a8565b8114613607575f80fd5b50565b5f81359050613618816135f4565b92915050565b5f819050919050565b6136308161361e565b811461363a575f80fd5b50565b5f8135905061364b81613627565b92915050565b5f80fd5b5f80fd5b5f80fd5b5f8083601f84011261367257613671613651565b5b8235905067ffffffffffffffff81111561368f5761368e613655565b5b6020830191508360208202830111156136ab576136aa613659565b5b9250929050565b5f805f805f608086880312156136cb576136ca613581565b5b5f6136d8888289016135e0565b95505060206136e98882890161360a565b94505060406136fa8882890161363d565b935050606086013567ffffffffffffffff81111561371b5761371a613585565b5b6137278882890161365d565b92509250509295509295909350565b61373f8161361e565b82525050565b5f6020820190506137585f830184613736565b92915050565b613767816135a8565b82525050565b5f6020820190506137805f83018461375e565b92915050565b5f60ff82169050919050565b61379b81613786565b81146137a5575f80fd5b50565b5f813590506137b681613792565b92915050565b5f80604083850312156137d2576137d1613581565b5b5f6137df8582860161363d565b92505060206137f0858286016137a8565b9150509250929050565b5f8115159050919050565b61380e816137fa565b82525050565b5f6020820190506138275f830184613805565b92915050565b5f67ffffffffffffffff82169050919050565b6138498161382d565b8114613853575f80fd5b50565b5f8135905061386481613840565b92915050565b5f6020828403121561387f5761387e613581565b5b5f61388c84828501613856565b91505092915050565b5f62ffffff82169050919050565b6138ac81613895565b82525050565b5f6020820190506138c55f8301846138a3565b92915050565b5f80604083850312156138e1576138e0613581565b5b5f6138ee8582860161363d565b92505060206138ff8582860161360a565b9150509250929050565b5f6020828403121561391e5761391d613581565b5b5f61392b8482850161363d565b91505092915050565b5f819050919050565b5f61395761395261394d84613589565b613934565b613589565b9050919050565b5f6139688261393d565b9050919050565b5f6139798261395e565b9050919050565b6139898161396f565b82525050565b5f64ffffffffff82169050919050565b6139a88161398f565b82525050565b6139b781613786565b82525050565b5f6cffffffffffffffffffffffffff82169050919050565b6139de816139bd565b82525050565b5f6dffffffffffffffffffffffffffff82169050919050565b613a06816139e4565b82525050565b60e082015f820151613a205f850182613980565b506020820151613a33602085018261399f565b506040820151613a46604085018261399f565b506060820151613a5960608501826139ae565b506080820151613a6c608085018261399f565b5060a0820151613a7f60a08501826139d5565b5060c0820151613a9260c08501826139fd565b50505050565b5f60e082019050613aab5f830184613a0c565b92915050565b613aba81613786565b82525050565b5f602082019050613ad35f830184613ab1565b92915050565b5f805f60608486031215613af057613aef613581565b5b5f613afd8682870161363d565b9350506020613b0e8682870161360a565b9250506040613b1f8682870161360a565b9150509250925092565b5f819050919050565b613b3b81613b29565b82525050565b5f602082019050613b545f830184613b32565b92915050565b5f805f8060808587031215613b7257613b71613581565b5b5f613b7f8782880161360a565b9450506020613b908782880161360a565b9350506040613ba18782880161363d565b9250506060613bb2878288016137a8565b91505092959194509250565b5f805f805f60808688031215613bd757613bd6613581565b5b5f613be48882890161360a565b9550506020613bf58882890161360a565b9450506040613c068882890161363d565b935050606086013567ffffffffffffffff811115613c2757613c26613585565b5b613c338882890161365d565b92509250509295509295909350565b613c4b81613b29565b8114613c55575f80fd5b50565b5f81359050613c6681613c42565b92915050565b5f60208284031215613c8157613c80613581565b5b5f613c8e84828501613c58565b91505092915050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b5f613ccb83836139ae565b60208301905092915050565b5f602082019050919050565b5f613ced82613c97565b613cf78185613ca1565b9350613d0283613cb1565b805f5b83811015613d32578151613d198882613cc0565b9750613d2483613cd7565b925050600181019050613d05565b5085935050505092915050565b5f6020820190508181035f830152613d578184613ce3565b905092915050565b5f613d698261395e565b9050919050565b613d7981613d5f565b82525050565b5f602082019050613d925f830184613d70565b92915050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b613dca8161361e565b82525050565b5f613ddb8383613dc1565b60208301905092915050565b5f602082019050919050565b5f613dfd82613d98565b613e078185613da2565b9350613e1283613db2565b805f5b83811015613e42578151613e298882613dd0565b9750613e3483613de7565b925050600181019050613e15565b5085935050505092915050565b5f6020820190508181035f830152613e678184613df3565b905092915050565b5f8060208385031215613e8557613e84613581565b5b5f83013567ffffffffffffffff811115613ea257613ea1613585565b5b613eae8582860161365d565b92509250509250929050565b5f65ffffffffffff82169050919050565b613ed481613eba565b82525050565b5f608082019050613eed5f830187613ecb565b613efa6020830186613ecb565b613f0760408301856138a3565b613f1460608301846138a3565b95945050505050565b5f6fffffffffffffffffffffffffffffffff82169050919050565b613f4181613f1d565b82525050565b5f602082019050613f5a5f830184613f38565b92915050565b5f8083601f840112613f7557613f74613651565b5b8235905067ffffffffffffffff811115613f9257613f91613655565b5b602083019150836020820283011115613fae57613fad613659565b5b9250929050565b5f8060208385031215613fcb57613fca613581565b5b5f83013567ffffffffffffffff811115613fe857613fe7613585565b5b613ff485828601613f60565b92509250509250929050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b5f81519050919050565b5f82825260208201905092915050565b5f5b83811015614060578082015181840152602081019050614045565b5f8484015250505050565b5f601f19601f8301169050919050565b5f61408582614029565b61408f8185614033565b935061409f818560208601614043565b6140a88161406b565b840191505092915050565b5f6140be838361407b565b905092915050565b5f602082019050919050565b5f6140dc82614000565b6140e6818561400a565b9350836020820285016140f88561401a565b805f5b85811015614133578484038952815161411485826140b3565b945061411f836140c6565b925060208a019950506001810190506140fb565b50829750879550505050505092915050565b5f6020820190508181035f83015261415d81846140d2565b905092915050565b5f805f6060848603121561417c5761417b613581565b5b5f6141898682870161360a565b935050602061419a8682870161363d565b92505060406141ab868287016137a8565b9150509250925092565b5f6141bf8261395e565b9050919050565b6141cf816141b5565b82525050565b5f6020820190506141e85f8301846141c6565b92915050565b5f806040838503121561420457614203613581565b5b5f6142118582860161363d565b92505060206142228582860161363d565b9150509250929050565b5f614236826135a8565b9050919050565b6142468161422c565b8114614250575f80fd5b50565b5f813590506142618161423d565b92915050565b6142708161398f565b811461427a575f80fd5b50565b5f8135905061428b81614267565b92915050565b61429a816139bd565b81146142a4575f80fd5b50565b5f813590506142b581614291565b92915050565b5f805f805f60a086880312156142d4576142d3613581565b5b5f6142e188828901614253565b95505060206142f28882890161427d565b9450506040614303888289016142a7565b93505060606143148882890161427d565b9250506080614325888289016137a8565b9150509295509295909350565b61433b81613eba565b8114614345575f80fd5b50565b5f8135905061435681614332565b92915050565b5f805f6060848603121561437357614372613581565b5b5f61438086828701614348565b935050602061439186828701614348565b92505060406143a2868287016137a8565b9150509250925092565b5f63ffffffff82169050919050565b6143c4816143ac565b82525050565b5f6020820190506143dd5f8301846143bb565b92915050565b5f819050919050565b5f6143fa60208401846137a8565b905092915050565b5f602082019050919050565b5f6144198385613ca1565b9350614424826143e3565b805f5b8581101561445c5761443982846143ec565b6144438882613cc0565b975061444e83614402565b925050600181019050614427565b5085925050509392505050565b5f60608201905061447c5f83018761375e565b6144896020830186613736565b818103604083015261449c81848661440e565b905095945050505050565b5f815190506144b581613627565b92915050565b5f602082840312156144d0576144cf613581565b5b5f6144dd848285016144a7565b91505092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61451d82613786565b915061452883613786565b9250828203905060ff811115614541576145406144e6565b5b92915050565b5f60608201905061455a5f830186613ab1565b6145676020830185613ab1565b6145746040830184613ab1565b949350505050565b5f61458682613786565b915061459183613786565b9250828201905060ff8111156145aa576145a96144e6565b5b92915050565b5f6145ba8261361e565b91506145c58361361e565b92508282026145d38161361e565b915082820484148315176145ea576145e96144e6565b5b5092915050565b5f6145fb826139e4565b9150614606836139e4565b925082820190506dffffffffffffffffffffffffffff81111561462c5761462b6144e6565b5b92915050565b5f61464c61464761464284613786565b613934565b61361e565b9050919050565b61465c81614632565b82525050565b5f6020820190506146755f830184614653565b92915050565b5f6146858261382d565b91506146908361382d565b9250828203905067ffffffffffffffff8111156146b0576146af6144e6565b5b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f6146ed8261382d565b91506146f88361382d565b925082614708576147076146b6565b5b828204905092915050565b5f61471d82613895565b915061472883613895565b9250828201905062ffffff811115614743576147426144e6565b5b92915050565b5f614753826139e4565b915061475e836139e4565b925082820390506dffffffffffffffffffffffffffff811115614784576147836144e6565b5b92915050565b5f6147a461479f61479a846139e4565b613934565b61361e565b9050919050565b6147b48161478a565b82525050565b5f6040820190506147cd5f8301856147ab565b6147da6020830184613ab1565b9392505050565b5f6147eb8261361e565b91506147f68361361e565b925082820190508082111561480e5761480d6144e6565b5b92915050565b5f6040820190506148275f830185613ab1565b6148346020830184613ab1565b9392505050565b5f61484582613786565b915060ff8203614858576148576144e6565b5b600182019050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f602082840312156148d2576148d1613581565b5b5f6148df848285016137a8565b91505092915050565b5f6148f28261361e565b91506148fd8361361e565b9250828203905081811115614915576149146144e6565b5b92915050565b5f80fd5b5f80fd5b5f80858511156149365761493561491b565b5b838611156149475761494661491f565b5b6001850283019150848603905094509492505050565b5f80fd5b5f80fd5b5f80fd5b5f80833560016020038436030381126149855761498461495d565b5b80840192508235915067ffffffffffffffff8211156149a7576149a6614961565b5b6020830192506001820236038313156149c3576149c2614965565b5b509250929050565b5f81905092915050565b828183375f83830152505050565b5f6149ee83856149cb565b93506149fb8385846149d5565b82840190509392505050565b5f614a1182614029565b614a1b81856149cb565b9350614a2b818560208601614043565b80840191505092915050565b5f614a438285876149e3565b9150614a4f8284614a07565b9150819050949350505050565b5f614a668261361e565b9150614a718361361e565b925082614a8157614a806146b6565b5b828204905092915050565b5f614a9682613eba565b9150614aa183613eba565b925082614ab157614ab06146b6565b5b828206905092915050565b5f614ac682613eba565b9150614ad183613eba565b9250828203905065ffffffffffff811115614aef57614aee6144e6565b5b92915050565b5f604082019050614b085f83018561375e565b614b15602083018461375e565b9392505050565b5f81519050614b2a816135f4565b92915050565b5f60208284031215614b4557614b44613581565b5b5f614b5284828501614b1c565b91505092915050565b5f604082019050614b6e5f830185613736565b614b7b60208301846147ab565b9392505050565b614b8b8161398f565b82525050565b614b9a816139bd565b82525050565b5f608082019050614bb35f830187614b82565b614bc06020830186614b91565b614bcd6040830185614b82565b614bda6060830184613ab1565b95945050505050565b5f614bed82613eba565b9150614bf883613eba565b9250828202614c0681613eba565b9150808214614c1857614c176144e6565b5b5092915050565b5f614c2982613eba565b9150614c3483613eba565b9250828201905065ffffffffffff811115614c5257614c516144e6565b5b92915050565b5f614c6282613eba565b9150614c6d83613eba565b925082614c7d57614c7c6146b6565b5b828204905092915050565b5f614c9282613895565b9150614c9d83613895565b9250828203905062ffffff811115614cb857614cb76144e6565b5b92915050565b5f82825260208201905092915050565b7f53616665436173743a2076616c756520646f65736e27742066697420696e20315f8201527f3132206269747300000000000000000000000000000000000000000000000000602082015250565b5f614d28602783614cbe565b9150614d3382614cce565b604082019050919050565b5f6020820190508181035f830152614d5581614d1c565b9050919050565b5f606082019050614d6f5f83018661375e565b614d7c602083018561375e565b614d896040830184613736565b949350505050565b5f614d9b826139bd565b9150614da6836139bd565b9250828202614db4816139bd565b9150808214614dc657614dc56144e6565b5b5092915050565b5f604082019050614de05f83018561375e565b614ded6020830184613736565b9392505050565b5f604082019050614e075f830185613b32565b614e146020830184613736565b9392505050565b5f614e35614e30614e2b84613eba565b613934565b61361e565b9050919050565b614e4581614e1b565b82525050565b5f608082019050614e5e5f83018761375e565b614e6b602083018661375e565b614e786040830185614e3c565b614e856060830184614e3c565b95945050505050565b614e978161382d565b82525050565b5f602082019050614eb05f830184614e8e565b92915050565b5f606082019050614ec95f83018661375e565b614ed660208301856138a3565b614ee360408301846138a3565b949350505050565b5f606082019050614efe5f83018661375e565b614f0b6020830185614e3c565b614f186040830184614e3c565b949350505050565b5f604082019050614f335f8301856138a3565b614f4060208301846138a3565b9392505050565b7f53616665436173743a2076616c756520646f65736e27742066697420696e20315f8201527f3238206269747300000000000000000000000000000000000000000000000000602082015250565b5f614fa1602783614cbe565b9150614fac82614f47565b604082019050919050565b5f6020820190508181035f830152614fce81614f95565b9050919050565b7f53616665436173743a2076616c756520646f65736e27742066697420696e20345f8201527f3020626974730000000000000000000000000000000000000000000000000000602082015250565b5f61502f602683614cbe565b915061503a82614fd5565b604082019050919050565b5f6020820190508181035f83015261505c81615023565b9050919050565b61506c816137fa565b8114615076575f80fd5b50565b5f8151905061508781615063565b92915050565b5f602082840312156150a2576150a1613581565b5b5f6150af84828501615079565b91505092915050565b7f5361666545524332303a204552433230206f7065726174696f6e20646964206e5f8201527f6f74207375636365656400000000000000000000000000000000000000000000602082015250565b5f615112602a83614cbe565b915061511d826150b8565b604082019050919050565b5f6020820190508181035f83015261513f81615106565b9050919050565b5f6151518284614a07565b915081905092915050565b7f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000005f82015250565b5f615190601d83614cbe565b915061519b8261515c565b602082019050919050565b5f6020820190508181035f8301526151bd81615184565b9050919050565b7f416464726573733a20696e73756666696369656e742062616c616e636520666f5f8201527f722063616c6c0000000000000000000000000000000000000000000000000000602082015250565b5f61521e602683614cbe565b9150615229826151c4565b604082019050919050565b5f6020820190508181035f83015261524b81615212565b9050919050565b5f81519050919050565b5f61526682615252565b6152708185614cbe565b9350615280818560208601614043565b6152898161406b565b840191505092915050565b5f6020820190508181035f8301526152ac818461525c565b90509291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a264697066735822122088079660ab1a69b253a33479e02a0b724dd02ff90a71d231160a6b8b1bb6ea5c64736f6c634300081800330000000000000000000000007e63601f7e28c758feccf8cdf02f6598694f44c600000000000000000000000045b2010d8a4f08b53c9fa7544c51dfd9733732cb
Deployed Bytecode
0x608060405234801561000f575f80fd5b506004361061018c575f3560e01c8063719ce73e116100dc578063ac9650d811610095578063b7f9779b1161006f578063b7f9779b1461056b578063be4120071461059b578063be6ccf87146105cb578063c1a287e2146105fe5761018c565b8063ac9650d8146104ed578063ae4143cb1461051d578063b0812d7b1461054d5761018c565b8063719ce73e146103dc5780637dbf0a51146103fa57806381c84f7f1461042a5780638346e96b1461045a578063a3dc5b921461048a578063a4958845146104bd5761018c565b806320555db1116101495780635bbf224f116101235780635bbf224f1461032e5780635ffe152d1461035e57806362f0c0fe1461038e5780636aa72a67146103be5761018c565b806320555db11461029e57806339fe3913146102ce5780634c340e60146102fe5761018c565b806308ec9dcf14610190578063095d488a146101c0578063096fe668146101de5780630ea90ff51461020e578063120468a01461023e57806314fdecca1461026e575b5f80fd5b6101aa60048036038101906101a591906136b2565b61061c565b6040516101b79190613745565b60405180910390f35b6101c86106a7565b6040516101d5919061376d565b60405180910390f35b6101f860048036038101906101f391906137bc565b6106ac565b6040516102059190613814565b60405180910390f35b6102286004803603810190610223919061386a565b61086d565b60405161023591906138b2565b60405180910390f35b610258600480360381019061025391906138cb565b61092b565b6040516102659190613814565b60405180910390f35b61028860048036038101906102839190613909565b610b2b565b6040516102959190613a98565b60405180910390f35b6102b860048036038101906102b391906138cb565b610b43565b6040516102c59190613814565b60405180910390f35b6102e860048036038101906102e39190613909565b610de9565b6040516102f59190613ac0565b60405180910390f35b61031860048036038101906103139190613ad9565b610e1e565b6040516103259190613b41565b60405180910390f35b61034860048036038101906103439190613b5a565b610e49565b6040516103559190613745565b60405180910390f35b61037860048036038101906103739190613bbe565b610ee9565b6040516103859190613745565b60405180910390f35b6103a860048036038101906103a39190613c6c565b610f10565b6040516103b59190613d3f565b60405180910390f35b6103c6611004565b6040516103d39190613745565b60405180910390f35b6103e461100a565b6040516103f19190613d7f565b60405180910390f35b610414600480360381019061040f9190613bbe565b61102e565b6040516104219190613e4f565b60405180910390f35b610444600480360381019061043f9190613909565b611100565b604051610451919061376d565b60405180910390f35b610474600480360381019061046f9190613e6f565b611130565b6040516104819190613b41565b60405180910390f35b6104a4600480360381019061049f91906137bc565b611188565b6040516104b49493929190613eda565b60405180910390f35b6104d760048036038101906104d29190613909565b61134a565b6040516104e49190613f47565b60405180910390f35b61050760048036038101906105029190613fb5565b611373565b6040516105149190614145565b60405180910390f35b61053760048036038101906105329190614165565b611551565b6040516105449190613f47565b60405180910390f35b610555611666565b60405161056291906141d5565b60405180910390f35b610585600480360381019061058091906141ee565b61168a565b6040516105929190613ac0565b60405180910390f35b6105b560048036038101906105b091906142bb565b6116c1565b6040516105c29190613745565b60405180910390f35b6105e560048036038101906105e0919061435c565b611ece565b6040516105f59493929190613eda565b60405180910390f35b610606611f5d565b60405161061391906143ca565b60405180910390f35b5f8573ffffffffffffffffffffffffffffffffffffffff1663b2456c3a868686866040518563ffffffff1660e01b815260040161065c9493929190614469565b6020604051808303815f875af1158015610678573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061069c91906144bb565b905095945050505050565b600181565b5f6106b682611f64565b5f6106c084611fa3565b90506106cc848261213f565b5f816060015190508060ff6106e19190614513565b60ff168460ff16111561073057838160ff6040517fa5bd653500000000000000000000000000000000000000000000000000000000815260040161072793929190614547565b60405180910390fd5b838161073c919061457c565b5f808781526020019081526020015f205f01601e6101000a81548160ff021916908360ff1602179055505f6107918360a001516cffffffffffffffffffffffffff168660ff1661078c91906145b0565b61218f565b9050808360c001516107a391906145f1565b5f808881526020019081526020015f2060010160126101000a8154816dffffffffffffffffffffffffffff02191690836dffffffffffffffffffffffffffff1602179055506108283330836dffffffffffffffffffffffffffff16865f015173ffffffffffffffffffffffffffffffffffffffff166121eb909392919063ffffffff16565b857fa9527ed49c1c2ab5449cfef5b611076ce228a0a0de4534874963b83abb6e7b46866040516108589190614662565b60405180910390a26001935050505092915050565b5f7f00000000000000000000000000000000000000000000000000000000664681e065ffffffffffff168267ffffffffffffffff1610156108b0575f9050610926565b60017f000000000000000000000000000000000000000000000000000000000001518065ffffffffffff167f00000000000000000000000000000000000000000000000000000000664681e065ffffffffffff168461090f919061467b565b61091991906146e3565b6109239190614713565b90505b919050565b5f8173ffffffffffffffffffffffffffffffffffffffff165f73ffffffffffffffffffffffffffffffffffffffff1603610991576040517f07b6dbc700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f61099b84611fa3565b90506109d660015f8681526020019081526020015f205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16612274565b6109e0848261213f565b5f610a01826080015164ffffffffff16836020015164ffffffffff166122e9565b9050805f808781526020019081526020015f205f01601e6101000a81548160ff021916908360ff1602179055505f610a38836122fd565b9050808360c00151610a4a9190614749565b5f808881526020019081526020015f2060010160126101000a8154816dffffffffffffffffffffffffffff02191690836dffffffffffffffffffffffffffff160217905550610acd85826dffffffffffffffffffffffffffff16855f015173ffffffffffffffffffffffffffffffffffffffff1661236d9092919063ffffffff16565b8473ffffffffffffffffffffffffffffffffffffffff16867f98f89153fa6ee40b2edcd2e1ce4a5a9edfb2f74818016fc24e6cfe7b6fcd12a98385604051610b169291906147ba565b60405180910390a36001935050505092915050565b610b3361349e565b610b3c82611fa3565b9050919050565b5f8173ffffffffffffffffffffffffffffffffffffffff165f73ffffffffffffffffffffffffffffffffffffffff1603610ba9576040517f07b6dbc700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f610bb384611fa3565b9050610bee60015f8681526020019081526020015f205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16612274565b5f610bf8826123f3565b90505f826040015164ffffffffff1690505f624f1a0063ffffffff16828410610c215783610c23565b825b610c2d91906147e1565b905080421015610c7457806040517f948fa73e000000000000000000000000000000000000000000000000000000008152600401610c6b9190613745565b60405180910390fd5b5f8460c001516dffffffffffffffffffffffffffff1690505f808981526020019081526020015f205f8082015f6101000a81549073ffffffffffffffffffffffffffffffffffffffff02191690555f820160146101000a81549064ffffffffff02191690555f820160196101000a81549064ffffffffff02191690555f8201601e6101000a81549060ff0219169055600182015f6101000a81549064ffffffffff02191690556001820160056101000a8154906cffffffffffffffffffffffffff02191690556001820160126101000a8154906dffffffffffffffffffffffffffff02191690555050610d8b8782875f015173ffffffffffffffffffffffffffffffffffffffff1661236d9092919063ffffffff16565b8673ffffffffffffffffffffffffffffffffffffffff16887f6f804f2ef186cd4b2a6740c084b86f557a497a1fcf3a6b073068a55c51187b6f83604051610dd29190613745565b60405180910390a360019550505050505092915050565b5f80610df483611fa3565b9050610e16816080015164ffffffffff16826020015164ffffffffff166122e9565b915050919050565b6003602052825f5260405f20602052815f5260405f20602052805f5260405f205f9250925050505481565b5f805f610e5585610de9565b90508360ff168160ff1611610ea35783816040517fb53dc8f5000000000000000000000000000000000000000000000000000000008152600401610e9a929190614814565b60405180910390fd5b5f8490505b8160ff168160ff161015610ecf57610ec08382612416565b92508080600101915050610ea8565b50610edd878787858861242b565b92505050949350505050565b5f80610ef58484611130565b9050610f04878787845f61242b565b91505095945050505050565b60605f805f90505b610100811015610f4957610f2c8482612831565b15610f3e5781610f3b9061483b565b91505b806001019050610f18565b505f8160ff1667ffffffffffffffff811115610f6857610f67614863565b5b604051908082528060200260200182016040528015610f965781602001602082028036833780820191505090505b5090505f805b610100811015610ff857610fb08682612831565b15610fed5780838380610fc29061483b565b945060ff1681518110610fd857610fd7614890565b5b602002602001019060ff16908160ff16815250505b806001019050610f9c565b50819350505050919050565b60025481565b7f00000000000000000000000045b2010d8a4f08b53c9fa7544c51dfd9733732cb81565b60608282905067ffffffffffffffff81111561104d5761104c614863565b5b60405190808252806020026020018201604052801561107b5781602001602082028036833780820191505090505b5090505f61108885611fa3565b90505f5b848490508110156110f5576110cb888888858989878181106110b1576110b0614890565b5b90506020020160208101906110c691906148bd565b61284d565b8382815181106110de576110dd614890565b5b60200260200101818152505080600101905061108c565b505095945050505050565b6001602052805f5260405f205f915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b5f805f5b8484905081101561117d576111708286868481811061115657611155614890565b5b905060200201602081019061116b91906148bd565b612416565b9150806001019050611134565b508091505092915050565b5f805f805f805f8881526020019081526020015f206040518060e00160405290815f82015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020015f820160149054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f820160199054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f8201601e9054906101000a900460ff1660ff1660ff168152602001600182015f9054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020016001820160059054906101000a90046cffffffffffffffffffffffffff166cffffffffffffffffffffffffff166cffffffffffffffffffffffffff1681526020016001820160129054906101000a90046dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff16815250509050611338816080015164ffffffffff16826020015164ffffffffff1688611ece565b94509450945094505092959194509250565b5f61135c61135783611fa3565b6122fd565b6dffffffffffffffffffffffffffff169050919050565b60605f61137e612a31565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461141e575f366113ba612a38565b5f3690506113c891906148e8565b9080926113d793929190614923565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f81840152601f19601f8201169050808301925050505050505061146c565b5f67ffffffffffffffff81111561143857611437614863565b5b6040519080825280601f01601f19166020018201604052801561146a5781602001600182028036833780820191505090505b505b90508383905067ffffffffffffffff81111561148b5761148a614863565b5b6040519080825280602002602001820160405280156114be57816020015b60608152602001906001900390816114a95790505b5091505f5b848490508110156115495761151e308686848181106114e5576114e4614890565b5b90506020028101906114f79190614969565b8560405160200161150a93929190614a37565b604051602081830303815290604052612a3c565b83828151811061153157611530614890565b5b602002602001018190525080806001019150506114c3565b505092915050565b5f8061155c84611fa3565b90505f805f80611583856080015164ffffffffff16866020015164ffffffffff1689611ece565b93509350935093506115a28786606001518565ffffffffffff16612a69565b5f6115b289898c88888888612b09565b90505f81602001516fffffffffffffffffffffffffffffffff16036115df575f965050505050505061165f565b5f6115ec8a8a8686612ec1565b90505f82602001516fffffffffffffffffffffffffffffffff168860a001516cffffffffffffffffffffffffff1661162491906145b0565b90505f825f01516fffffffffffffffffffffffffffffffff169050611653818361164e9190614a5c565b6130a3565b99505050505050505050505b9392505050565b7f0000000000000000000000007e63601f7e28c758feccf8cdf02f6598694f44c681565b5f8061169584611fa3565b90506116b8816080015164ffffffffff16826020015164ffffffffff1685613101565b91505092915050565b5f80846cffffffffffffffffffffffffff160361170a576040517f9e0bcf1b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61171382611f64565b7f000000000000000000000000000000000000000000000000000000000001518065ffffffffffff168364ffffffffff16101561177c576040517f9ea02d5d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f7f00000000000000000000000000000000000000000000000000000000000151808464ffffffffff166117b09190614a8c565b65ffffffffffff16146117ef576040517f51a845f600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000664681e065ffffffffffff168564ffffffffff161015611858576040517f17c409d000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f7f00000000000000000000000000000000000000000000000000000000000151807f00000000000000000000000000000000000000000000000000000000664681e08764ffffffffff166118ad9190614abc565b6118b79190614a8c565b65ffffffffffff16146118f6576040517f3bd76d4800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600173ffffffffffffffffffffffffffffffffffffffff167f0000000000000000000000007e63601f7e28c758feccf8cdf02f6598694f44c673ffffffffffffffffffffffffffffffffffffffff1663b5f783a888306040518363ffffffff1660e01b8152600401611969929190614af5565b602060405180830381865afa158015611984573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119a89190614b30565b73ffffffffffffffffffffffffffffffffffffffff1614611a4d577f0000000000000000000000007e63601f7e28c758feccf8cdf02f6598694f44c673ffffffffffffffffffffffffffffffffffffffff16638ab656868760016040518363ffffffff1660e01b8152600401611a1f929190614af5565b5f604051808303815f87803b158015611a36575f80fd5b505af1158015611a48573d5f803e3d5ffd5b505050505b5f6001600254611a5d91906147e1565b9050806002819055505f611a8d8460ff16876cffffffffffffffffffffffffff16611a8891906145b0565b61218f565b90503360015f8481526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506040518060e001604052808973ffffffffffffffffffffffffffffffffffffffff1681526020018664ffffffffff168152602001611b1b4261313e565b64ffffffffff1681526020018560ff1681526020018864ffffffffff168152602001876cffffffffffffffffffffffffff168152602001826dffffffffffffffffffffffffffff168152505f808481526020019081526020015f205f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151815f0160146101000a81548164ffffffffff021916908364ffffffffff1602179055506040820151815f0160196101000a81548164ffffffffff021916908364ffffffffff1602179055506060820151815f01601e6101000a81548160ff021916908360ff1602179055506080820151816001015f6101000a81548164ffffffffff021916908364ffffffffff16021790555060a08201518160010160056101000a8154816cffffffffffffffffffffffffff02191690836cffffffffffffffffffffffffff16021790555060c08201518160010160126101000a8154816dffffffffffffffffffffffffffff02191690836dffffffffffffffffffffffffffff1602179055509050505f8873ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401611d03919061376d565b602060405180830381865afa158015611d1e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d4291906144bb565b9050611d813330846dffffffffffffffffffffffffffff168c73ffffffffffffffffffffffffffffffffffffffff166121eb909392919063ffffffff16565b5f8973ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401611dbb919061376d565b602060405180830381865afa158015611dd6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dfa91906144bb565b9050826dffffffffffffffffffffffffffff1682611e1891906147e1565b811015611e69578181611e2b91906148e8565b836040517f4512ed95000000000000000000000000000000000000000000000000000000008152600401611e60929190614b5b565b60405180910390fd5b8973ffffffffffffffffffffffffffffffffffffffff16847f3f5ba8197aa0b8fc2ed9032b8078309a0b00dd1e94618cdfb3748900d63e09a28b8b8b8b604051611eb69493929190614ba0565b60405180910390a38394505050505095945050505050565b5f805f808460ff1686611ee19190614be3565b87611eec9190614c1f565b93508584611efa9190614c1f565b9250611f0d8465ffffffffffff1661086d565b915060017f000000000000000000000000000000000000000000000000000000000001518087611f3d9190614c58565b83611f489190614713565b611f529190614c88565b905093509350935093565b624f1a0081565b8060ff165f03611fa0576040517fa36a16cf00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50565b611fab61349e565b5f805f8481526020019081526020015f206040518060e00160405290815f82015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020015f820160149054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f820160199054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f8201601e9054906101000a900460ff1660ff1660ff168152602001600182015f9054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020016001820160059054906101000a90046cffffffffffffffffffffffffff166cffffffffffffffffffffffffff166cffffffffffffffffffffffffff1681526020016001820160129054906101000a90046dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff1681525050905080915050919050565b42612149826123f3565b1161218b57816040517f1bffb7630000000000000000000000000000000000000000000000000000000081526004016121829190613745565b60405180910390fd5b5050565b5f6dffffffffffffffffffffffffffff80168211156121e3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016121da90614d3e565b60405180910390fd5b819050919050565b61226e846323b872dd60e01b85858560405160240161220c93929190614d5c565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050613191565b50505050565b8073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146122e65733816040517fe9d5e7b00000000000000000000000000000000000000000000000000000000081526004016122dd929190614af5565b60405180910390fd5b50565b5f6122f5838342613101565b905092915050565b5f612307826123f3565b4210612315575f9050612368565b612335826080015164ffffffffff16836020015164ffffffffff166122e9565b82606001516123449190614513565b60ff168260a001516123569190614d91565b6cffffffffffffffffffffffffff1690505b919050565b6123ee8363a9059cbb60e01b848460405160240161238c929190614dcd565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050613191565b505050565b5f816060015160ff1682602001510282608001510164ffffffffff169050919050565b5f8160ff1660015f1b901b8317905092915050565b5f805f808681526020019081526020015f206040518060e00160405290815f82015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020015f820160149054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f820160199054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020015f8201601e9054906101000a900460ff1660ff1660ff168152602001600182015f9054906101000a900464ffffffffff1664ffffffffff1664ffffffffff1681526020016001820160059054906101000a90046cffffffffffffffffffffffffff166cffffffffffffffffffffffffff166cffffffffffffffffffffffffff1681526020016001820160129054906101000a90046dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff166dffffffffffffffffffffffffffff168152505090505f8060035f8881526020019081526020015f205f8a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205490508019861695505f8560ff1690505b610100811015612690576126658782612831565b15612685576126778a8a8a878561284d565b8361268291906147e1565b92505b806001019050612651565b5085811760035f8981526020019081526020015f205f8b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550612747828460c001516dffffffffffffffffffffffffffff1661274291906148e8565b61218f565b5f808981526020019081526020015f2060010160126101000a8154816dffffffffffffffffffffffffffff02191690836dffffffffffffffffffffffffffff1602179055506127ba8883855f015173ffffffffffffffffffffffffffffffffffffffff1661236d9092919063ffffffff16565b8773ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff16887f6271dc4eb75db30bd9dad309127dd75e1f8e1f8deb6efc3300ad7da6f4b7c024898660405161281a929190614df4565b60405180910390a481935050505095945050505050565b5f806001808460ff16865f1c901c161490508091505092915050565b5f805f805f612873876080015164ffffffffff16886020015164ffffffffff1688611ece565b93509350935093506128928688606001518565ffffffffffff16612a69565b5f7f0000000000000000000000007e63601f7e28c758feccf8cdf02f6598694f44c673ffffffffffffffffffffffffffffffffffffffff1663bb35799a8c8c88886040518563ffffffff1660e01b81526004016128f29493929190614e4b565b602060405180830381865afa15801561290d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061293191906144bb565b90505f811115612a1f575f61294b8a898e89898989612b09565b90505f81602001516fffffffffffffffffffffffffffffffff1603612978575f9650505050505050612a28565b5f6129858b8a8787612ec1565b90505f815f01516fffffffffffffffffffffffffffffffff1683602001516fffffffffffffffffffffffffffffffff168c60a001516cffffffffffffffffffffffffff166129d391906145b0565b6129dd9190614a5c565b90505f835f01516fffffffffffffffffffffffffffffffff168286612a0291906145b0565b612a0c9190614a5c565b9050809950505050505050505050612a28565b5f955050505050505b95945050505050565b5f33905090565b5f90565b6060612a6183836040518060600160405280602781526020016152b560279139613257565b905092915050565b8067ffffffffffffffff16421015612ab857806040517facb91bdb000000000000000000000000000000000000000000000000000000008152600401612aaf9190614e9d565b60405180910390fd5b8160ff168360ff1610612b045782826040517f5f62d754000000000000000000000000000000000000000000000000000000008152600401612afb929190614814565b60405180910390fd5b505050565b612b11613521565b60055f8981526020019081526020015f205f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f208760ff166101008110612b7357612b72614890565b5b016040518060400160405290815f82015f9054906101000a90046fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff1681526020015f820160109054906101000a90046fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff168152505090505f81602001516fffffffffffffffffffffffffffffffff1603612eb657612cd37f00000000000000000000000045b2010d8a4f08b53c9fa7544c51dfd9733732cb73ffffffffffffffffffffffffffffffffffffffff1663a84037b68886866040518463ffffffff1660e01b8152600401612c8f93929190614eb6565b602060405180830381865afa158015612caa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612cce91906144bb565b6130a3565b81602001906fffffffffffffffffffffffffffffffff1690816fffffffffffffffffffffffffffffffff1681525050612da67f0000000000000000000000007e63601f7e28c758feccf8cdf02f6598694f44c673ffffffffffffffffffffffffffffffffffffffff1663e7d7b2258888886040518463ffffffff1660e01b8152600401612d6293929190614eeb565b602060405180830381865afa158015612d7d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612da191906144bb565b6130a3565b815f01906fffffffffffffffffffffffffffffffff1690816fffffffffffffffffffffffffffffffff16815250508060055f8a81526020019081526020015f205f8873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f208860ff166101008110612e3757612e36614890565b5b015f820151815f015f6101000a8154816fffffffffffffffffffffffffffffffff02191690836fffffffffffffffffffffffffffffffff1602179055506020820151815f0160106101000a8154816fffffffffffffffffffffffffffffffff02191690836fffffffffffffffffffffffffffffffff1602179055509050505b979650505050505050565b612ec961355d565b60045f8681526020019081526020015f208460ff166101008110612ef057612eef614890565b5b016040518060200160405290815f82015f9054906101000a90046fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff166fffffffffffffffffffffffffffffffff168152505090505f815f01516fffffffffffffffffffffffffffffffff160361309b576130047f00000000000000000000000045b2010d8a4f08b53c9fa7544c51dfd9733732cb73ffffffffffffffffffffffffffffffffffffffff166302abcc1e85856040518363ffffffff1660e01b8152600401612fc0929190614f20565b602060405180830381865afa158015612fdb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612fff91906144bb565b6130a3565b815f01906fffffffffffffffffffffffffffffffff1690816fffffffffffffffffffffffffffffffff16815250508060045f8781526020019081526020015f208560ff16610100811061305a57613059614890565b5b015f820151815f015f6101000a8154816fffffffffffffffffffffffffffffffff02191690836fffffffffffffffffffffffffffffffff1602179055509050505b949350505050565b5f6fffffffffffffffffffffffffffffffff80168211156130f9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016130f090614fb7565b60405180910390fd5b819050919050565b5f808483111561312157838584038161311d5761311c6146b6565b5b0490505b60ff801681116131315780613134565b60ff5b9150509392505050565b5f64ffffffffff8016821115613189576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161318090615045565b60405180910390fd5b819050919050565b5f6131f2826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c65648152508573ffffffffffffffffffffffffffffffffffffffff166132d99092919063ffffffff16565b90505f81511480613213575080806020019051810190613212919061508d565b5b613252576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161324990615128565b60405180910390fd5b505050565b60605f808573ffffffffffffffffffffffffffffffffffffffff16856040516132809190615146565b5f60405180830381855af49150503d805f81146132b8576040519150601f19603f3d011682016040523d82523d5f602084013e6132bd565b606091505b50915091506132ce868383876132f0565b925050509392505050565b60606132e784845f85613364565b90509392505050565b60608315613351575f835103613349576133098561342d565b613348576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161333f906151a6565b60405180910390fd5b5b82905061335c565b61335b838361344f565b5b949350505050565b6060824710156133a9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016133a090615234565b60405180910390fd5b5f808673ffffffffffffffffffffffffffffffffffffffff1685876040516133d19190615146565b5f6040518083038185875af1925050503d805f811461340b576040519150601f19603f3d011682016040523d82523d5f602084013e613410565b606091505b5091509150613421878383876132f0565b92505050949350505050565b5f808273ffffffffffffffffffffffffffffffffffffffff163b119050919050565b5f825111156134615781518083602001fd5b806040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016134959190615294565b60405180910390fd5b6040518060e001604052805f73ffffffffffffffffffffffffffffffffffffffff1681526020015f64ffffffffff1681526020015f64ffffffffff1681526020015f60ff1681526020015f64ffffffffff1681526020015f6cffffffffffffffffffffffffff1681526020015f6dffffffffffffffffffffffffffff1681525090565b60405180604001604052805f6fffffffffffffffffffffffffffffffff1681526020015f6fffffffffffffffffffffffffffffffff1681525090565b60405180602001604052805f6fffffffffffffffffffffffffffffffff1681525090565b5f80fd5b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6135b282613589565b9050919050565b5f6135c3826135a8565b9050919050565b6135d3816135b9565b81146135dd575f80fd5b50565b5f813590506135ee816135ca565b92915050565b6135fd816135a8565b8114613607575f80fd5b50565b5f81359050613618816135f4565b92915050565b5f819050919050565b6136308161361e565b811461363a575f80fd5b50565b5f8135905061364b81613627565b92915050565b5f80fd5b5f80fd5b5f80fd5b5f8083601f84011261367257613671613651565b5b8235905067ffffffffffffffff81111561368f5761368e613655565b5b6020830191508360208202830111156136ab576136aa613659565b5b9250929050565b5f805f805f608086880312156136cb576136ca613581565b5b5f6136d8888289016135e0565b95505060206136e98882890161360a565b94505060406136fa8882890161363d565b935050606086013567ffffffffffffffff81111561371b5761371a613585565b5b6137278882890161365d565b92509250509295509295909350565b61373f8161361e565b82525050565b5f6020820190506137585f830184613736565b92915050565b613767816135a8565b82525050565b5f6020820190506137805f83018461375e565b92915050565b5f60ff82169050919050565b61379b81613786565b81146137a5575f80fd5b50565b5f813590506137b681613792565b92915050565b5f80604083850312156137d2576137d1613581565b5b5f6137df8582860161363d565b92505060206137f0858286016137a8565b9150509250929050565b5f8115159050919050565b61380e816137fa565b82525050565b5f6020820190506138275f830184613805565b92915050565b5f67ffffffffffffffff82169050919050565b6138498161382d565b8114613853575f80fd5b50565b5f8135905061386481613840565b92915050565b5f6020828403121561387f5761387e613581565b5b5f61388c84828501613856565b91505092915050565b5f62ffffff82169050919050565b6138ac81613895565b82525050565b5f6020820190506138c55f8301846138a3565b92915050565b5f80604083850312156138e1576138e0613581565b5b5f6138ee8582860161363d565b92505060206138ff8582860161360a565b9150509250929050565b5f6020828403121561391e5761391d613581565b5b5f61392b8482850161363d565b91505092915050565b5f819050919050565b5f61395761395261394d84613589565b613934565b613589565b9050919050565b5f6139688261393d565b9050919050565b5f6139798261395e565b9050919050565b6139898161396f565b82525050565b5f64ffffffffff82169050919050565b6139a88161398f565b82525050565b6139b781613786565b82525050565b5f6cffffffffffffffffffffffffff82169050919050565b6139de816139bd565b82525050565b5f6dffffffffffffffffffffffffffff82169050919050565b613a06816139e4565b82525050565b60e082015f820151613a205f850182613980565b506020820151613a33602085018261399f565b506040820151613a46604085018261399f565b506060820151613a5960608501826139ae565b506080820151613a6c608085018261399f565b5060a0820151613a7f60a08501826139d5565b5060c0820151613a9260c08501826139fd565b50505050565b5f60e082019050613aab5f830184613a0c565b92915050565b613aba81613786565b82525050565b5f602082019050613ad35f830184613ab1565b92915050565b5f805f60608486031215613af057613aef613581565b5b5f613afd8682870161363d565b9350506020613b0e8682870161360a565b9250506040613b1f8682870161360a565b9150509250925092565b5f819050919050565b613b3b81613b29565b82525050565b5f602082019050613b545f830184613b32565b92915050565b5f805f8060808587031215613b7257613b71613581565b5b5f613b7f8782880161360a565b9450506020613b908782880161360a565b9350506040613ba18782880161363d565b9250506060613bb2878288016137a8565b91505092959194509250565b5f805f805f60808688031215613bd757613bd6613581565b5b5f613be48882890161360a565b9550506020613bf58882890161360a565b9450506040613c068882890161363d565b935050606086013567ffffffffffffffff811115613c2757613c26613585565b5b613c338882890161365d565b92509250509295509295909350565b613c4b81613b29565b8114613c55575f80fd5b50565b5f81359050613c6681613c42565b92915050565b5f60208284031215613c8157613c80613581565b5b5f613c8e84828501613c58565b91505092915050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b5f613ccb83836139ae565b60208301905092915050565b5f602082019050919050565b5f613ced82613c97565b613cf78185613ca1565b9350613d0283613cb1565b805f5b83811015613d32578151613d198882613cc0565b9750613d2483613cd7565b925050600181019050613d05565b5085935050505092915050565b5f6020820190508181035f830152613d578184613ce3565b905092915050565b5f613d698261395e565b9050919050565b613d7981613d5f565b82525050565b5f602082019050613d925f830184613d70565b92915050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b613dca8161361e565b82525050565b5f613ddb8383613dc1565b60208301905092915050565b5f602082019050919050565b5f613dfd82613d98565b613e078185613da2565b9350613e1283613db2565b805f5b83811015613e42578151613e298882613dd0565b9750613e3483613de7565b925050600181019050613e15565b5085935050505092915050565b5f6020820190508181035f830152613e678184613df3565b905092915050565b5f8060208385031215613e8557613e84613581565b5b5f83013567ffffffffffffffff811115613ea257613ea1613585565b5b613eae8582860161365d565b92509250509250929050565b5f65ffffffffffff82169050919050565b613ed481613eba565b82525050565b5f608082019050613eed5f830187613ecb565b613efa6020830186613ecb565b613f0760408301856138a3565b613f1460608301846138a3565b95945050505050565b5f6fffffffffffffffffffffffffffffffff82169050919050565b613f4181613f1d565b82525050565b5f602082019050613f5a5f830184613f38565b92915050565b5f8083601f840112613f7557613f74613651565b5b8235905067ffffffffffffffff811115613f9257613f91613655565b5b602083019150836020820283011115613fae57613fad613659565b5b9250929050565b5f8060208385031215613fcb57613fca613581565b5b5f83013567ffffffffffffffff811115613fe857613fe7613585565b5b613ff485828601613f60565b92509250509250929050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b5f81519050919050565b5f82825260208201905092915050565b5f5b83811015614060578082015181840152602081019050614045565b5f8484015250505050565b5f601f19601f8301169050919050565b5f61408582614029565b61408f8185614033565b935061409f818560208601614043565b6140a88161406b565b840191505092915050565b5f6140be838361407b565b905092915050565b5f602082019050919050565b5f6140dc82614000565b6140e6818561400a565b9350836020820285016140f88561401a565b805f5b85811015614133578484038952815161411485826140b3565b945061411f836140c6565b925060208a019950506001810190506140fb565b50829750879550505050505092915050565b5f6020820190508181035f83015261415d81846140d2565b905092915050565b5f805f6060848603121561417c5761417b613581565b5b5f6141898682870161360a565b935050602061419a8682870161363d565b92505060406141ab868287016137a8565b9150509250925092565b5f6141bf8261395e565b9050919050565b6141cf816141b5565b82525050565b5f6020820190506141e85f8301846141c6565b92915050565b5f806040838503121561420457614203613581565b5b5f6142118582860161363d565b92505060206142228582860161363d565b9150509250929050565b5f614236826135a8565b9050919050565b6142468161422c565b8114614250575f80fd5b50565b5f813590506142618161423d565b92915050565b6142708161398f565b811461427a575f80fd5b50565b5f8135905061428b81614267565b92915050565b61429a816139bd565b81146142a4575f80fd5b50565b5f813590506142b581614291565b92915050565b5f805f805f60a086880312156142d4576142d3613581565b5b5f6142e188828901614253565b95505060206142f28882890161427d565b9450506040614303888289016142a7565b93505060606143148882890161427d565b9250506080614325888289016137a8565b9150509295509295909350565b61433b81613eba565b8114614345575f80fd5b50565b5f8135905061435681614332565b92915050565b5f805f6060848603121561437357614372613581565b5b5f61438086828701614348565b935050602061439186828701614348565b92505060406143a2868287016137a8565b9150509250925092565b5f63ffffffff82169050919050565b6143c4816143ac565b82525050565b5f6020820190506143dd5f8301846143bb565b92915050565b5f819050919050565b5f6143fa60208401846137a8565b905092915050565b5f602082019050919050565b5f6144198385613ca1565b9350614424826143e3565b805f5b8581101561445c5761443982846143ec565b6144438882613cc0565b975061444e83614402565b925050600181019050614427565b5085925050509392505050565b5f60608201905061447c5f83018761375e565b6144896020830186613736565b818103604083015261449c81848661440e565b905095945050505050565b5f815190506144b581613627565b92915050565b5f602082840312156144d0576144cf613581565b5b5f6144dd848285016144a7565b91505092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61451d82613786565b915061452883613786565b9250828203905060ff811115614541576145406144e6565b5b92915050565b5f60608201905061455a5f830186613ab1565b6145676020830185613ab1565b6145746040830184613ab1565b949350505050565b5f61458682613786565b915061459183613786565b9250828201905060ff8111156145aa576145a96144e6565b5b92915050565b5f6145ba8261361e565b91506145c58361361e565b92508282026145d38161361e565b915082820484148315176145ea576145e96144e6565b5b5092915050565b5f6145fb826139e4565b9150614606836139e4565b925082820190506dffffffffffffffffffffffffffff81111561462c5761462b6144e6565b5b92915050565b5f61464c61464761464284613786565b613934565b61361e565b9050919050565b61465c81614632565b82525050565b5f6020820190506146755f830184614653565b92915050565b5f6146858261382d565b91506146908361382d565b9250828203905067ffffffffffffffff8111156146b0576146af6144e6565b5b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f6146ed8261382d565b91506146f88361382d565b925082614708576147076146b6565b5b828204905092915050565b5f61471d82613895565b915061472883613895565b9250828201905062ffffff811115614743576147426144e6565b5b92915050565b5f614753826139e4565b915061475e836139e4565b925082820390506dffffffffffffffffffffffffffff811115614784576147836144e6565b5b92915050565b5f6147a461479f61479a846139e4565b613934565b61361e565b9050919050565b6147b48161478a565b82525050565b5f6040820190506147cd5f8301856147ab565b6147da6020830184613ab1565b9392505050565b5f6147eb8261361e565b91506147f68361361e565b925082820190508082111561480e5761480d6144e6565b5b92915050565b5f6040820190506148275f830185613ab1565b6148346020830184613ab1565b9392505050565b5f61484582613786565b915060ff8203614858576148576144e6565b5b600182019050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f602082840312156148d2576148d1613581565b5b5f6148df848285016137a8565b91505092915050565b5f6148f28261361e565b91506148fd8361361e565b9250828203905081811115614915576149146144e6565b5b92915050565b5f80fd5b5f80fd5b5f80858511156149365761493561491b565b5b838611156149475761494661491f565b5b6001850283019150848603905094509492505050565b5f80fd5b5f80fd5b5f80fd5b5f80833560016020038436030381126149855761498461495d565b5b80840192508235915067ffffffffffffffff8211156149a7576149a6614961565b5b6020830192506001820236038313156149c3576149c2614965565b5b509250929050565b5f81905092915050565b828183375f83830152505050565b5f6149ee83856149cb565b93506149fb8385846149d5565b82840190509392505050565b5f614a1182614029565b614a1b81856149cb565b9350614a2b818560208601614043565b80840191505092915050565b5f614a438285876149e3565b9150614a4f8284614a07565b9150819050949350505050565b5f614a668261361e565b9150614a718361361e565b925082614a8157614a806146b6565b5b828204905092915050565b5f614a9682613eba565b9150614aa183613eba565b925082614ab157614ab06146b6565b5b828206905092915050565b5f614ac682613eba565b9150614ad183613eba565b9250828203905065ffffffffffff811115614aef57614aee6144e6565b5b92915050565b5f604082019050614b085f83018561375e565b614b15602083018461375e565b9392505050565b5f81519050614b2a816135f4565b92915050565b5f60208284031215614b4557614b44613581565b5b5f614b5284828501614b1c565b91505092915050565b5f604082019050614b6e5f830185613736565b614b7b60208301846147ab565b9392505050565b614b8b8161398f565b82525050565b614b9a816139bd565b82525050565b5f608082019050614bb35f830187614b82565b614bc06020830186614b91565b614bcd6040830185614b82565b614bda6060830184613ab1565b95945050505050565b5f614bed82613eba565b9150614bf883613eba565b9250828202614c0681613eba565b9150808214614c1857614c176144e6565b5b5092915050565b5f614c2982613eba565b9150614c3483613eba565b9250828201905065ffffffffffff811115614c5257614c516144e6565b5b92915050565b5f614c6282613eba565b9150614c6d83613eba565b925082614c7d57614c7c6146b6565b5b828204905092915050565b5f614c9282613895565b9150614c9d83613895565b9250828203905062ffffff811115614cb857614cb76144e6565b5b92915050565b5f82825260208201905092915050565b7f53616665436173743a2076616c756520646f65736e27742066697420696e20315f8201527f3132206269747300000000000000000000000000000000000000000000000000602082015250565b5f614d28602783614cbe565b9150614d3382614cce565b604082019050919050565b5f6020820190508181035f830152614d5581614d1c565b9050919050565b5f606082019050614d6f5f83018661375e565b614d7c602083018561375e565b614d896040830184613736565b949350505050565b5f614d9b826139bd565b9150614da6836139bd565b9250828202614db4816139bd565b9150808214614dc657614dc56144e6565b5b5092915050565b5f604082019050614de05f83018561375e565b614ded6020830184613736565b9392505050565b5f604082019050614e075f830185613b32565b614e146020830184613736565b9392505050565b5f614e35614e30614e2b84613eba565b613934565b61361e565b9050919050565b614e4581614e1b565b82525050565b5f608082019050614e5e5f83018761375e565b614e6b602083018661375e565b614e786040830185614e3c565b614e856060830184614e3c565b95945050505050565b614e978161382d565b82525050565b5f602082019050614eb05f830184614e8e565b92915050565b5f606082019050614ec95f83018661375e565b614ed660208301856138a3565b614ee360408301846138a3565b949350505050565b5f606082019050614efe5f83018661375e565b614f0b6020830185614e3c565b614f186040830184614e3c565b949350505050565b5f604082019050614f335f8301856138a3565b614f4060208301846138a3565b9392505050565b7f53616665436173743a2076616c756520646f65736e27742066697420696e20315f8201527f3238206269747300000000000000000000000000000000000000000000000000602082015250565b5f614fa1602783614cbe565b9150614fac82614f47565b604082019050919050565b5f6020820190508181035f830152614fce81614f95565b9050919050565b7f53616665436173743a2076616c756520646f65736e27742066697420696e20345f8201527f3020626974730000000000000000000000000000000000000000000000000000602082015250565b5f61502f602683614cbe565b915061503a82614fd5565b604082019050919050565b5f6020820190508181035f83015261505c81615023565b9050919050565b61506c816137fa565b8114615076575f80fd5b50565b5f8151905061508781615063565b92915050565b5f602082840312156150a2576150a1613581565b5b5f6150af84828501615079565b91505092915050565b7f5361666545524332303a204552433230206f7065726174696f6e20646964206e5f8201527f6f74207375636365656400000000000000000000000000000000000000000000602082015250565b5f615112602a83614cbe565b915061511d826150b8565b604082019050919050565b5f6020820190508181035f83015261513f81615106565b9050919050565b5f6151518284614a07565b915081905092915050565b7f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000005f82015250565b5f615190601d83614cbe565b915061519b8261515c565b602082019050919050565b5f6020820190508181035f8301526151bd81615184565b9050919050565b7f416464726573733a20696e73756666696369656e742062616c616e636520666f5f8201527f722063616c6c0000000000000000000000000000000000000000000000000000602082015250565b5f61521e602683614cbe565b9150615229826151c4565b604082019050919050565b5f6020820190508181035f83015261524b81615212565b9050919050565b5f81519050919050565b5f61526682615252565b6152708185614cbe565b9350615280818560208601614043565b6152898161406b565b840191505092915050565b5f6020820190508181035f8301526152ac818461525c565b90509291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a264697066735822122088079660ab1a69b253a33479e02a0b724dd02ff90a71d231160a6b8b1bb6ea5c64736f6c63430008180033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000007e63601f7e28c758feccf8cdf02f6598694f44c600000000000000000000000045b2010d8a4f08b53c9fa7544c51dfd9733732cb
-----Decoded View---------------
Arg [0] : _twabController (address): 0x7e63601F7e28C758Feccf8CDF02F6598694f44C6
Arg [1] : _prizePool (address): 0x45b2010d8A4f08b53c9fa7544C51dFd9733732cb
-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 0000000000000000000000007e63601f7e28c758feccf8cdf02f6598694f44c6
Arg [1] : 00000000000000000000000045b2010d8a4f08b53c9fa7544c51dfd9733732cb
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$3,809.63
Net Worth in ETH
1.605822
Token Allocations
POOL
100.00%
Multichain Portfolio | 32 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|---|---|---|---|---|
| BASE | 100.00% | $0.050365 | 75,640.3553 | $3,809.63 |
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
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.