Verified contractExactMIT
Staking
Address0x32a422b010574ec8a287c122c3524e7994b8703d
- Balance
0 ETH
- Transactions
219
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 21,593,405
- Creation transaction
- 0x806488ca76…d00583c4ff
13 files
- contracts/Staking.solmain13.8 KB
- @openzeppelin/contracts/access/Ownable.sol3.1 KB
- @openzeppelin/contracts/access/Ownable2Step.sol1.99 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- @openzeppelin/contracts/utils/Address.sol6.26 KB
- @openzeppelin/contracts/utils/Context.sol963 B
- @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol661 B
- @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol3.53 KB
- @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol1.29 KB
- contracts/interfaces/IStaking.sol15.31 KB
- contracts/libraries/UnsafeMath.sol856 B
contracts/Staking.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IUniswapV2Factory} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import {IUniswapV2Router02} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import {IStaking} from "./interfaces/IStaking.sol";
import {UnsafeMath} from "./libraries/UnsafeMath.sol";
contract Staking is IStaking, Ownable2Step {
using UnsafeMath for uint256;
using SafeERC20 for IERC20;
/// @inheritdoc IStaking
uint256 public constant MAX_STAKE_AMOUNT = 40e6 ether;
/// @inheritdoc IStaking
uint256 public constant MAX_STAKE_AMOUNT_USDT = 100_000e6;
/// @inheritdoc IStaking
uint256 public immutable deployedAt;
/// @inheritdoc IStaking
uint256 public immutable bonusPeriod;
/// @inheritdoc IStaking
address public immutable usdt;
/// @inheritdoc IStaking
IERC20 public immutable token;
/// @inheritdoc IStaking
IUniswapV2Router02 public immutable uniV2Router;
/// @inheritdoc IStaking
uint256 public rewards;
StakingPool[] private _stakingPools;
/// @inheritdoc IStaking
function stakingPools(uint256 poolIndex) external view returns (StakingPool memory stakingPool) {
return _stakingPools[poolIndex];
}
/// @inheritdoc IStaking
function stakingPoolsList() external view returns (StakingPool[] memory) {
return _stakingPools;
}
/// @inheritdoc IStaking
function stakingPoolsLength() external view returns (uint256) {
return _stakingPools.length;
}
Stake[] private _stakes;
/// @inheritdoc IStaking
function stakes(uint256 stakeIndex) external view returns (Stake memory stake_) {
return _stakes[stakeIndex];
}
/// @inheritdoc IStaking
function stakesLength() external view returns (uint256) {
return _stakes.length;
}
/// @inheritdoc IStaking
mapping(address account => bool bonusUsed) public bonusIsUsed;
constructor(
address owner_,
uint256 bonusPeriod_,
address usdt_,
IERC20 token_,
IUniswapV2Router02 uniV2Router_,
StakingPool[] memory stakingPools_
) Ownable(owner_) {
if (usdt_ == address(0)) revert AddressIsZero();
if (address(token_) == address(0)) revert AddressIsZero();
bonusPeriod = bonusPeriod_;
usdt = usdt_;
token = token_;
uniV2Router = uniV2Router_;
IUniswapV2Factory uniV2Factory = IUniswapV2Factory(uniV2Router.factory());
// slither-disable-next-line unused-return
if (uniV2Factory.getPair(address(token_), usdt_) == address(0)) uniV2Factory.createPair(address(token_), usdt_);
deployedAt = block.timestamp;
for (uint256 i = 0; i < stakingPools_.length; i++) _createStakingPool(stakingPools_[i]);
}
/// @inheritdoc IStaking
function replenishRewards(uint256 amount) external onlyOwner returns (uint256 availableRewards) {
rewards = availableRewards = rewards + amount;
emit RewardPoolIncreased(amount, availableRewards);
token.safeTransferFrom(msg.sender, address(this), amount);
}
/// @inheritdoc IStaking
function decreaseRewardPool(uint256 amount) external onlyOwner returns (uint256 availableRewards) {
uint256 currentRewardPool = rewards;
if (currentRewardPool < amount) revert RewardPoolIsEmpty(amount, currentRewardPool);
rewards = availableRewards = currentRewardPool.unsafeSub(amount);
emit RewardPoolDecreased(amount, availableRewards);
token.safeTransfer(msg.sender, amount);
}
/// @inheritdoc IStaking
function createStakingPool(StakingPool memory stakingPool) external onlyOwner returns (uint256 poolIndex) {
return _createStakingPool(stakingPool);
}
/// @inheritdoc IStaking
function updateStakingPool(uint256 poolIndex, StakingPool memory newParameters) external onlyOwner {
if (poolIndex >= _stakingPools.length) revert StakingPoolNotFound(poolIndex, _stakingPools.length);
_validateStakingPoolParameters(newParameters);
_stakingPools[poolIndex] = newParameters;
emit StakingPoolUpserted(poolIndex, newParameters);
}
/// @inheritdoc IStaking
function stake(uint256 poolIndex, uint256 amount) external returns (Stake memory stake_) {
address caller = msg.sender;
stake_ = _stakeNoTransfer(caller, poolIndex, amount);
token.safeTransferFrom(caller, address(this), amount);
}
/// @inheritdoc IStaking
function cancelStaking(
uint256 stakeIndex,
uint256 unstakeAmount
) external returns (uint256 newStakeAmount, uint256 newExpectedRewards) {
address caller = msg.sender;
Stake storage stake_ = _getStake(caller, stakeIndex);
if (block.timestamp > stake_.stakedAt + stake_.cancelPeriod) {
revert CancelPeriodIsClosed(block.timestamp, stake_.stakedAt, stake_.cancelPeriod);
}
uint256 prevBonus = _cancelStakeBonus(stake_);
uint256 rewardDiff;
(newStakeAmount, newExpectedRewards, rewardDiff) = _decreaseStakeAmount(
stake_,
unstakeAmount,
stake_.rewardX18
);
rewards += rewardDiff.unsafeAdd(prevBonus);
emit StakeCanceled(
stakeIndex,
caller,
stake_.stakingPoolIndex,
unstakeAmount,
newStakeAmount,
newExpectedRewards,
prevBonus
);
token.safeTransfer(caller, unstakeAmount);
}
/// @inheritdoc IStaking
function emergencyWithdrawal(
uint256 stakeIndex,
uint256 unstakeAmount
) external returns (uint256 penalty, uint256 rewards_) {
address caller = msg.sender;
Stake storage stake_ = _getStake(caller, stakeIndex);
uint256 rewardX18 = stake_.rewardX18;
penalty = unstakeAmount.unsafeDivCeil(10); // 10%
rewards_ = _calculateIntermediateReward(unstakeAmount, rewardX18, stake_);
(uint256 newStakeAmount, uint256 newExpectedRewards, uint256 rewardDiff) = _decreaseStakeAmount(
stake_,
unstakeAmount,
rewardX18
);
uint256 rewardPoolIncreaseValue = penalty.unsafeAdd(rewardDiff.unsafeSub(rewards_)).unsafeAdd(
_cancelStakeBonus(stake_)
);
rewards += rewardPoolIncreaseValue;
emit EmergencyWithdrawal(
stakeIndex,
caller,
stake_.stakingPoolIndex,
unstakeAmount,
newStakeAmount,
newExpectedRewards,
rewards_,
rewardPoolIncreaseValue
);
token.safeTransfer(caller, unstakeAmount.unsafeSub(penalty).unsafeAdd(rewards_));
}
/// @inheritdoc IStaking
function withdraw(uint256 stakeIndex) external returns (uint256 rewards_) {
address caller = msg.sender;
Stake storage stake_ = _getStake(caller, stakeIndex);
uint256 totalWithdrawalAmount;
(rewards_, totalWithdrawalAmount) = _withdrawNoTransfer(stakeIndex, caller, stake_);
token.safeTransfer(stake_.account, totalWithdrawalAmount);
}
/// @inheritdoc IStaking
function restake(
uint256 stakeIndex,
uint256 restakePoolIndex,
uint256 restakeAmount
) external returns (Stake memory restake_) {
address caller = msg.sender;
Stake storage stake_ = _getStake(caller, stakeIndex);
(, uint256 totalWithdrawalAmount) = _withdrawNoTransfer(stakeIndex, caller, stake_);
if (restakeAmount > totalWithdrawalAmount) {
revert InsufficientRestakeAmount(restakeAmount, totalWithdrawalAmount);
}
restake_ = _stakeNoTransfer(caller, restakePoolIndex, restakeAmount);
if (totalWithdrawalAmount > restakeAmount) {
token.safeTransfer(caller, totalWithdrawalAmount.unsafeSub(restakeAmount));
}
}
function _stakeNoTransfer(
address account,
uint256 poolIndex,
uint256 amount
) private returns (Stake memory stake_) {
uint256 timestamp = block.timestamp;
_validateStakingAmount(amount);
if (poolIndex >= _stakingPools.length) revert StakingPoolNotFound(poolIndex, _stakingPools.length);
StakingPool storage pool = _stakingPools[poolIndex];
if (!pool.enabled) revert StakingPoolIsDisabled(poolIndex);
uint256 rewardX18 = pool.rewardX18;
uint256 duration = pool.duration;
uint256 cancelPeriod = pool.cancelPeriod;
uint256 expectedRewards = (amount * rewardX18) / 1e18;
bool useBonus = timestamp <= deployedAt + bonusPeriod && !bonusIsUsed[account];
uint256 bonus = useBonus ? amount.unsafeDiv(20) : 0; // 5%
uint256 totalRewards = expectedRewards + bonus;
if (totalRewards > rewards) revert RewardPoolIsEmpty(totalRewards, rewards);
if (useBonus) bonusIsUsed[account] = true;
rewards = rewards.unsafeSub(totalRewards);
uint256 stakeIndex = _stakes.length;
stake_ = Stake({
inProgress: true,
account: account,
amount: amount,
stakingPoolIndex: poolIndex,
stakedAt: timestamp,
duration: duration,
endsAt: timestamp + duration,
cancelPeriod: cancelPeriod,
rewardX18: rewardX18,
expectedRewards: expectedRewards,
bonus: bonus
});
// check overflow before unstaking
amount + totalRewards;
_stakes.push(stake_);
emit Staked(stakeIndex, account, poolIndex, amount, duration, cancelPeriod, rewardX18, bonus);
}
function _createStakingPool(StakingPool memory pool) private returns (uint256 poolIndex) {
_validateStakingPoolParameters(pool);
poolIndex = _stakingPools.length;
_stakingPools.push(pool);
emit StakingPoolUpserted(poolIndex, pool);
}
function _withdrawNoTransfer(
uint256 stakeIndex,
address staker,
Stake storage stake_
) private returns (uint256 rewards_, uint256 totalWithdrawalAmount) {
uint256 stakeAmount = stake_.amount;
if (block.timestamp < stake_.endsAt) revert StakingNotFinished(block.timestamp, stake_.endsAt);
rewards_ = stake_.expectedRewards + stake_.bonus;
stake_.inProgress = false;
totalWithdrawalAmount = stakeAmount.unsafeAdd(rewards_);
emit Withdrawal(stakeIndex, staker, stake_.stakingPoolIndex, rewards_);
}
function _decreaseStakeAmount(
Stake storage stake_,
uint256 unstakeAmount,
uint256 rewardX18
) private returns (uint256 newStakeAmount, uint256 newExpectedRewards, uint256 rewardDiff) {
uint256 prevStakedAmount = stake_.amount;
if (unstakeAmount > prevStakedAmount) revert UnstakeAmountGTStakeAmount(unstakeAmount, prevStakedAmount);
newStakeAmount = prevStakedAmount.unsafeSub(unstakeAmount);
if (newStakeAmount == 0) stake_.inProgress = false;
stake_.amount = newStakeAmount;
uint256 prevExpectedRewards = stake_.expectedRewards;
stake_.expectedRewards = newExpectedRewards = newStakeAmount.unsafeMul(rewardX18) / 1e18;
rewardDiff = prevExpectedRewards.unsafeSub(newExpectedRewards);
}
function _cancelStakeBonus(Stake storage stake_) private returns (uint256 prevBonus) {
prevBonus = stake_.bonus;
if (prevBonus > 0) stake_.bonus = 0;
}
function _validateStakingAmount(uint256 amount) private view {
if (amount <= MAX_STAKE_AMOUNT) return;
(bool usdtEquivalentCalculated, uint256 usdtEquivalent) = _tryGetUSDTAmountOut(amount);
if (!usdtEquivalentCalculated || usdtEquivalent > MAX_STAKE_AMOUNT_USDT) {
revert MaxStakingAmountExceeded(amount, usdtEquivalent);
}
}
function _getStake(address caller, uint256 stakeIndex) private view returns (Stake storage stake_) {
if (stakeIndex >= _stakes.length) revert StakingNotFound(stakeIndex, _stakes.length);
stake_ = _stakes[stakeIndex];
if (caller != stake_.account) revert UnauthorizedAccount(caller, stake_.account);
if (!stake_.inProgress) revert StakingIsClosed(stakeIndex);
}
function _tryGetUSDTAmountOut(uint256 tokenAmountIn) private view returns (bool success, uint256 amountOut) {
address[] memory path = new address[](2);
path[0] = address(token);
path[1] = address(usdt);
try uniV2Router.getAmountsOut(tokenAmountIn, path) returns (uint256[] memory result) {
return (true, result[1]);
} catch {
return (false, 0);
}
}
function _validateStakingPoolParameters(StakingPool memory pool) private pure {
if (pool.cancelPeriod >= pool.duration) {
revert StakingPoolCancelPeriodGTEDuration(pool.cancelPeriod, pool.duration);
}
}
/// @dev uses unsafe `amount * rewardX18`
/// @dev block timestamp should be gte `stakedAt`
function _calculateIntermediateReward(
uint256 amount,
uint256 rewardX18,
Stake storage stake_
) private view returns (uint256) {
uint256 timestamp = block.timestamp;
if (timestamp >= stake_.endsAt) revert StakingIsFinished(timestamp, stake_.endsAt);
return
((amount.unsafeMul(rewardX18) * (timestamp.unsafeSub(stake_.stakedAt))) / 1e18).unsafeDiv(stake_.duration);
}
}
@openzeppelin/contracts/access/Ownable.sol
// 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);
}
}
@openzeppelin/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// 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);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// 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;
}
}
@openzeppelin/contracts/utils/Address.sol
// 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();
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contracts/interfaces/IStaking.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IUniswapV2Router02} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
interface IStaking {
/// @notice Emitted when the reward pool is increased
/// @param increaseAmount The amount by which the reward pool is increased
/// @param newRewardPoolValue The new total reward pool value after the increase
event RewardPoolIncreased(uint256 increaseAmount, uint256 newRewardPoolValue);
/// @notice Emitted when the reward pool is decreased
/// @param decreaseAmount The amount by which the reward pool is decreased
/// @param newRewardPoolValue The new total reward pool value after the decrease
event RewardPoolDecreased(uint256 decreaseAmount, uint256 newRewardPoolValue);
/// @notice Emitted when a staking pool is created or updated
/// @param index The index of the staking pool
/// @param pool The details of the staking pool
event StakingPoolUpserted(uint256 indexed index, StakingPool pool);
/// @notice Emitted when tokens are staked
/// @param stakeIndex The index of the stake
/// @param staker The address of the user staking tokens
/// @param stakingPoolIndex The index of the staking pool used
/// @param amount The amount of tokens staked
/// @param duration The duration of the staking period
/// @param cancelPeriod The period during which the stake can be canceled
/// @param rewardX18 The reward multiplier applied to the stake (scaled by 1e18)
/// @param bonus The bonus applied to the stake
event Staked(
uint256 indexed stakeIndex,
address indexed staker,
uint256 indexed stakingPoolIndex,
uint256 amount,
uint256 duration,
uint256 cancelPeriod,
uint256 rewardX18,
uint256 bonus
);
/// @notice Emitted when a stake is canceled
/// @param stakeIndex The index of the stake
/// @param staker The address of the user who canceled the stake
/// @param stakingPoolIndex The index of the staking pool used
/// @param unstakeAmount The amount of tokens unstaked
/// @param newStakeAmount The remaining staked amount after cancellation
/// @param newExpectedRewards The new expected rewards after the cancellation
/// @param prevBonus The previous bonus before the cancellation
event StakeCanceled(
uint256 indexed stakeIndex,
address indexed staker,
uint256 indexed stakingPoolIndex,
uint256 unstakeAmount,
uint256 newStakeAmount,
uint256 newExpectedRewards,
uint256 prevBonus
);
/// @notice Emitted when an emergency withdrawal is executed
/// @param stakeIndex The index of the stake
/// @param staker The address of the user executing the emergency withdrawal
/// @param stakingPoolIndex The index of the staking pool used
/// @param unstakeAmount The amount of tokens unstaked
/// @param newStakeAmount The remaining staked amount after withdrawal
/// @param newExpectedRewards The new expected rewards after the withdrawal
/// @param rewards The rewards the user earned prior to the emergency withdrawal
/// @param rewardPoolIncreaseValue The increase in the reward pool due to the emergency withdrawal
event EmergencyWithdrawal(
uint256 indexed stakeIndex,
address indexed staker,
uint256 indexed stakingPoolIndex,
uint256 unstakeAmount,
uint256 newStakeAmount,
uint256 newExpectedRewards,
uint256 rewards,
uint256 rewardPoolIncreaseValue
);
/// @notice Emitted when tokens are unstaked after the staking period is complete
/// @param stakeIndex The index of the stake
/// @param staker The address of the user unstaking tokens
/// @param stakingPoolIndex The index of the staking pool used
/// @param rewards The rewards earned by the user
event Withdrawal(
uint256 indexed stakeIndex,
address indexed staker,
uint256 indexed stakingPoolIndex,
uint256 rewards
);
/// @notice Indicates that the provided address is zero
error AddressIsZero();
/// @notice Indicates that a requested staking pool is not found
/// @param requestedStakingPoolIndex The index of the requested staking pool
/// @param stakingPoolsCount The total number of staking pools
error StakingPoolNotFound(uint256 requestedStakingPoolIndex, uint256 stakingPoolsCount);
/// @notice Indicates that a staking pool is disabled
/// @param poolIndex The index of the disabled staking pool
error StakingPoolIsDisabled(uint256 poolIndex);
/// @notice Indicates that the maximum staking amount is exceeded
/// @param stakingAmount The amount the user is attempting to stake
/// @param usdtEquivalent The USDT equivalent value of the staking amount
error MaxStakingAmountExceeded(uint256 stakingAmount, uint256 usdtEquivalent);
/// @notice Indicates that the reward pool is empty
/// @param expectedRewards The expected rewards for the stake
/// @param availableRewards The available rewards in the pool
error RewardPoolIsEmpty(uint256 expectedRewards, uint256 availableRewards);
/// @notice Indicates that a requested stake is not found
/// @param requestedStakingIndex The index of the requested stake
/// @param stakesCount The total number of stakes
error StakingNotFound(uint256 requestedStakingIndex, uint256 stakesCount);
/// @notice Indicates that an unauthorized account attempts an action
/// @param caller The address of the unauthorized account
/// @param staker The address of the staker
error UnauthorizedAccount(address caller, address staker);
/// @notice Indicates that attempting to perform an action on a stake that is not yet finished
/// @param currentTimestamp The current block timestamp
/// @param stakingEndsAt The timestamp when the stake ends
error StakingNotFinished(uint256 currentTimestamp, uint256 stakingEndsAt);
/// @notice Indicates that attempting to perform an action on a stake that has already finished
/// @param currentTimestamp The current block timestamp
/// @param stakingEndedAt The timestamp when the stake ended
error StakingIsFinished(uint256 currentTimestamp, uint256 stakingEndedAt);
/// @notice Indicates that attempting to perform an action on a closed stake
/// @param stakeIndex The index of the closed stake
error StakingIsClosed(uint256 stakeIndex);
/// @notice Indicates that attempting to unstake an amount greater than the staked amount
/// @param unstakeAmount The amount attempted to be unstaked
/// @param stakeAmount The total staked amount
error UnstakeAmountGTStakeAmount(uint256 unstakeAmount, uint256 stakeAmount);
/// @notice Indicates that the restake amount is insufficient
/// @param restakeAmount The amount attempted to be restaked
/// @param totalWithdrawalAmount The total amount withdrawn
error InsufficientRestakeAmount(uint256 restakeAmount, uint256 totalWithdrawalAmount);
/// @notice Indicates that attempting to cancel a stake after the cancel period has closed
/// @param currentTimestamp The current block timestamp
/// @param stakedAt The timestamp when the stake was created
/// @param cancelPeriod The duration of the cancel period
error CancelPeriodIsClosed(uint256 currentTimestamp, uint256 stakedAt, uint256 cancelPeriod);
/// @notice Indicates that the staking pool's cancel period is greater than or equal to its duration
/// @param cancelPeriod The cancel period of the staking pool
/// @param duration The duration of the staking pool
error StakingPoolCancelPeriodGTEDuration(uint256 cancelPeriod, uint256 duration);
/// @notice Struct representing a staking pool
/// @param enabled Whether the staking pool is enabled
/// @param duration The duration of the staking period
/// @param rewardX18 The reward multiplier applied to stakes (scaled by 1e18)
/// @param cancelPeriod The period during which a stake can be canceled
struct StakingPool {
bool enabled;
uint256 duration;
uint256 rewardX18;
uint256 cancelPeriod;
}
/// @notice Struct representing a user's stake
/// @param inProgress Whether the stake is currently active
/// @param account The address of the user who created the stake
/// @param amount The amount of tokens staked
/// @param stakingPoolIndex The index of the staking pool used
/// @param stakedAt The timestamp when the stake was created
/// @param duration The duration of the staking period
/// @param endsAt The timestamp when the staking period ends
/// @param cancelPeriod The period during which the stake can be canceled
/// @param rewardX18 The reward multiplier applied to the stake (scaled by 1e18)
/// @param expectedRewards The expected rewards for the stake
/// @param bonus The bonus applied to the stake
struct Stake {
bool inProgress;
address account;
uint256 amount;
uint256 stakingPoolIndex;
uint256 stakedAt;
uint256 duration;
uint256 endsAt;
uint256 cancelPeriod;
uint256 rewardX18;
uint256 expectedRewards;
uint256 bonus;
}
// #region public constants
// solhint-disable func-name-mixedcase
// slither-disable-start naming-convention
/// @notice The maximum amount of tokens that can be staked
function MAX_STAKE_AMOUNT() external pure returns (uint256);
/// @notice The maximum stake amount in USDT equivalent
function MAX_STAKE_AMOUNT_USDT() external pure returns (uint256);
// slither-disable-end naming-convention
// solhint-enable func-name-mixedcase
// #endregion
/// @notice The timestamp of contract deployment
function deployedAt() external view returns (uint256);
/// @notice The duration of the bonus period
function bonusPeriod() external view returns (uint256);
/// @notice The address of the USDT token
function usdt() external view returns (address);
/// @notice The address of the staking token
function token() external view returns (IERC20);
/// @notice The address of the Uniswap V2 router
function uniV2Router() external view returns (IUniswapV2Router02);
/// @notice The total amount of rewards available
function rewards() external view returns (uint256);
/// @notice Returns the details of a specific staking pool
/// @param poolIndex The index of the staking pool
/// @return stakingPool The staking pool details
function stakingPools(uint256 poolIndex) external view returns (StakingPool memory stakingPool);
/// @notice The list of all staking pools
function stakingPoolsList() external view returns (StakingPool[] memory);
/// @notice The number of staking pools
function stakingPoolsLength() external view returns (uint256);
/// @notice Returns the details of a specific stake
/// @param stakeIndex The index of the stake
/// @return stake The stake details
function stakes(uint256 stakeIndex) external view returns (Stake memory stake);
/// @notice The total number of stakes
function stakesLength() external view returns (uint256);
/// @notice Checks if a bonus has been used by a specific account
/// @param account The address of the user
/// @return bonusUsed True if the bonus has been used, false otherwise
function bonusIsUsed(address account) external view returns (bool bonusUsed);
// #region owner functions
/// @notice Replenishes the reward pool with additional tokens
/// @dev This function can only be called by the contract owner
/// @param amount The amount to replenish the reward pool
/// @return availableRewards The total rewards available after replenishment
function replenishRewards(uint256 amount) external returns (uint256 availableRewards);
/// @notice Decreases the reward pool by a specified amount
/// @dev This function can only be called by the contract owner
/// @param amount The amount by which to decrease the reward pool
/// @return availableRewards The total rewards available in the pool after the decrease
function decreaseRewardPool(uint256 amount) external returns (uint256 availableRewards);
/// @notice Creates a new staking pool
/// @dev This function can only be called by the contract owner
/// @param stakingPool The parameters of the new staking pool
/// @return poolIndex The index of the newly created staking pool
function createStakingPool(StakingPool memory stakingPool) external returns (uint256 poolIndex);
/// @notice Updates the parameters of an existing staking pool
/// @dev This function can only be called by the contract owner
/// @param poolIndex The index of the staking pool to update
/// @param newParameters The new parameters for the staking pool
function updateStakingPool(uint256 poolIndex, StakingPool memory newParameters) external;
// #endregion
/// @notice Allows a user to stake tokens in a specific pool
/// @param poolIndex The index of the staking pool
/// @param amount The amount of tokens to stake
/// @return stake_ The details of the created stake
function stake(uint256 poolIndex, uint256 amount) external returns (Stake memory stake_);
/// @notice Allows a user to cancel a stake and withdraw a portion of the staked tokens
/// @param stakeIndex The index of the stake
/// @param unstakeAmount The amount of tokens to unstake
/// @return newStakeAmount The remaining staked amount after cancellation
/// @return unstakedAmount The total amount of tokens unstaked
function cancelStaking(
uint256 stakeIndex,
uint256 unstakeAmount
) external returns (uint256 newStakeAmount, uint256 unstakedAmount);
/// @notice Allows a user to perform an emergency withdrawal
/// @param stakeIndex The index of the stake
/// @param unstakeAmount The amount of tokens to unstake
/// @return penalty The penalty applied for the emergency withdrawal
/// @return rewards_ The total rewards earned before the emergency withdrawal
function emergencyWithdrawal(
uint256 stakeIndex,
uint256 unstakeAmount
) external returns (uint256 penalty, uint256 rewards_);
/// @notice Allows a user to unstake tokens after the staking period is over
/// @param stakeIndex The index of the stake
/// @return rewards_ The total rewards earned for the stake
function withdraw(uint256 stakeIndex) external returns (uint256 rewards_);
/// @notice Allows a user to restake tokens in a new staking pool
/// @param stakeIndex The index of the original stake
/// @param restakePoolIndex The index of the new staking pool
/// @param restakeAmount The amount of tokens to restake
/// @return restake_ The details of the new stake
function restake(
uint256 stakeIndex,
uint256 restakePoolIndex,
uint256 restakeAmount
) external returns (Stake memory restake_);
}
contracts/libraries/UnsafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;
library UnsafeMath {
function unsafeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
return a + b;
}
}
function unsafeSub(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
return a - b;
}
}
function unsafeMul(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
return a * b;
}
}
function unsafeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
return a / b;
}
}
function unsafeDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
uint256 result = a / b;
return a % b > 0 ? result + 1 : result;
}
}
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.