// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts/access/Ownable.sol";
import { ASR_ZeroAddress } from "../src/errors/Staking.sol";
abstract contract ArcadeRewardsRecipient is Ownable {
address public rewardsDistribution;
constructor(address _rewardsDistribution) {
if (address(_rewardsDistribution) == address(0)) revert ASR_ZeroAddress("rewardsDistribution");
rewardsDistribution = _rewardsDistribution;
}
modifier onlyRewardsDistribution() {
require(msg.sender == rewardsDistribution, "Caller is not RewardsDistribution contract");
_;
}
function notifyRewardAmount(uint256 reward) external virtual;
function setRewardsDistribution(address _rewardsDistribution) external onlyOwner {
rewardsDistribution = _rewardsDistribution;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "./external/council/interfaces/IVotingVault.sol";
import "./external/council/libraries/History.sol";
import "./external/council/libraries/Storage.sol";
import "./interfaces/IArcadeStakingRewards.sol";
import "./ArcadeRewardsRecipient.sol";
import {
ASR_ZeroAddress,
ASR_ZeroAmount,
ASR_RewardsPeriod,
ASR_StakingToken,
ASR_RewardTooHigh,
ASR_BalanceAmount,
ASR_Locked,
ASR_RewardsToken,
ASR_DepositCountExceeded,
ASR_ZeroConversionRate,
ASR_InvalidDelegationAddress,
ASR_MinimumRewardAmount,
ASR_ZeroRewardRate,
ASR_AmountTooBig
} from "../src/errors/Staking.sol";
/**
* @title ArcadeStakingRewards
* @author Non-Fungible Technologies, Inc.
*
* @notice To optimize gas usage, unlockTimeStamp in struct UserStake is stored in
* uint32 format. This limits timestamp support to dates before 03:14:07 UTC on
* 19 January 2038. Any time beyond this point will cause an overflow.
*
* The ArcadeStakingRewards contract is a fork of the Synthetix StakingRewards
* contract.
* https://github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol
*
* The contract manages a staking mechanism where users can stake the ERC20 ARCD/WETH pair
* token and earn rewards over time, paid in the ERC20 rewardsToken. Rewards are earned
* based on the amount of ARCD/WETH staked and the length of time staked.
*
* Users have the flexibility to make multiple deposits, each accruing
* rewards separately until the staking period concludes. Upon depositing
* their tokens for staking, users are required to commit to a lock period
* where funds are immovable (even if the staking cycle concludes), until
* the chosen lock period expires. Early withdrawal is not permitted before
* the locking period is over.
* Should users choose not to withdraw their funds post the lock period, these
* funds will seamlessly transition into a subsequent staking cycle. Unlike the
* initial deposit, these automatically re-staked funds are not bound by a lock
* period and can be freely withdrawn at any point, even before the current
* staking cycle concludes.
*
* The lock period gives users the opportunity to enhance their reward earnings
* with a bonus multiplier that is contingent on the duration for which the user
* chooses to lock their staking tokens. The available lock durations are categorized
* as short, medium, and long. Each category is associated with a progressively
* increasing multiplier, with the short duration offering the smallest and
* the long duration offering the largest.
* When a user decides to lock their staking tokens for one of these durations,
* their total reward is calculated as:
* (the user's staked amount * multiplier for the chosen duration) + original
* staked amount.
* This boosts the user's rewards in proportion to both the amount staked and
* the duration of the stake.
*
* In the exitAll() and claimRewardAll() external functions, it's necessary to
* limit the number of iterations processed within these functions' loops to
* prevent exceeding the block gas limit. Because of this, the contract enforces
* a hard limit on the number deposits a user can have per wallet address and
* consequently on the number of iterations that can be processed in a single
* transaction. This limit is defined by the MAX_DEPOSITS state variable.
* Should a user necessitate making more than the MAX_DEPOSITS number
* of stakes, they will be required to use a different wallet address.
*
* The locking pool gives users governance capabilities by also serving as a
* voting vault. When users stake, they gain voting power. They can use this voting
* power to vote in ArcadeDAO governance. The voting power is automatically accrued
* to their account and is delegated to their chosen delegatee's address on their
* behalf without the need for them to call any additional transaction.
* The ArcadeStakingRewards contract governance functionality is adapted from the
* LockingVault deployment at:
* https://etherscan.io/address/0x7a58784063D41cb78FBd30d271F047F0b9156d6e#code
*
* Once a user makes their initial stake, the voting power for any future stakes will
* need to be delegated to the same address as the initial stake. To assign a
* different delegate, users are required to use the changeDelegate() function.
*
* A user's voting power is determined by the quantity of ARCD/WETH pair tokens
* they have staked. To calculate this voting power, an ARCD/WETH to ARCD
* conversion rate is set in the contract at deployment and cannot be updated.
* The user's ARCD amount is a product of their deposited ARCD/WETH amount and
* the conversion rate.
*/
contract ArcadeStakingRewards is IArcadeStakingRewards, ArcadeRewardsRecipient, IVotingVault, ReentrancyGuard, Pausable {
using SafeERC20 for IERC20;
using Math for uint256;
// Bring library into scope
using History for History.HistoricalBalances;
// ============================================ STATE ==============================================
// ============== Constants ==============
uint256 public constant ONE = 1e18;
uint256 public constant MAX_DEPOSITS = 20;
uint256 public constant LP_TO_ARCD_DENOMINATOR = 1e3;
uint256 public constant SHORT_BONUS = 11e17;
uint256 public constant MEDIUM_BONUS = 13e17;
uint256 public constant LONG_BONUS = 18e17;
uint256 public constant SHORT_LOCK_TIME = 30 days;
uint256 public constant MEDIUM_LOCK_TIME = 60 days;
uint256 public constant LONG_LOCK_TIME = 150 days;
// ============ Global State =============
uint256 public immutable LP_TO_ARCD_RATE;
IERC20 public immutable rewardsToken;
IERC20 public immutable arcdWethLP;
uint256 public periodFinish;
uint256 public lastUpdateTime;
uint256 public rewardsDuration = 180 days;
uint256 public notifiedRewardAmount;
uint256 public rewardPerTokenStored;
uint256 public rewardRate;
mapping(address => UserStake[]) public stakes;
uint256 public totalDeposits;
uint256 public totalDepositsWithBonus;
uint256 public unclaimedRewards;
// ========================================== CONSTRUCTOR ===========================================
/**
* @notice Sets up the contract by initializing the staking and rewards tokens,
* and setting the owner and rewards distribution addresses as well as
* setting the LP to governance conversion rate.
*
* @param _owner The address of the contract owner.
* @param _rewardsDistribution The address of the entity setting the rules
* of how rewards are distributed.
* @param _rewardsToken The address of the rewards ERC20 token.
* @param _arcdWethLP The address of the staking ERC20 token.
* @param _lpToArcdRate Immutable ARCD/WETH to ARCD conversion rate.
*/
constructor(
address _owner,
address _rewardsDistribution,
address _rewardsToken,
address _arcdWethLP,
uint256 _lpToArcdRate
) Ownable(_owner) ArcadeRewardsRecipient(_rewardsDistribution) {
if (address(_rewardsToken) == address(0)) revert ASR_ZeroAddress("rewardsToken");
if (address(_arcdWethLP) == address(0)) revert ASR_ZeroAddress("arcdWethLP");
if (_lpToArcdRate == 0) revert ASR_ZeroConversionRate();
rewardsToken = IERC20(_rewardsToken);
arcdWethLP = IERC20(_arcdWethLP);
LP_TO_ARCD_RATE = _lpToArcdRate;
}
// ========================================== VIEW FUNCTIONS =========================================
/**
* @notice Returns the total amount of staking tokens held in the contract.
*
* @return uint256 The amount of staked tokens.
*/
function totalSupply() external view returns (uint256) {
return totalDeposits;
}
/**
* @notice Returns the amount of staking tokens staked by a user account.
*
* @param account The address of the account.
*
* @return userBalance The total amount that the user is staking.
*/
function getTotalUserDeposits(address account) external view returns (uint256 userBalance) {
UserStake[] storage userStakes = stakes[account];
uint256 numUserStakes = userStakes.length;
for (uint256 i = 0; i < numUserStakes; ++i) {
UserStake storage userStake = userStakes[i];
userBalance += userStake.amount;
}
}
/**
* @notice Returns the amount of staking tokens staked in a specific deposit.
*
* @param account The address of the account.
* @param depositId The specified deposit to get the balance of.
*
* @return depositBalance The total amount staked in the deposit.
*/
function balanceOfDeposit(address account, uint256 depositId) external view returns (uint256 depositBalance) {
depositBalance = stakes[account][depositId].amount;
}
/**
* @notice Returns the last timestamp at which rewards can be calculated and
* be accounted for.
*
* @return uint256 The timestamp record after which rewards
* can no longer be calculated.
*/
function lastTimeRewardApplicable() public view returns (uint256) {
return block.timestamp < periodFinish ? block.timestamp : periodFinish;
}
/**
* @notice Returns the amount of reward token earned per staked token.
*
* @return uint256 The reward token amount per staked token.
* @return uint256 Unclaimed rewards.
*/
function rewardPerToken() public view returns (uint256, uint256) {
if (totalDepositsWithBonus == 0) {
return (rewardPerTokenStored, unclaimedRewards);
}
uint256 timePassed = lastTimeRewardApplicable() - lastUpdateTime;
uint256 durationRewards = timePassed * rewardRate;
uint256 updatedRewardsPerToken = (durationRewards * ONE) / totalDepositsWithBonus;
return (rewardPerTokenStored + updatedRewardsPerToken, unclaimedRewards + durationRewards);
}
/**
* @notice Returns the reward amount for a deposit.
*
* @param account The address of the user that is staking.
* @param depositId The specified deposit to get the reward for.
*
* @return rewards Rewards amounts earned for each deposit.
*/
function getPendingRewards(address account, uint256 depositId) external view returns (uint256 rewards) {
UserStake storage userStake = stakes[account][depositId];
rewards = _getPendingRewards(userStake);
}
/**
* @notice Returns the amount of reward distributable over the current reward period.
*
* @return uint256 The amount of reward token that is distributable.
*/
function getRewardForDuration() external view returns (uint256) {
return rewardRate * rewardsDuration;
}
/**
* @notice Returns information about a deposit.
* @param account The user whose stakes to get.
* @param depositId The specified deposit to get.
*
* @return lock Lock period committed.
* @return unlockTimestamp Timestamp marking the end of the lock period.
* @return amount Amount staked.
* @return rewardPerTokenPaid Reward per token accounted for.
* @return rewards Amount of rewards accrued.
*/
function getUserStake(address account, uint256 depositId) external view returns (
uint8 lock,
uint32 unlockTimestamp,
uint256 amount,
uint256 rewardPerTokenPaid,
uint256 rewards)
{
UserStake storage userStake = stakes[account][depositId];
lock = uint8(userStake.lock);
unlockTimestamp = userStake.unlockTimestamp;
amount = userStake.amount;
rewardPerTokenPaid = userStake.rewardPerTokenPaid;
rewards = _getPendingRewards(userStake);
}
/**
* @notice Gives the last depositId, equivalent to userStakes.length.
*
* @param account The user whose stakes to get.
*
* @return lastDepositId Id of the last stake.
*/
function getLastDepositId(address account) external view returns (uint256 lastDepositId) {
lastDepositId = stakes[account].length - 1;
}
/**
* @notice Gets all of a user's active stakes.
*
* @param account The user whose stakes to get.
*
* @return activeStakes Array of id's of user's active stakes.
*/
function getActiveStakes(address account) external view returns (uint256[] memory) {
UserStake[] storage userStakes = stakes[account];
uint256 activeCount = 0;
uint256 numUserStakes = userStakes.length;
for (uint256 i = 0; i < numUserStakes; ++i) {
UserStake storage userStake = userStakes[i];
if (userStake.amount > 0) {
activeCount++;
}
}
uint256[] memory activeStakes = new uint256[](activeCount);
uint256 activeIndex;
for (uint256 i = 0; i < numUserStakes; ++i) {
if (userStakes[i].amount > 0) {
activeStakes[activeIndex++] = i;
}
}
return activeStakes;
}
/**
* @notice Gets all of a user's deposit ids for stakes that are holding a reward.
* Also gets the amount of rewards for each deposit.
*
* @param account The user whose deposit indices to get.
*
* @return rewardedDeposits Array of id's of user's stakes holding
* rewards.
* @return rewardsArray Array of user's rewards.
*/
function getDepositIndicesWithRewards(address account) external view returns (uint256[] memory, uint256[] memory) {
UserStake[] storage userStakes = stakes[account];
uint256 numUserStakes = userStakes.length;
uint256[] memory rewards = new uint256[](numUserStakes);
uint256 rewarded = 0;
(uint256 updatedRewardPerToken,) = rewardPerToken();
for (uint256 i = 0; i < numUserStakes; ++i) {
UserStake storage userStake = userStakes[i];
uint256 stakeAmountWithBonus = _getAmountWithBonus(userStake);
if (stakeAmountWithBonus == 0) continue;
uint256 userRewardPerTokenPaid = userStake.rewardPerTokenPaid;
rewards[i] = ((stakeAmountWithBonus * (updatedRewardPerToken - userRewardPerTokenPaid)) / ONE);
if (rewards[i] > 0) {
rewarded++;
}
}
uint256[] memory rewardedDeposits = new uint256[](rewarded);
uint256[] memory rewardAmounts = new uint256[](rewarded);
uint256 rewardedIndex = 0;
uint256 numRewards = rewards.length;
for (uint256 i = 0; i < numRewards; ++i) {
if (rewards[i] > 0) {
rewardedDeposits[rewardedIndex] = i;
rewardAmounts[rewardedIndex] = rewards[i];
rewardedIndex++;
}
}
return (rewardedDeposits, rewardAmounts);
}
/**
* @notice Returns just the "amount with bonus" for a deposit.
*
* @param account The user's account.
* @param depositId The specified deposit to get the amount
* with bonus for.
*
* @return amountWithBonus Value of user stake with bonus.
*/
function getAmountWithBonus(address account, uint256 depositId) external view returns (uint256 amountWithBonus) {
UserStake storage userStake = stakes[account][depositId];
amountWithBonus = _getAmountWithBonus(userStake);
}
/**
* @notice Get pending reward for user deposits.
*
* @param account The user's account.
*
* @return totalRewards Value of a user's rewards across all deposits.
*/
function getTotalUserPendingRewards(address account) external view returns (uint256 totalRewards) {
UserStake[] storage userStakes = stakes[account];
uint256 numUserStakes = userStakes.length;
for (uint256 i = 0; i < numUserStakes; ++i) {
UserStake storage userStake = userStakes[i];
totalRewards += _getPendingRewards(userStake);
}
}
/**
* @notice Get all user's deposits with their bonus amounts.
*
* @param account The user's account.
*
* @return totalDepositsWithBonuses Value of a user's deposits with bonuses across all deposits.
*/
function getTotalUserDepositsWithBonus(address account) external view returns (uint256 totalDepositsWithBonuses) {
UserStake[] storage userStakes = stakes[account];
uint256 numUserStakes = userStakes.length;
for (uint256 i = 0; i < numUserStakes; ++i) {
UserStake storage userStake = userStakes[i];
totalDepositsWithBonuses += _getAmountWithBonus(userStake);
}
}
/**
* @notice Converts the user's staked LP token value to governance power amount based on the
* immutable rate set in the contract.
*
* @param arcdWethLPAmount The LP token amount to use for the conversion.
*
* @return uint256 Value of ARCD.
*/
function convertLPToArcd(uint256 arcdWethLPAmount) public view returns (uint256) {
return (arcdWethLPAmount * LP_TO_ARCD_RATE) / LP_TO_ARCD_DENOMINATOR;
}
// ========================================= MUTATIVE FUNCTIONS ========================================
/**
* @notice Allows users to stake their tokens, which are then tracked in the contract. The total
* supply of staked tokens and individual user balances are updated accordingly.
*
* @param amount The amount of tokens the user wishes to deposit and stake.
* @param delegation The address to which the user's voting power will be delegated.
* @param lock The locking period for the staked tokens.
*/
function deposit(
uint256 amount,
address delegation,
Lock lock
) external nonReentrant whenNotPaused updateReward {
if (amount == 0) revert ASR_ZeroAmount();
if (delegation == address(0)) revert ASR_ZeroAddress("delegation");
uint256 userStakeCount = stakes[msg.sender].length;
if (userStakeCount >= MAX_DEPOSITS) revert ASR_DepositCountExceeded();
(uint256 amountWithBonus, uint256 lockDuration) = _calculateBonus(amount, lock);
uint256 votingPowerToAdd = convertLPToArcd(amount);
// update the vote power to equal the amount staked with bonus
_addVotingPower(msg.sender, votingPowerToAdd, delegation);
// populate user stake information
stakes[msg.sender].push(
UserStake({
amount: amount,
unlockTimestamp: uint32(block.timestamp + lockDuration),
rewardPerTokenPaid: rewardPerTokenStored,
lock: lock
})
);
totalDeposits += amount;
totalDepositsWithBonus += amountWithBonus;
arcdWethLP.safeTransferFrom(msg.sender, address(this), amount);
// if this is the first stake and the reward amount is notified, begin
// reward emissions
if (notifiedRewardAmount > 0) {
_startRewardEmission(notifiedRewardAmount);
}
emit Staked(msg.sender, userStakeCount, amount, uint8(lock));
}
/**
* @notice Enables the claim of accumulated rewards.
*
* @param depositId The specified deposit to get the reward for.
*/
function claimReward(uint256 depositId) external whenNotPaused nonReentrant updateReward {
UserStake storage userStake = stakes[msg.sender][depositId];
if (userStake.amount == 0) revert ASR_BalanceAmount();
uint256 reward = _getPendingRewards(userStake);
if (reward > 0) {
unclaimedRewards -= reward;
userStake.rewardPerTokenPaid = rewardPerTokenStored;
rewardsToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward, depositId);
}
}
/**
* @notice Enables the claim of all accumulated rewards in one transaction.
*/
function claimRewardAll() external whenNotPaused nonReentrant updateReward {
UserStake[] storage userStakes = stakes[msg.sender];
uint256 totalReward = 0;
uint256 numUserStakes = userStakes.length;
for (uint256 i = 0; i < numUserStakes; ++i) {
UserStake storage userStake = userStakes[i];
uint256 reward = _getPendingRewards(userStake);
totalReward += reward;
if (reward > 0) {
userStake.rewardPerTokenPaid = rewardPerTokenStored;
emit RewardPaid(msg.sender, reward, i);
}
}
if (totalReward > 0) {
unclaimedRewards -= totalReward;
rewardsToken.safeTransfer(msg.sender, totalReward);
}
}
/**
* @notice Withdraws staked tokens that are unlocked. Allows for partial withdrawals.
*
* @param depositId The specified deposit to withdraw from.
* @param amount The amount to be withdrawn from the user stake.
*/
function withdraw(uint256 amount, uint256 depositId) public whenNotPaused nonReentrant updateReward {
if (amount == 0) revert ASR_ZeroAmount();
UserStake storage userStake = stakes[msg.sender][depositId];
if (userStake.amount == 0) revert ASR_BalanceAmount();
if (block.timestamp < userStake.unlockTimestamp) revert ASR_Locked();
if (amount > userStake.amount) amount = userStake.amount;
(uint256 amountWithBonus, ) = _calculateBonus(amount, userStake.lock);
uint256 votePowerToSubtract = convertLPToArcd(amount);
_subtractVotingPower(votePowerToSubtract, msg.sender);
uint256 reward = _getPendingRewards(userStake);
userStake.amount -= amount;
totalDeposits -= amount;
totalDepositsWithBonus -= amountWithBonus;
if (reward > 0) {
unclaimedRewards -= reward;
userStake.rewardPerTokenPaid = rewardPerTokenStored;
rewardsToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward, depositId);
}
arcdWethLP.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, depositId, amount, uint8(userStake.lock));
}
/**
* @notice Allows users to withdraw staked tokens and claim their rewards
* for a specific deposit id, all in one transaction.
* Lock period needs to have ended.
*
* @param depositId The specified deposit to exit.
*/
function exit(uint256 depositId) external {
withdraw(type(uint256).max, depositId);
}
/**
* @notice Allows users to withdraw all their staked tokens and claim all reward
* tokens in one transaction. Lock period needs to have ended.
*/
function exitAll() external whenNotPaused nonReentrant updateReward {
UserStake[] storage userStakes = stakes[msg.sender];
uint256 totalWithdrawAmount = 0;
uint256 totalRewardAmount = 0;
uint256 totalVotingPower = 0;
uint256 amountWithBonusToSubtract = 0;
uint256 numUserStakes = userStakes.length;
for (uint256 i = 0; i < numUserStakes; ++i) {
UserStake storage userStake = userStakes[i];
uint256 amount = userStake.amount;
if (amount == 0 || block.timestamp < userStake.unlockTimestamp) continue;
(uint256 amountWithBonus, ) = _calculateBonus(amount, userStake.lock);
uint256 votePowerToSubtract = convertLPToArcd(amount);
uint256 reward = _getPendingRewards(userStake);
userStake.amount -= amount;
amountWithBonusToSubtract += amountWithBonus;
totalVotingPower += votePowerToSubtract;
totalWithdrawAmount += amount;
totalRewardAmount += reward;
if (reward > 0) {
userStake.rewardPerTokenPaid = rewardPerTokenStored;
emit RewardPaid(msg.sender, reward, i);
}
emit Withdrawn(msg.sender, i, amount, uint8(userStake.lock));
}
if (totalVotingPower > 0) {
_subtractVotingPower(totalVotingPower, msg.sender);
}
if (amountWithBonusToSubtract > 0) {
totalDepositsWithBonus -= amountWithBonusToSubtract;
}
if (totalWithdrawAmount > 0) {
totalDeposits -= totalWithdrawAmount;
arcdWethLP.safeTransfer(msg.sender, totalWithdrawAmount);
}
if (totalRewardAmount > 0) {
unclaimedRewards -= totalRewardAmount;
rewardsToken.safeTransfer(msg.sender, totalRewardAmount);
}
}
// ======================================== RESTRICTED FUNCTIONS =========================================
/**
* @notice Notifies the contract of new rewards available for distribution. Reward emissions is delayed
* until the first user stakes.
* Can only be called by the rewardsDistribution address.
*
* @dev To avoid rounding errors, the notified reward amount is adjusted to be divisible by the
* rewardsDuration if necessary. This rounding down will evenutally result in an amount of
* "leftover" rewards not being distributed. The leftover amount will need to be periodically
* recovered by the owner at times when the pool is not active.
*
*
* @param reward The amount of new reward tokens.
*/
function notifyRewardAmount(uint256 reward) external override whenNotPaused onlyRewardsDistribution updateReward {
if (reward < ONE) revert ASR_MinimumRewardAmount();
if (totalDeposits > 0) {
_startRewardEmission(reward);
} else {
notifiedRewardAmount += reward;
}
emit RewardAdded(reward);
}
/**
* @notice Allows the contract owner to recover ERC20 tokens locked in the contract.
* Reward tokens can be recovered only if the total staked amount is zero.
*
* @param tokenAddress The address of the token to recover.
* @param tokenAmount The amount of token to recover.
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner {
if (tokenAddress == address(arcdWethLP)) revert ASR_StakingToken();
if (tokenAddress == address(rewardsToken) && totalDeposits != 0) revert ASR_RewardsToken();
if (tokenAddress == address(0)) revert ASR_ZeroAddress("token");
if (tokenAmount == 0) revert ASR_ZeroAmount();
IERC20(tokenAddress).safeTransfer(msg.sender, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/**
* @notice An only owner function to set the duration of the rewards period. The previous
* rewards period must be complete before a new duration can be set.
*
* @param _rewardsDuration The amount of time the rewards period will be.
*/
function setRewardsDuration(uint256 _rewardsDuration) external whenNotPaused onlyOwner {
if (block.timestamp <= periodFinish) revert ASR_RewardsPeriod();
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
/**
* @notice Pauses the contract, callable by only the owner. Reversible.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Unpauses the contract, callable by only the owner. Reversible.
*/
function unpause() external onlyOwner {
_unpause();
}
// ============================================== HELPERS ===============================================
/**
* @notice Updates the global reward counter.
*/
modifier updateReward {
(rewardPerTokenStored, unclaimedRewards) = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
_;
}
/**
* @notice Triggers reward emissions when the first user stakes and if there is a reward amount.
* Adjusts the rewardRate rate at which rewards will be distributed to users to over the
* remaining duration of the reward period.
*
* @param reward The amount of reward tokens to distribute.
*/
function _startRewardEmission(uint256 reward) private {
uint256 leftover;
if (block.timestamp < periodFinish) {
uint256 remaining = periodFinish - block.timestamp;
leftover = remaining * rewardRate;
reward += leftover;
}
uint256 remainder = reward % rewardsDuration;
reward -= remainder;
rewardRate = reward / rewardsDuration;
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
if (reward + leftover + unclaimedRewards > balance) revert ASR_RewardTooHigh();
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp + rewardsDuration;
notifiedRewardAmount = 0;
emit RewardEmissionActivated(reward, periodFinish);
}
/**
* @notice Calculates the total amount for a user's stake including the bonus based on
* the stake's lock period.
*
* @param userStake The user's stake object.
*
* @return amountWithBonus The total amount including the bonus.
*/
function _getAmountWithBonus(UserStake storage userStake) internal view returns (uint256 amountWithBonus) {
uint256 amount = userStake.amount;
Lock lock = userStake.lock;
(amountWithBonus, ) = _calculateBonus(amount, lock);
}
/**
* @notice Calculates the pending rewards of a user's stake.
*
* @param userStake The user's stake object.
*
* @return rewards The amount of user rewards.
*/
function _getPendingRewards(UserStake storage userStake) internal view returns (uint256 rewards) {
uint256 stakeAmountWithBonus = _getAmountWithBonus(userStake);
uint256 userRewardPerTokenPaid = userStake.rewardPerTokenPaid;
(uint256 updatedRewardPerToken,) = rewardPerToken();
rewards = ((stakeAmountWithBonus * (updatedRewardPerToken - userRewardPerTokenPaid)) / ONE);
}
/**
* @notice Calculate the bonus for a user's stake.
*
* @param amount The stake amount.
* @param lock The lock period committed.
*
* @return bonusAmount The bonus value of of the.
*/
function _calculateBonus(uint256 amount, Lock lock) internal pure returns (uint256 bonusAmount, uint256 lockDuration) {
uint256 bonus;
if (lock == Lock.Short) {
bonus = SHORT_BONUS;
lockDuration = SHORT_LOCK_TIME;
} else if (lock == Lock.Medium) {
bonus = MEDIUM_BONUS;
lockDuration = MEDIUM_LOCK_TIME;
} else if (lock == Lock.Long) {
bonus = LONG_BONUS;
lockDuration = LONG_LOCK_TIME;
}
bonusAmount = amount + (amount * bonus) / ONE;
}
/**
* @notice This internal function adapted from the external withdraw function in the LockingVault
* contract, with a key modification: it omits the token transfer transaction. This
* is because the tokens are already present within this contract. Additionally, the function
* adds an address account parameter to specify the user whose voting power needs updating.
* In the Locking Vault msg.sender directly indicated the user, wheras in this
* context msg.sender refers to the contract itself. Therefore, we explicitly pass the
* user's address.
*
* @param amount The amount of token to withdraw.
* @param account The funded account for the withdrawal.
*/
function _subtractVotingPower(uint256 amount, address account) internal {
if (amount > type(uint96).max) revert ASR_AmountTooBig();
// Load our deposits storage
Storage.AddressUint storage userData = _deposits()[account];
// Reduce the user's stored balance
// If properly optimized this block should result in 1 sload 1 store
userData.amount -= uint96(amount);
address delegate = userData.who;
// Reduce the delegate voting power
// Get the storage pointer
History.HistoricalBalances memory votingPower = _votingPower();
// Load the most recent voter power stamp
uint256 delegateeVotes = votingPower.loadTop(delegate);
// remove the votes from the delegate
votingPower.push(delegate, delegateeVotes - amount);
// Emit an event to track votes
emit VoteChange(account, delegate, -1 * int256(amount));
}
/**
* @notice This internal function is adapted from the external deposit function from the LockingVault
* contract, with 2 key modifications: it omits the token transfer transaction and reverts if the
* specified delegation address does not align with the user's previously designated delegate.
*
* @param fundedAccount The address to credit this deposit to.
* @param amount The amount of token which is deposited.
* @param delegation Delegation address.
*/
function _addVotingPower(
address fundedAccount,
uint256 amount,
address delegation
) internal {
if (amount > type(uint96).max) revert ASR_AmountTooBig();
// No delegating to zero
if (delegation == address(0)) revert ASR_ZeroAddress("delegation");
// Load our deposits storage
Storage.AddressUint storage userData = _deposits()[fundedAccount];
// Load who has the user's votes
address delegate = userData.who;
if (delegate == address(0)) {
// If the user is un-delegated we delegate to their indicated address
delegate = delegation;
// Set the delegation
userData.who = delegate;
} if (delegation != delegate) {
revert ASR_InvalidDelegationAddress();
}
// Now we increase the user's balance
userData.amount += uint96(amount);
// Next we increase the delegation to their delegate
// Get the storage pointer
History.HistoricalBalances memory votingPower = _votingPower();
// Load the most recent voter power stamp
uint256 delegateeVotes = votingPower.loadTop(delegate);
// Emit an event to track votes
emit VoteChange(fundedAccount, delegate, int256(amount));
// Add the newly deposited votes to the delegate
votingPower.push(delegate, delegateeVotes + amount);
}
/**
* @notice This function is taken from the LockingVault contract. It is a single endpoint
* for loading storage for deposits.
*
* @return A storage mapping which can be used to look
* up deposit data.
*/
function _deposits()
internal
pure
returns (mapping(address => Storage.AddressUint) storage)
{
// This call returns a storage mapping with a unique non overwrite-able storage location
// which can be persisted through upgrades, even if they change storage layout
return (Storage.mappingAddressToPackedAddressUint("deposits"));
}
/**
* @notice This function is taken from the LockingVault contract. Returns the historical
* voting power tracker.
*
*
* @return A struct which can push to and find items in
* block indexed storage.
*/
function _votingPower()
internal
pure
returns (History.HistoricalBalances memory)
{
// This call returns a storage mapping with a unique non overwrite-able storage location
// which can be persisted through upgrades, even if they change storage layout
return (History.load("votingPower"));
}
/**
* @notice This function is taken from the LockingVault contract. Loads the voting power of a
* user. It is revised to no longer remove stale blocks from the queue to address the
* problem of gas depletion encountered with overly long queues.
*
* @param user The address we want to load the voting power of.
* @param blockNumber The block number we want the user's voting power at.
*
* @return The number of votes.
*/
function queryVotePower(
address user,
uint256 blockNumber,
bytes calldata
) external view override returns (uint256) {
return queryVotePowerView(user, blockNumber);
}
/**
* @notice This function is taken from the LockingVault contract. Loads the voting power of a
* user without changing state.
*
* @param user The address we want to load the voting power of.
* @param blockNumber The block number we want the user's voting power at.
*
* @return The number of votes.
*/
function queryVotePowerView(address user, uint256 blockNumber)
public
view
returns (uint256)
{
// Get our reference to historical data
History.HistoricalBalances memory votingPower = _votingPower();
// Find the historical datum
return votingPower.find(user, blockNumber);
}
/**
* @notice This function is taken from the LockingVault contract, it changes a user's voting power.
*
* @param newDelegate The new address which gets voting power.
*/
function changeDelegation(address newDelegate) external {
// No delegating to zero
if (newDelegate == address(0)) revert ASR_ZeroAddress("delegation");
// Get the stored user data
Storage.AddressUint storage userData = _deposits()[msg.sender];
// Get the user balance
uint256 userBalance = uint256(userData.amount);
address oldDelegate = userData.who;
// Reset the user delegation
userData.who = newDelegate;
// Reduce the old voting power
// Get the storage pointer
History.HistoricalBalances memory votingPower = _votingPower();
// Load the old delegate's voting power
uint256 oldDelegateVotes = votingPower.loadTop(oldDelegate);
// Reduce the old voting power
votingPower.push(oldDelegate, oldDelegateVotes - userBalance);
// Emit an event to track votes
emit VoteChange(msg.sender, oldDelegate, -1 * int256(userBalance));
// Get the new delegate's votes
uint256 newDelegateVotes = votingPower.loadTop(newDelegate);
// Store the increase in power
votingPower.push(newDelegate, newDelegateVotes + userBalance);
// Emit an event tracking this voting power change
emit VoteChange(msg.sender, newDelegate, int256(userBalance));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.20;
import "./Storage.sol";
// This library is an assembly optimized storage library which is designed
// to track timestamp history in a struct which uses hash derived pointers.
// WARNING - Developers using it should not access the underlying storage
// directly since we break some assumptions of high level solidity. Please
// note this library also increases the risk profile of memory manipulation
// please be cautious in your usage of uninitialized memory structs and other
// anti patterns.
library History {
// The storage layout of the historical array looks like this
// [(128 bit min index)(128 bit length)] [0][0] ... [(64 bit block num)(192 bit data)] .... [(64 bit block num)(192 bit data)]
// We give the option to the invoker of the search function the ability to clear
// stale storage. To find data we binary search for the block number we need
// This library expects the blocknumber indexed data to be pushed in ascending block number
// order and if data is pushed with the same blocknumber it only retains the most recent.
// This ensures each blocknumber is unique and contains the most recent data at the end
// of whatever block it indexes [as long as that block is not the current one].
// A struct which wraps a memory pointer to a string and the pointer to storage
// derived from that name string by the storage library
// WARNING - For security purposes never directly construct this object always use load
struct HistoricalBalances {
string name;
// Note - We use bytes32 to reduce how easy this is to manipulate in high level sol
bytes32 cachedPointer;
}
/// @notice The method by which inheriting contracts init the HistoricalBalances struct
/// @param name The name of the variable. Note - these are globals, any invocations of this
/// with the same name work on the same storage.
/// @return The memory pointer to the wrapper of the storage pointer
function load(string memory name)
internal
pure
returns (HistoricalBalances memory)
{
mapping(address => uint256[]) storage storageData =
Storage.mappingAddressToUnit256ArrayPtr(name);
bytes32 pointer;
assembly {
pointer := storageData.slot
}
return HistoricalBalances(name, pointer);
}
/// @notice An unsafe method of attaching the cached ptr in a historical balance memory objects
/// @param pointer cached pointer to storage
/// @return storageData A storage array mapping pointer
/// @dev PLEASE DO NOT USE THIS METHOD WITHOUT SERIOUS REVIEW. IF AN EXTERNAL ACTOR CAN CALL THIS WITH
// ARBITRARY DATA THEY MAY BE ABLE TO OVERWRITE ANY STORAGE IN THE CONTRACT.
function _getMapping(bytes32 pointer)
private
pure
returns (mapping(address => uint256[]) storage storageData)
{
assembly {
storageData.slot := pointer
}
}
/// @notice This function adds a block stamp indexed piece of data to a historical data array
/// To prevent duplicate entries if the top of the array has the same blocknumber
/// the value is updated instead
/// @param wrapper The wrapper which hold the reference to the historical data storage pointer
/// @param who The address which indexes the array we need to push to
/// @param data The data to append, should be at most 192 bits and will revert if not
function push(
HistoricalBalances memory wrapper,
address who,
uint256 data
) internal {
// Check preconditions
// OoB = Out of Bounds, short for contract bytecode size reduction
require(data <= type(uint192).max, "OoB");
// Get the storage this is referencing
mapping(address => uint256[]) storage storageMapping =
_getMapping(wrapper.cachedPointer);
// Get the array we need to push to
uint256[] storage storageData = storageMapping[who];
// We load the block number and then shift it to be in the top 64 bits
uint256 blockNumber = block.number << 192;
// We combine it with the data, because of our require this will have a clean
// top 64 bits
uint256 packedData = blockNumber | data;
// Load the array length
(uint256 minIndex, uint256 length) = _loadBounds(storageData);
// On the first push we don't try to load
uint256 loadedBlockNumber = 0;
if (length != 0) {
(loadedBlockNumber, ) = _loadAndUnpack(storageData, length - 1);
}
// The index we push to, note - we use this pattern to not branch the assembly
uint256 index = length;
// If the caller is changing data in the same block we change the entry for this block
// instead of adding a new one. This ensures each block numb is unique in the array.
if (loadedBlockNumber == block.number) {
index = length - 1;
}
// We use assembly to write our data to the index
assembly {
// Stores packed data in the equivalent of storageData[length]
sstore(
add(
// The start of the data slots
add(storageData.slot, 1),
// index where we store
index
),
packedData
)
}
// Reset the boundaries if they changed
if (loadedBlockNumber != block.number) {
_setBounds(storageData, minIndex, length + 1);
}
}
/// @notice Loads the most recent timestamp of delegation power
/// @param wrapper The memory struct which we want to search for historical data
/// @param who The user who's balance we want to load
/// @return the top slot of the array
function loadTop(HistoricalBalances memory wrapper, address who)
internal
view
returns (uint256)
{
// Load the storage pointer
uint256[] storage userData = _getMapping(wrapper.cachedPointer)[who];
// Load the length
(, uint256 length) = _loadBounds(userData);
// If it's zero no data has ever been pushed so we return zero
if (length == 0) {
return 0;
}
// Load the current top
(, uint256 storedData) = _loadAndUnpack(userData, length - 1);
// and return it
return (storedData);
}
/// @notice Finds the data stored with the highest block number which is less than or equal to a provided
/// blocknumber.
/// @param wrapper The memory struct which we want to search for historical data
/// @param who The address which indexes the array to be searched
/// @param blocknumber The blocknumber we want to load the historical data of
/// @return The loaded unpacked data at this point in time.
function find(
HistoricalBalances memory wrapper,
address who,
uint256 blocknumber
) internal view returns (uint256) {
// Get the storage this is referencing
mapping(address => uint256[]) storage storageMapping =
_getMapping(wrapper.cachedPointer);
// Get the array we need to push to
uint256[] storage storageData = storageMapping[who];
// Pre load the bounds
(uint256 minIndex, uint256 length) = _loadBounds(storageData);
// Search for the blocknumber
(, uint256 loadedData) =
_find(storageData, blocknumber, 0, minIndex, length);
// In this function we don't have to change the stored length data
return (loadedData);
}
/// @notice Finds the data stored with the highest blocknumber which is less than or equal to a provided block number
/// Opportunistically clears any data older than staleBlock which is possible to clear.
/// @param wrapper The memory struct which points to the storage we want to search
/// @param who The address which indexes the historical data we want to search
/// @param blocknumber The blocknumber we want to load the historical state of
/// @param staleBlock A block number which we can [but are not obligated to] delete history older than
/// @return The found data
function findAndClear(
HistoricalBalances memory wrapper,
address who,
uint256 blocknumber,
uint256 staleBlock
) internal returns (uint256) {
// Get the storage this is referencing
mapping(address => uint256[]) storage storageMapping =
_getMapping(wrapper.cachedPointer);
// Get the array we need to push to
uint256[] storage storageData = storageMapping[who];
// Pre load the bounds
(uint256 minIndex, uint256 length) = _loadBounds(storageData);
// Search for the blocknumber
(uint256 staleIndex, uint256 loadedData) =
_find(storageData, blocknumber, staleBlock, minIndex, length);
// We clear any data in the stale region
// Note - Since find returns 0 if no stale data is found and we use > instead of >=
// this won't trigger if no stale data is found. Plus it won't trigger on minIndex == staleIndex
// == maxIndex and clear the whole array.
if (staleIndex > minIndex) {
// Delete the outdated stored info
_clear(minIndex, staleIndex, storageData);
// Reset the array info with stale index as the new minIndex
_setBounds(storageData, staleIndex, length);
}
return (loadedData);
}
/// @notice Searches for the data stored at the largest blocknumber index less than a provided parameter.
/// Allows specification of a expiration stamp and returns the greatest examined index which is
/// found to be older than that stamp.
/// @param data The stored data
/// @param blocknumber the blocknumber we want to load the historical data for.
/// @param staleBlock The oldest block that we care about the data stored for, all previous data can be deleted
/// @param startingMinIndex The smallest filled index in the array
/// @param length the length of the array
/// @return Returns the largest stale data index seen or 0 for no seen stale data and the stored data
function _find(
uint256[] storage data,
uint256 blocknumber,
uint256 staleBlock,
uint256 startingMinIndex,
uint256 length
) private view returns (uint256, uint256) {
// We explicitly revert on the reading of memory which is uninitialized
require(length != 0, "uninitialized");
// Do some correctness checks
require(staleBlock <= blocknumber);
require(startingMinIndex < length);
// Load the bounds of our binary search
uint256 maxIndex = length - 1;
uint256 minIndex = startingMinIndex;
uint256 staleIndex = 0;
// We run a binary search on the block number fields in the array between
// the minIndex and maxIndex. If we find indexes with blocknumber < staleBlock
// we set staleIndex to them and return that data for an optional clearing step
// in the calling function.
while (minIndex != maxIndex) {
// We use the ceil instead of the floor because this guarantees that
// we pick the highest blocknumber less than or equal the requested one
uint256 mid = (minIndex + maxIndex + 1) / 2;
// Load and unpack the data in the midpoint index
(uint256 pastBlock, uint256 loadedData) = _loadAndUnpack(data, mid);
// If we've found the exact block we are looking for
if (pastBlock == blocknumber) {
// Then we just return the data
return (staleIndex, loadedData);
// Otherwise if the loaded block is smaller than the block number
} else if (pastBlock < blocknumber) {
// Then we first check if this is possibly a stale block
if (pastBlock < staleBlock) {
// If it is we mark it for clearing
staleIndex = mid;
}
// We then repeat the search logic on the indices greater than the midpoint
minIndex = mid;
// In this case the pastBlock > blocknumber
} else {
// We then repeat the search on the indices below the midpoint
maxIndex = mid - 1;
}
}
// We load at the final index of the search
(uint256 _pastBlock, uint256 _loadedData) =
_loadAndUnpack(data, minIndex);
// This will only be hit if a user has misconfigured the stale index and then
// tried to load father into the past than has been preserved
require(_pastBlock <= blocknumber, "Search Failure");
return (staleIndex, _loadedData);
}
/// @notice Clears storage between two bounds in array
/// @param oldMin The first index to set to zero
/// @param newMin The new minimum filled index, ie clears to index < newMin
/// @param data The storage array pointer
function _clear(
uint256 oldMin,
uint256 newMin,
uint256[] storage data
) private {
// Correctness checks on this call
require(oldMin <= newMin);
// This function is private and trusted and should be only called by functions which ensure
// that oldMin < newMin < length
assembly {
// The layout of arrays in solidity is [length][data]....[data] so this pointer is the
// slot to write to data
let dataLocation := add(data.slot, 1)
// Loop through each index which is below new min and clear the storage
// Note - Uses strict min so if given an input like oldMin = 5 newMin = 5 will be a no op
for {
let i := oldMin
} lt(i, newMin) {
i := add(i, 1)
} {
// store at the starting data pointer + i 256 bits of zero
sstore(add(dataLocation, i), 0)
}
}
}
/// @notice Loads and unpacks the block number index and stored data from a data array
/// @param data the storage array
/// @param i the index to load and unpack
/// @return (block number, stored data)
function _loadAndUnpack(uint256[] storage data, uint256 i)
private
view
returns (uint256, uint256)
{
// This function is trusted and should only be called after checking data lengths
// we use assembly for the sload to avoid reloading length.
uint256 loaded;
assembly {
loaded := sload(add(add(data.slot, 1), i))
}
// Unpack the packed 64 bit block number and 192 bit data field
return (
loaded >> 192,
loaded &
0x0000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff
);
}
/// @notice This function sets our non standard bounds data field where a normal array
/// would have length
/// @param data the pointer to the storage array
/// @param minIndex The minimum non stale index
/// @param length The length of the storage array
function _setBounds(
uint256[] storage data,
uint256 minIndex,
uint256 length
) private {
// Correctness check
require(minIndex < length);
assembly {
// Ensure data cleanliness
let clearedLength := and(
length,
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff
)
// We move the min index into the top 128 bits by shifting it left by 128 bits
let minInd := shl(128, minIndex)
// We pack the data using binary or
let packed := or(minInd, clearedLength)
// We store in the packed data in the length field of this storage array
sstore(data.slot, packed)
}
}
/// @notice This function loads and unpacks our packed min index and length for our custom storage array
/// @param data The pointer to the storage location
/// @return minInd the first filled index in the array
/// @return length the length of the array
function _loadBounds(uint256[] storage data)
private
view
returns (uint256 minInd, uint256 length)
{
// Use assembly to manually load the length storage field
uint256 packedData;
assembly {
packedData := sload(data.slot)
}
// We use a shift right to clear out the low order bits of the data field
minInd = packedData >> 128;
// We use a binary and to extract only the bottom 128 bits
length =
packedData &
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
interface IArcadeStakingRewards {
// ================================================= EVENTS ==================================================
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 depositId, uint256 amount, uint8 lock);
event Withdrawn(address indexed user, uint256 depositId, uint256 amount, uint8 lock);
event RewardPaid(address indexed user, uint256 reward, uint256 depositId);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
event VoteChange(address indexed from, address indexed to, int256 amount);
event RewardEmissionActivated(uint256 rewardAmount, uint256 rewardEnd);
// ================================================= STRUCTS =================================================
enum Lock {
Short,
Medium,
Long
}
struct UserStake {
Lock lock;
uint32 unlockTimestamp;
uint256 amount;
uint256 rewardPerTokenPaid;
}
// ============================================= VIEW FUNCTIONS ==============================================
function getTotalUserDeposits(address account) external view returns (uint256);
function getPendingRewards(address account, uint256 depositId) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256, uint256);
function rewardsToken() external view returns (IERC20);
function totalSupply() external view returns (uint256);
function getAmountWithBonus(address account, uint256 depositId) external view returns (uint256);
function getActiveStakes(address account) external view returns (uint256[] memory);
function getLastDepositId(address account) external view returns (uint256);
function getDepositIndicesWithRewards(address account) external view returns (uint256[] memory, uint256[] memory);
function getUserStake(address account, uint256 depositId) external view returns (uint8 lock, uint32 unlockTimestamp, uint256 amount, uint256 rewardPerTokenPaid, uint256 rewards);
function getTotalUserDepositsWithBonus(address account) external view returns (uint256);
function balanceOfDeposit(address account, uint256 depositId) external view returns (uint256);
function getTotalUserPendingRewards(address account) external view returns (uint256);
function convertLPToArcd(uint256 arcdWethPairAmount) external view returns (uint256);
// =========================================== MUTATIVE FUNCTIONS ============================================
function exitAll() external;
function exit(uint256 depositId) external;
function claimReward(uint256 depositId) external;
function claimRewardAll() external;
function deposit(uint256 amount, address firstDelegation, Lock lock) external;
function withdraw(uint256 amount, uint256 depositId) external;
function setRewardsDuration(uint256 _rewardsDuration) external;
function recoverERC20(address tokenAddress, uint256 tokenAmount) external;
function pause() external;
function unpause() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @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: Apache-2.0
pragma solidity 0.8.20;
interface IVotingVault {
/// @notice Attempts to load the voting power of a user
/// @param user The address we want to load the voting power of
/// @param blockNumber the block number we want the user's voting power at
/// @param extraData Abi encoded optional extra data used by some vaults, such as merkle proofs
/// @return the number of votes
function queryVotePower(
address user,
uint256 blockNumber,
bytes calldata extraData
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../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 An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev 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);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that 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(token).code.length > 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
/**
* @title Staking
* @author Non-Fungible Technologies, Inc.
*
* This file contains all custom errors for the ArcadeStakingRewards contract.
* All errors are prefixed by "ASR_" for ArcadeStakingRewards. Errors located in one place
* to make it possible to holistically look at all the failure cases.
*/
// ==================================== Arcade Staking Rewards Errors ======================================
/**
* @notice Zero address passed in where not allowed.
* @param addressType The name of the parameter for which a zero
* address was provided.
*/
error ASR_ZeroAddress(string addressType);
/**
* @notice Cannot withdraw or stake amount zero.
*/
error ASR_ZeroAmount();
/**
* @notice ARCDWETH to ARCD conversion rate cannot be zero.
*/
error ASR_ZeroConversionRate();
/**
* @notice Previous rewards period must be complete
* to update rewards duration.
*/
error ASR_RewardsPeriod();
/**
* @notice Staking token cannot be ERC20 recovered.
*/
error ASR_StakingToken();
/**
* @notice Reward + leftover must be less than contract reward balance.
* This keeps the reward in a range less than 2^256 / 10^18
* and prevents overflow.
*/
error ASR_RewardTooHigh();
/**
* @notice User tries to withdraw an amount greater than
* than their balance.
*/
error ASR_BalanceAmount();
/**
* @notice Cannot withdraw a deposit which is still locked.
*/
error ASR_Locked();
/**
* @notice Cannot withdraw reward tokens unless totalDeposits == 0 to
* safeguard rewardsRate.
*
*/
error ASR_RewardsToken();
/**
* @notice Deposits number is larger than MAX_ITERATIONS.
*
*/
error ASR_DepositCountExceeded();
/**
* @notice The provided delegate address does not match their initial delegate.
*/
error ASR_InvalidDelegationAddress();
/**
* @notice The reward amount in notifyRewardAmount is less than the allowed minimum.
*/
error ASR_MinimumRewardAmount();
/**
* @notice The reward rate cannot be zero.
*/
error ASR_ZeroRewardRate();
/**
* @notice Amount cannot exceed the maximum value that can be held by a uint96.
*/
error ASR_AmountTooBig();
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.20;
// This library allows for secure storage pointers across proxy implementations
// It will return storage pointers based on a hashed name and type string.
library Storage {
// This library follows a pattern which if solidity had higher level
// type or macro support would condense quite a bit.
// Each basic type which does not support storage locations is encoded as
// a struct of the same name capitalized and has functions 'load' and 'set'
// which load the data and set the data respectively.
// All types will have a function of the form 'typename'Ptr('name') -> storage ptr
// which will return a storage version of the type with slot which is the hash of
// the variable name and type string. This pointer allows easy state management between
// upgrades and overrides the default solidity storage slot system.
/// @dev The address type container
struct Address {
address data;
}
/// @notice A function which turns a variable name for a storage address into a storage
/// pointer for its container.
/// @param name the variable name
/// @return data the storage pointer
function addressPtr(string memory name)
internal
pure
returns (Address storage data)
{
bytes32 typehash = keccak256("address");
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
assembly {
data.slot := offset
}
}
/// @notice A function to load an address from the container struct
/// @param input the storage pointer for the container
/// @return the loaded address
function load(Address storage input) internal view returns (address) {
return input.data;
}
/// @notice A function to set the internal field of an address container
/// @param input the storage pointer to the container
/// @param to the address to set the container to
function set(Address storage input, address to) internal {
input.data = to;
}
/// @dev The uint256 type container
struct Uint256 {
uint256 data;
}
/// @notice A function which turns a variable name for a storage uint256 into a storage
/// pointer for its container.
/// @param name the variable name
/// @return data the storage pointer
function uint256Ptr(string memory name)
internal
pure
returns (Uint256 storage data)
{
bytes32 typehash = keccak256("uint256");
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
assembly {
data.slot := offset
}
}
/// @notice A function to load an uint256 from the container struct
/// @param input the storage pointer for the container
/// @return the loaded uint256
function load(Uint256 storage input) internal view returns (uint256) {
return input.data;
}
/// @notice A function to set the internal field of a unit256 container
/// @param input the storage pointer to the container
/// @param to the address to set the container to
function set(Uint256 storage input, uint256 to) internal {
input.data = to;
}
/// @notice Returns the storage pointer for a named mapping of address to uint256
/// @param name the variable name for the pointer
/// @return data the mapping pointer
function mappingAddressToUnit256Ptr(string memory name)
internal
pure
returns (mapping(address => uint256) storage data)
{
bytes32 typehash = keccak256("mapping(address => uint256)");
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
assembly {
data.slot := offset
}
}
/// @notice Returns the storage pointer for a named mapping of address to uint256[]
/// @param name the variable name for the pointer
/// @return data the mapping pointer
function mappingAddressToUnit256ArrayPtr(string memory name)
internal
pure
returns (mapping(address => uint256[]) storage data)
{
bytes32 typehash = keccak256("mapping(address => uint256[])");
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
assembly {
data.slot := offset
}
}
/// @notice Allows external users to calculate the slot given by this lib
/// @param typeString the string which encodes the type
/// @param name the variable name
/// @return the slot assigned by this lib
function getPtr(string memory typeString, string memory name)
external
pure
returns (uint256)
{
bytes32 typehash = keccak256(abi.encodePacked(typeString));
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
return (uint256)(offset);
}
// A struct which represents 1 packed storage location with a compressed
// address and uint96 pair
struct AddressUint {
address who;
uint96 amount;
}
/// @notice Returns the storage pointer for a named mapping of address to uint256[]
/// @param name the variable name for the pointer
/// @return data the mapping pointer
function mappingAddressToPackedAddressUint(string memory name)
internal
pure
returns (mapping(address => AddressUint) storage data)
{
bytes32 typehash = keccak256("mapping(address => AddressUint)");
bytes32 offset = keccak256(abi.encodePacked(typehash, name));
assembly {
data.slot := offset
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
{
"compilationTarget": {
"src/ArcadeStakingRewards.sol": "ArcadeStakingRewards"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 2
},
"remappings": [
":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
":ds-test/=lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/"
],
"viaIR": true
}
[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_rewardsDistribution","type":"address"},{"internalType":"address","name":"_rewardsToken","type":"address"},{"internalType":"address","name":"_arcdWethLP","type":"address"},{"internalType":"uint256","name":"_lpToArcdRate","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"ASR_AmountTooBig","type":"error"},{"inputs":[],"name":"ASR_BalanceAmount","type":"error"},{"inputs":[],"name":"ASR_DepositCountExceeded","type":"error"},{"inputs":[],"name":"ASR_InvalidDelegationAddress","type":"error"},{"inputs":[],"name":"ASR_Locked","type":"error"},{"inputs":[],"name":"ASR_MinimumRewardAmount","type":"error"},{"inputs":[],"name":"ASR_RewardTooHigh","type":"error"},{"inputs":[],"name":"ASR_RewardsPeriod","type":"error"},{"inputs":[],"name":"ASR_RewardsToken","type":"error"},{"inputs":[],"name":"ASR_StakingToken","type":"error"},{"inputs":[{"internalType":"string","name":"addressType","type":"string"}],"name":"ASR_ZeroAddress","type":"error"},{"inputs":[],"name":"ASR_ZeroAmount","type":"error"},{"inputs":[],"name":"ASR_ZeroConversionRate","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Recovered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"rewardAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewardEnd","type":"uint256"}],"name":"RewardEmissionActivated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"depositId","type":"uint256"}],"name":"RewardPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newDuration","type":"uint256"}],"name":"RewardsDurationUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"depositId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint8","name":"lock","type":"uint8"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"int256","name":"amount","type":"int256"}],"name":"VoteChange","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"depositId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint8","name":"lock","type":"uint8"}],"name":"Withdrawn","type":"event"},{"inputs":[],"name":"LONG_BONUS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LONG_LOCK_TIME","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LP_TO_ARCD_DENOMINATOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LP_TO_ARCD_RATE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_DEPOSITS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MEDIUM_BONUS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MEDIUM_LOCK_TIME","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ONE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SHORT_BONUS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SHORT_LOCK_TIME","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"arcdWethLP","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"depositId","type":"uint256"}],"name":"balanceOfDeposit","outputs":[{"internalType":"uint256","name":"depositBalance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newDelegate","type":"address"}],"name":"changeDelegation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"depositId","type":"uint256"}],"name":"claimReward","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimRewardAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"arcdWethLPAmount","type":"uint256"}],"name":"convertLPToArcd","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"delegation","type":"address"},{"internalType":"enum IArcadeStakingRewards.Lock","name":"lock","type":"uint8"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"depositId","type":"uint256"}],"name":"exit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"exitAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getActiveStakes","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"depositId","type":"uint256"}],"name":"getAmountWithBonus","outputs":[{"internalType":"uint256","name":"amountWithBonus","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getDepositIndicesWithRewards","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getLastDepositId","outputs":[{"internalType":"uint256","name":"lastDepositId","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"depositId","type":"uint256"}],"name":"getPendingRewards","outputs":[{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRewardForDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getTotalUserDeposits","outputs":[{"internalType":"uint256","name":"userBalance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getTotalUserDepositsWithBonus","outputs":[{"internalType":"uint256","name":"totalDepositsWithBonuses","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getTotalUserPendingRewards","outputs":[{"internalType":"uint256","name":"totalRewards","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"depositId","type":"uint256"}],"name":"getUserStake","outputs":[{"internalType":"uint8","name":"lock","type":"uint8"},{"internalType":"uint32","name":"unlockTimestamp","type":"uint32"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"rewardPerTokenPaid","type":"uint256"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTimeRewardApplicable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastUpdateTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"notifiedRewardAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"name":"notifyRewardAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"periodFinish","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"blockNumber","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"queryVotePower","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"blockNumber","type":"uint256"}],"name":"queryVotePowerView","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"uint256","name":"tokenAmount","type":"uint256"}],"name":"recoverERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardPerToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerTokenStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardsDistribution","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardsDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardsToken","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_rewardsDistribution","type":"address"}],"name":"setRewardsDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_rewardsDuration","type":"uint256"}],"name":"setRewardsDuration","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"stakes","outputs":[{"internalType":"enum IArcadeStakingRewards.Lock","name":"lock","type":"uint8"},{"internalType":"uint32","name":"unlockTimestamp","type":"uint32"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"rewardPerTokenPaid","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalDeposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalDepositsWithBonus","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unclaimedRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"depositId","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]