Contract Name:
YearnBoostedStaker
Contract Source Code:
<i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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
* ====
*
* [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://diligence.consensys.net/posts/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.5.11/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);
}
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// 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);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface 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].
*/
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);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// 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 "./IERC20Permit.sol";
import "./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));
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.22;
import {IERC20, SafeERC20} from "./SafeERC20.sol";
import {IERC20Metadata} from "./IERC20Metadata.sol";
contract YearnBoostedStaker {
using SafeERC20 for IERC20;
uint public immutable MAX_STAKE_GROWTH_WEEKS;
uint8 public immutable MAX_WEEK_BIT;
uint public immutable START_TIME;
IERC20 public immutable stakeToken;
// Account weight tracking state vars.
mapping(address account => AccountData data) public accountData;
mapping(address account => mapping(uint week => uint weight)) private accountWeeklyWeights;
mapping(address account => mapping(uint week => ToRealize weight)) public accountWeeklyToRealize;
mapping(address account => mapping(uint week => uint amount)) public accountWeeklyMaxStake;
// Global weight tracking stats vars.
uint112 public globalGrowthRate;
uint16 public globalLastUpdateWeek;
mapping(uint week => uint weight) private globalWeeklyWeights;
mapping(uint week => ToRealize weight) public globalWeeklyToRealize;
mapping(uint week => uint amount) public globalWeeklyMaxStake;
// Generic token interface.
uint public totalSupply;
uint8 public immutable decimals;
// Permissioned roles
address public owner;
address public pendingOwner;
mapping(address account => mapping(address caller => ApprovalStatus approvalStatus)) public approvedCaller;
mapping(address staker => bool approved) public approvedWeightedStaker;
struct ToRealize {
uint128 weightPersistent;
uint128 weight;
}
struct AccountData {
uint112 realizedStake; // Amount of stake that has fully realized weight.
uint112 pendingStake; // Amount of stake that has not yet fully realized weight.
uint16 lastUpdateWeek; // Week of last sync.
// One byte member to represent weeks in which an account has pending weight changes.
// A bit is set to true when the account has a non-zero token balance to be realized in
// the corresponding week. We use this as a "map", allowing us to reduce gas consumption
// by avoiding unnecessary lookups on weeks which an account has zero pending stake.
//
// Example: 01000001
// The left-most bit represents the final week of pendingStake.
// Therefore, we can see that account has stake updates to process only in weeks 7 and 1.
uint8 updateWeeksBitmap;
}
enum ApprovalStatus {
None, // 0. Default value, indicating no approval
StakeOnly, // 1. Approved for stake only
UnstakeOnly, // 2. Approved for unstake only
StakeAndUnstake // 3. Approved for both stake and unstake
}
event Staked(address indexed account, uint indexed week, uint amount, uint newUserWeight, uint weightAdded);
event Unstaked(address indexed account, uint indexed week, uint amount, uint newUserWeight, uint weightRemoved);
event ApprovedCallerSet(address indexed account, address indexed caller, ApprovalStatus status);
event OwnershipTransferred(address indexed newOwner);
event WeightedStakerSet(address indexed staker, bool approved);
/**
@param _token The token to be staked.
@param _max_stake_growth_weeks The number of weeks a stake will grow for.
Not including desposit week.
@param _start_time allows deployer to optionally set a custom start time.
useful if needed to line up with week count in another system.
Passing a value of 0 will start at block.timestamp.
@param _owner Owner is able to grant access to stake with max boost.
*/
constructor(address _token, uint _max_stake_growth_weeks, uint _start_time, address _owner) {
owner = _owner;
emit OwnershipTransferred(_owner);
stakeToken = IERC20(_token);
decimals = IERC20Metadata(_token).decimals();
require(
_max_stake_growth_weeks > 0 &&
_max_stake_growth_weeks <= 7,
"Invalid weeks"
);
MAX_STAKE_GROWTH_WEEKS = _max_stake_growth_weeks;
MAX_WEEK_BIT = uint8(1 << MAX_STAKE_GROWTH_WEEKS);
if (_start_time == 0){
START_TIME = block.timestamp;
}
else {
require(_start_time <= block.timestamp, "!Past");
START_TIME = _start_time;
}
}
/**
@notice Stake tokens into the staking contract.
@param _amount Amount of tokens to stake.
*/
function stake(uint _amount) external returns (uint) {
return _stake(msg.sender, _amount);
}
function stakeFor(address _account, uint _amount) external returns (uint) {
if (msg.sender != _account) {
ApprovalStatus status = approvedCaller[_account][msg.sender];
require(
status == ApprovalStatus.StakeAndUnstake ||
status == ApprovalStatus.StakeOnly,
"!Permission"
);
}
return _stake(_account, _amount);
}
function _stake(address _account, uint _amount) internal returns (uint) {
require(_amount > 1 && _amount < type(uint112).max, "invalid amount");
// Before going further, let's sync our account and global weights
uint systemWeek = getWeek();
(AccountData memory acctData, uint accountWeight) = _checkpointAccount(_account, systemWeek);
uint112 globalWeight = uint112(_checkpointGlobal(systemWeek));
uint weight = _amount >> 1;
_amount = weight << 1; // This helps prevent balance/weight discrepencies.
acctData.pendingStake += uint112(weight);
globalGrowthRate += uint112(weight);
uint realizeWeek = systemWeek + MAX_STAKE_GROWTH_WEEKS;
ToRealize memory toRealize = accountWeeklyToRealize[_account][realizeWeek];
toRealize.weight += uint128(weight);
toRealize.weightPersistent += uint128(weight);
accountWeeklyToRealize[_account][realizeWeek] = toRealize;
toRealize = globalWeeklyToRealize[realizeWeek];
toRealize.weight += uint128(weight);
toRealize.weightPersistent += uint128(weight);
globalWeeklyToRealize[realizeWeek] = toRealize;
accountWeeklyWeights[_account][systemWeek] = accountWeight + weight;
globalWeeklyWeights[systemWeek] = globalWeight + weight;
acctData.updateWeeksBitmap |= 1; // Use bitwise or to ensure bit is flipped at least weighted position.
accountData[_account] = acctData;
totalSupply += _amount;
stakeToken.safeTransferFrom(msg.sender, address(this), uint(_amount));
emit Staked(_account, systemWeek, _amount, accountWeight + weight, weight);
return _amount;
}
/**
@notice Allows an option for an approved helper to stake to any account at any weight week.
@dev A stake using this method only effects weight in current and future weeks. It does not backfill prior weeks.
@param _amount Amount to stake
@return amount of tokens staked
*/
function stakeAsMaxWeighted(address _account, uint _amount) external returns (uint) {
require(
approvedWeightedStaker[msg.sender],
"!approvedStaker"
);
require(_amount > 1 && _amount < type(uint112).max, "invalid amount");
// Before going further, let's sync our account and global weights
uint systemWeek = getWeek();
(AccountData memory acctData, uint accountWeight) = _checkpointAccount(_account, systemWeek);
uint112 globalWeight = uint112(_checkpointGlobal(systemWeek));
uint weight = _amount >> 1;
_amount = weight << 1;
acctData.realizedStake += uint112(weight);
weight = weight * (MAX_STAKE_GROWTH_WEEKS + 1);
// Note: The usage of `stakeAsMaxWeighted` breaks an ability to reliably derive account + global
// amount deposited at any week using `weeklyToRealize` variables.
// To make up for this, we introduce the following two variables that are meant to recover that same
// ability for any on-chain integrators. They may combine this new data with `weeklyToRealize`.
accountWeeklyMaxStake[_account][systemWeek] += _amount;
globalWeeklyMaxStake[systemWeek] += _amount;
accountWeeklyWeights[_account][systemWeek] = accountWeight + weight;
globalWeeklyWeights[systemWeek] = globalWeight + weight;
accountData[_account] = acctData;
totalSupply += _amount;
stakeToken.safeTransferFrom(msg.sender, address(this), uint(_amount));
emit Staked(_account, systemWeek, _amount, accountWeight + weight, weight);
return _amount;
}
/**
@notice Unstake tokens from the contract.
@dev During partial unstake, this will always remove from the least-weighted first.
*/
function unstake(uint _amount, address _receiver) external returns (uint) {
return _unstake(msg.sender, _amount, _receiver);
}
/**
@notice Unstake tokens from the contract on behalf of another user.
@dev During partial unstake, this will always remove from the least-weighted first.
*/
function unstakeFor(address _account, uint _amount, address _receiver) external returns (uint) {
if (msg.sender != _account) {
ApprovalStatus status = approvedCaller[_account][msg.sender];
require(
status == ApprovalStatus.StakeAndUnstake ||
status == ApprovalStatus.UnstakeOnly,
"!Permission"
);
}
return _unstake(_account, _amount, _receiver);
}
function _unstake(address _account, uint _amount, address _receiver) internal returns (uint) {
require(_amount > 1 && _amount < type(uint112).max, "invalid amount");
uint systemWeek = getWeek();
// Before going further, let's sync our account and global weights
(AccountData memory acctData, ) = _checkpointAccount(_account, systemWeek);
_checkpointGlobal(systemWeek);
// Here we do work to pull from most recent (least weighted) stake first
uint8 bitmap = acctData.updateWeeksBitmap;
uint128 weightToRemove;
uint128 amountNeeded = uint128(_amount >> 1);
_amount = amountNeeded << 1; // This helps prevent balance/weight discrepencies.
if (bitmap > 0) {
for (uint128 weekIndex; weekIndex < MAX_STAKE_GROWTH_WEEKS;) {
// Move right to left, checking each bit if there's an update for corresponding week.
uint8 mask = uint8(1 << weekIndex);
if (bitmap & mask == mask) {
uint weekToCheck = systemWeek + MAX_STAKE_GROWTH_WEEKS - weekIndex;
uint128 pending = accountWeeklyToRealize[_account][weekToCheck].weight;
if (amountNeeded > pending){
weightToRemove += pending * (weekIndex + 1);
accountWeeklyToRealize[_account][weekToCheck].weight = 0;
globalWeeklyToRealize[weekToCheck].weight -= pending;
if (weekIndex == 0) { // Current system week
accountWeeklyToRealize[_account][weekToCheck].weightPersistent = 0;
globalWeeklyToRealize[weekToCheck].weightPersistent -= pending;
}
bitmap = bitmap ^ mask;
amountNeeded -= pending;
}
else {
// handle the case where we have more pending than needed
weightToRemove += amountNeeded * (weekIndex + 1);
accountWeeklyToRealize[_account][weekToCheck].weight -= amountNeeded;
globalWeeklyToRealize[weekToCheck].weight -= amountNeeded;
if (weekIndex == 0) { // Current system week
accountWeeklyToRealize[_account][weekToCheck].weightPersistent -= amountNeeded;
globalWeeklyToRealize[weekToCheck].weightPersistent -= amountNeeded;
}
if (amountNeeded == pending) bitmap = bitmap ^ mask;
amountNeeded = 0;
break;
}
}
unchecked{weekIndex++;}
}
acctData.updateWeeksBitmap = bitmap;
}
uint pendingRemoved = (_amount >> 1) - amountNeeded;
if (amountNeeded > 0) {
weightToRemove += amountNeeded * uint128(1 + MAX_STAKE_GROWTH_WEEKS);
acctData.realizedStake -= uint112(amountNeeded);
acctData.pendingStake = 0;
}
else{
acctData.pendingStake -= uint112(pendingRemoved);
}
accountData[_account] = acctData;
globalGrowthRate -= uint112(pendingRemoved);
globalWeeklyWeights[systemWeek] -= weightToRemove;
uint newAccountWeight = accountWeeklyWeights[_account][systemWeek] - weightToRemove;
accountWeeklyWeights[_account][systemWeek] = newAccountWeight;
totalSupply -= _amount;
emit Unstaked(_account, systemWeek, _amount, newAccountWeight, weightToRemove);
stakeToken.safeTransfer(_receiver, _amount);
return _amount;
}
/**
@notice Get the current realized weight for an account
@param _account Account to checkpoint.
@return acctData Most recent account data written to storage.
@return weight Most current account weight.
@dev Prefer to use this function over it's view counterpart for
contract -> contract interactions.
*/
function checkpointAccount(address _account) external returns (AccountData memory acctData, uint weight) {
(acctData, weight) = _checkpointAccount(_account, getWeek());
accountData[_account] = acctData;
}
/**
@notice Checkpoint an account using a specified week limit.
@dev To use in the event that significant number of weeks have passed since last
heckpoint and single call becomes too expensive.
@param _account Account to checkpoint.
@param _week Week which we want to checkpoint to.
@return acctData Most recent account data written to storage.
@return weight Account weight for provided week.
*/
function checkpointAccountWithLimit(address _account, uint _week) external returns (AccountData memory acctData, uint weight) {
uint systemWeek = getWeek();
if (_week >= systemWeek) _week = systemWeek;
(acctData, weight) = _checkpointAccount(_account, _week);
accountData[_account] = acctData;
}
function _checkpointAccount(address _account, uint _systemWeek) internal returns (AccountData memory acctData, uint weight){
acctData = accountData[_account];
uint lastUpdateWeek = acctData.lastUpdateWeek;
if (_systemWeek == lastUpdateWeek) {
return (acctData, accountWeeklyWeights[_account][lastUpdateWeek]);
}
require(_systemWeek > lastUpdateWeek, "specified week is older than last update.");
uint pending = uint(acctData.pendingStake);
uint realized = acctData.realizedStake;
if (pending == 0) {
if (realized != 0) {
weight = accountWeeklyWeights[_account][lastUpdateWeek];
while (lastUpdateWeek < _systemWeek) {
unchecked{lastUpdateWeek++;}
// Fill in any missing weeks
accountWeeklyWeights[_account][lastUpdateWeek] = weight;
}
}
accountData[_account].lastUpdateWeek = uint16(_systemWeek);
acctData.lastUpdateWeek = uint16(_systemWeek);
return (acctData, weight);
}
weight = accountWeeklyWeights[_account][lastUpdateWeek];
uint8 bitmap = acctData.updateWeeksBitmap;
uint targetSyncWeek = min(_systemWeek, lastUpdateWeek + MAX_STAKE_GROWTH_WEEKS);
// Populate data for missed weeks
while (lastUpdateWeek < targetSyncWeek) {
unchecked{ lastUpdateWeek++; }
weight += pending; // Increment weights by weekly growth factor.
accountWeeklyWeights[_account][lastUpdateWeek] = weight;
// Shift left on bitmap as we pass over each week.
bitmap = bitmap << 1;
if (bitmap & MAX_WEEK_BIT == MAX_WEEK_BIT){ // If left-most bit is true, we have something to realize; push pending to realized.
// Do any updates needed to realize an amount for an account.
uint toRealize = accountWeeklyToRealize[_account][lastUpdateWeek].weight;
pending -= toRealize;
realized += toRealize;
if (pending == 0) break; // All pending has been realized. No need to continue.
}
}
// Fill in any missed weeks.
while (lastUpdateWeek < _systemWeek){
unchecked{lastUpdateWeek++;}
accountWeeklyWeights[_account][lastUpdateWeek] = weight;
}
// Write new account data to storage.
acctData = AccountData({
updateWeeksBitmap: bitmap,
pendingStake: uint112(pending),
realizedStake: uint112(realized),
lastUpdateWeek: uint16(_systemWeek)
});
}
/**
@notice View function to get the current weight for an account
*/
function getAccountWeight(address account) external view returns (uint) {
return getAccountWeightAt(account, getWeek());
}
/**
@notice Get the weight for an account in a given week
*/
function getAccountWeightAt(address _account, uint _week) public view returns (uint) {
if (_week > getWeek()) return 0;
AccountData memory acctData = accountData[_account];
uint16 lastUpdateWeek = acctData.lastUpdateWeek;
if (lastUpdateWeek >= _week) return accountWeeklyWeights[_account][_week];
uint weight = accountWeeklyWeights[_account][lastUpdateWeek];
uint pending = uint(acctData.pendingStake);
if (pending == 0) return weight;
uint8 bitmap = acctData.updateWeeksBitmap;
while (lastUpdateWeek < _week) { // Populate data for missed weeks
unchecked{lastUpdateWeek++;}
weight += pending; // Increment weight by 1 week
// Our bitmap is used to determine if week has any amount to realize.
bitmap = bitmap << 1;
if (bitmap & MAX_WEEK_BIT == MAX_WEEK_BIT){ // If left-most bit is true, we have something to realize; push pending to realized.
pending -= accountWeeklyToRealize[_account][lastUpdateWeek].weight;
if (pending == 0) break; // All pending has now been realized, let's exit.
}
}
return weight;
}
/**
@notice Get the current total system weight
@dev Also updates local storage values for total weights. Using
this function over it's `view` counterpart is preferred for
contract -> contract interactions.
*/
function checkpointGlobal() external returns (uint) {
uint systemWeek = getWeek();
return _checkpointGlobal(systemWeek);
}
/**
@notice Get the current total system weight
@dev Also updates local storage values for total weights. Using
this function over it's `view` counterpart is preferred for
contract -> contract interactions.
*/
function _checkpointGlobal(uint systemWeek) internal returns (uint) {
// These two share a storage slot.
uint16 lastUpdateWeek = globalLastUpdateWeek;
uint rate = globalGrowthRate;
uint weight = globalWeeklyWeights[lastUpdateWeek];
if (weight == 0) {
globalLastUpdateWeek = uint16(systemWeek);
return 0;
}
if (lastUpdateWeek == systemWeek){
return weight;
}
while (lastUpdateWeek < systemWeek) {
unchecked{lastUpdateWeek++;}
weight += rate;
globalWeeklyWeights[lastUpdateWeek] = weight;
rate -= globalWeeklyToRealize[lastUpdateWeek].weight;
}
globalGrowthRate = uint112(rate);
globalLastUpdateWeek = uint16(systemWeek);
return weight;
}
/**
@notice Get the system weight for current week.
*/
function getGlobalWeight() external view returns (uint) {
return getGlobalWeightAt(getWeek());
}
/**
@notice Get the system weight for a specified week in the past.
@dev querying a week in the future will always return 0.
@param week the week number to query global weight for.
*/
function getGlobalWeightAt(uint week) public view returns (uint) {
uint systemWeek = getWeek();
if (week > systemWeek) return 0;
// Read these together since they are packed in the same slot.
uint16 lastUpdateWeek = globalLastUpdateWeek;
uint rate = globalGrowthRate;
if (week <= lastUpdateWeek) return globalWeeklyWeights[week];
uint weight = globalWeeklyWeights[lastUpdateWeek];
if (rate == 0) {
return weight;
}
while (lastUpdateWeek < week) {
unchecked {lastUpdateWeek++;}
weight += rate;
rate -= globalWeeklyToRealize[lastUpdateWeek].weight;
}
return weight;
}
/**
@notice Returns the balance of underlying staked tokens for an account
@param _account Account to query balance.
@return balance of account.
*/
function balanceOf(address _account) external view returns (uint) {
AccountData memory acctData = accountData[_account];
return 2 * (acctData.pendingStake + acctData.realizedStake);
}
/**
@notice Allow another address to stake or unstake on behalf of. Useful for zaps and other functionality.
@param _caller Address of the caller to approve or unapprove.
@param _status Enum representing various approval status states.
*/
function setApprovedCaller(address _caller, ApprovalStatus _status) external {
approvedCaller[msg.sender][_caller] = _status;
emit ApprovedCallerSet(msg.sender, _caller, _status);
}
/**
@notice Allow owner to specify an account which has ability to stakeAsWeighted.
@param _staker Address of account with staker permissions.
@param _approved Approve or unapprove the staker.
*/
function setWeightedStaker(address _staker, bool _approved) external {
require(msg.sender == owner, "!authorized");
approvedWeightedStaker[_staker] = _approved;
emit WeightedStakerSet(_staker, _approved);
}
/**
@notice Set a pending owner which can later be accepted.
@param _pendingOwner Address of the new owner.
*/
function transferOwnership(address _pendingOwner) external {
require(msg.sender == owner, "!authorized");
pendingOwner = _pendingOwner;
}
/**
@notice Allow pending owner to accept ownership
*/
function acceptOwnership() external {
require(msg.sender == pendingOwner, "!authorized");
owner = msg.sender;
pendingOwner = address(0);
emit OwnershipTransferred(msg.sender);
}
function sweep(address _token) external {
require(msg.sender == owner, "!authorized");
uint amount = IERC20(_token).balanceOf(address(this));
if (_token == address(stakeToken)) {
amount = amount - totalSupply;
}
if (amount > 0) IERC20(_token).safeTransfer(owner, amount);
}
function getWeek() public view returns (uint week) {
unchecked{
return (block.timestamp - START_TIME) / 1 weeks;
}
}
function min(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
}