Verified contractExactMIT
YieldPool
Address0xdda135a0d36455d96a873f174a415b55e2d04157
- Balance
0 ETH
- Transactions
7,308
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,244,945
- Creation transaction
- 0xfa262556d4…3504d5fadf
14 files
- project/contracts/yieldPool/YieldPool.solmain14.6 KB
- npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol4.45 KB
- npm/@openzeppelin/[email protected]/interfaces/IERC165.sol193 B
- npm/@openzeppelin/[email protected]/interfaces/IERC20.sol182 B
- npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol2.78 KB
- npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol13.31 KB
- npm/@openzeppelin/[email protected]/utils/ReentrancyGuard.sol4.77 KB
- npm/@openzeppelin/[email protected]/utils/StorageSlot.sol4.18 KB
- npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol871 B
- project/contracts/yieldPool/core/YieldPoolCore.sol23.9 KB
- project/contracts/yieldPool/core/YieldPoolStorage.sol5.71 KB
- project/contracts/yieldPool/lib/IUniswapV2.sol607 B
- project/contracts/yieldPool/lib/YieldPoolErrors.sol2.79 KB
- project/contracts/yieldPool/lib/YieldPoolEvents.sol2.67 KB
project/contracts/yieldPool/YieldPool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {YieldPoolCore} from "./core/YieldPoolCore.sol";
import {YieldPoolErrors} from "./lib/YieldPoolErrors.sol";
import {YieldPoolEvents} from "./lib/YieldPoolEvents.sol";
import {IUniswapV2Router02} from "./lib/IUniswapV2.sol";
/**
* @title YieldPool
* @notice Two-phase USDT-reward staking vault.
*
* Phase 1 — ARC staking
* ─────────────────────
* Users stake ARC tokens and earn USDT platform revenue pro-rata using the
* MasterChef accumulator model (accRewardPerShare over totalStaked ARC).
*
* Phase 2 — LP staking (activated once by the lpActivator role)
* ───────────────────────────────────────────────────────────────
* The lpActivator calls activateLpMode(lpToken) exactly once, providing the
* address of the pre-existing Uniswap V2 ARC/USDT LP token. After this:
* • New pure-ARC stakes are permanently disabled.
* • Existing ARC stakers stop earning new rewards (accRewardPerShare freezes)
* but retain all rewards earned up to the switch and may unstake / claim freely.
* • Users call addLiquidityAndStake(arcAmount, usdtAmount, …) to deposit both
* tokens; the contract adds them to the Uniswap V2 pool via the router, holds
* the resulting LP tokens, and tracks the ARC actually consumed as the reward
* weight for that position (same accumulator model, different denominator).
* • LP stakes must be held for a minimum of 7 days before they become eligible to
* earn epoch rewards. USDT notified before any stake is eligible is queued and
* flushed automatically into the first epoch that has eligible ARC.
* • cancelLpStake removes liquidity via the router and returns ARC + USDT to the
* user, along with any accrued USDT reward.
* • notifyReward now feeds the LP pool accumulator instead of the ARC pool.
*
* Architecture
* ────────────
* lib/YieldPoolErrors — custom errors
* lib/YieldPoolEvents — events
* lib/IUniswapV2 — minimal V2 router interface
* core/YieldPoolStorage — state layout + Stake / LpStake structs
* core/YieldPoolCore — all internal logic
* YieldPool — external entry points (this file)
*/
contract YieldPool is YieldPoolCore, ReentrancyGuard {
using SafeERC20 for IERC20;
// ─── Constructor ───────────────────────────────────────────────────────────
/**
* @param _arcToken ARC ERC-20 token address
* @param _usdtToken USDT ERC-20 token address
* @param _rewarder Address authorised to call notifyReward
* @param _lpActivator Address authorised to call activateLpMode (once)
* @param _uniswapRouter Uniswap V2 Router02 address
*/
constructor(
address _arcToken,
address _usdtToken,
address _rewarder,
address _lpActivator,
address _uniswapRouter
) {
if (
_arcToken == address(0) ||
_usdtToken == address(0) ||
_rewarder == address(0) ||
_lpActivator == address(0) ||
_uniswapRouter == address(0)
) revert YieldPoolErrors.ZeroAddress();
arcToken = IERC20(_arcToken);
usdtToken = IERC20(_usdtToken);
rewarder = _rewarder;
lpActivator = _lpActivator;
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
deployTime = block.timestamp;
nextStakeId = 1;
nextLpStakeId = 1;
}
// ══════════════════════════════════════════════════════════════════════════
// §1 Mode switch
// ══════════════════════════════════════════════════════════════════════════
/**
* @notice Permanently enables LP staking mode and disables new ARC stakes.
* @dev Can only be called once by the lpActivator.
* After this call notifyReward feeds the LP pool and addLiquidityAndStake
* becomes available. Existing ARC stakers can still unstake and claim.
* @param _lpToken Address of the Uniswap V2 ARC/USDT LP token
*/
function activateLpMode(address _lpToken) external {
if (msg.sender != lpActivator) revert YieldPoolErrors.NotLpActivator();
_activateLpMode(_lpToken);
}
// ══════════════════════════════════════════════════════════════════════════
// §2 ARC staking
// ══════════════════════════════════════════════════════════════════════════
/**
* @notice Opens a new ARC stake position.
* @dev Reverts once LP mode is active. Each call creates an independent
* position; stake again to add more ARC.
* @param amount ARC to lock (caller must have approved this contract)
*/
function stake(uint256 amount) external nonReentrant {
_stake(msg.sender, amount);
}
/**
* @notice Seeds Phase-1 ARC stakes on behalf of a list of users.
* @dev Only callable within 1 day of deployment and before LP mode is active.
* The caller funds the whole batch: the summed ARC is pulled from msg.sender
* (who must have approved this contract), while each position is owned by the
* matching `users` entry. Has no access control — see _batchStakeFor for the
* rationale and trade-off. The two arrays must have equal, non-zero length.
* @param users Addresses to credit with the new stake positions
* @param amounts ARC to stake for each user (parallel to `users`)
*/
function batchStakeFor(
address[] calldata users,
uint256[] calldata amounts
) external nonReentrant {
_batchStakeFor(users, amounts);
}
/**
* @notice Closes an ARC stake position and returns ARC + any accrued USDT reward.
* @param stakeId Position to close
*/
function unstake(uint256 stakeId) external nonReentrant {
_unstake(stakeId);
}
/**
* @notice Closes up to 20 ARC stake positions in a single transaction.
* @dev All stakeIds must belong to msg.sender and be active; the call reverts
* on the first invalid entry — no partial state is committed.
* If the consolidated USDT transfer fails, rewards are frozen and
* recoverable via claimFrozenRewards().
* @param stakeIds Array of stake IDs to close (max 20)
*/
function batchUnstake(uint256[] calldata stakeIds) external nonReentrant {
_batchUnstake(stakeIds);
}
/**
* @notice Claims accrued USDT reward for a single ARC stake.
* @param stakeId Stake to claim from
*/
function claim(uint256 stakeId) external nonReentrant {
_claim(stakeId);
}
/**
* @notice Claims accrued USDT reward for multiple ARC stakes in one transaction.
* @param stakeIds Stake IDs to collect from (all must be active and owned by caller)
*/
function batchClaim(uint256[] calldata stakeIds) external nonReentrant {
_batchClaim(stakeIds);
}
/**
* @notice Claims USDT rewards that were frozen during a previous unstake
* because the USDT token was paused or had blacklisted this contract.
*/
function claimFrozenRewards() external nonReentrant {
uint256 amount = frozenRewards[msg.sender];
if (amount == 0) revert YieldPoolErrors.NoFrozenRewards();
frozenRewards[msg.sender] = 0;
usdtToken.safeTransfer(msg.sender, amount);
}
// ══════════════════════════════════════════════════════════════════════════
// §3 LP staking
// ══════════════════════════════════════════════════════════════════════════
/**
* @notice Deposits ARC + USDT as Uniswap V2 liquidity and opens an LP stake.
* @dev Only available after activateLpMode is called.
* The contract adds liquidity via the router and holds the LP tokens.
* Reward weight = ARC actually consumed by Uniswap (not the LP token count).
* Any tokens not used by Uniswap due to ratio rounding are refunded.
* The stake must be held for at least 7 days before it becomes eligible to
* earn USDT epoch rewards; claimLpReward reverts before that window passes.
* @param arcAmount ARC to deposit (caller must have approved this contract)
* @param usdtAmount USDT to deposit (caller must have approved this contract)
* @param arcAmountMin Minimum ARC Uniswap must consume (slippage guard)
* @param usdtAmountMin Minimum USDT Uniswap must consume (slippage guard)
*/
function addLiquidityAndStake(
uint256 arcAmount,
uint256 usdtAmount,
uint256 arcAmountMin,
uint256 usdtAmountMin
) external nonReentrant {
_addLiquidityAndStake(
msg.sender,
arcAmount,
usdtAmount,
arcAmountMin,
usdtAmountMin
);
}
/**
* @notice Claims accrued USDT reward for an active LP stake.
* @dev Reverts with StakeNotYetEligible if the 7-day minimum hold period has
* not elapsed since the stake was opened.
* @param lpStakeId LP stake to claim from
*/
function claimLpReward(uint256 lpStakeId) external nonReentrant {
_claimLpReward(lpStakeId);
}
/**
* @notice Claims accrued USDT reward for multiple LP stakes in one transaction.
* @dev All lpStakeIds must belong to msg.sender and be active. All must have
* passed their 7-day eligibility window; the call reverts on the first
* ineligible entry. A single USDT transfer covers all collected rewards.
* @param lpStakeIds LP stake IDs to collect from (max 20)
*/
function batchClaimLpReward(
uint256[] calldata lpStakeIds
) external nonReentrant {
_batchClaimLpReward(lpStakeIds);
}
/**
* @notice Cancels an LP stake: removes Uniswap V2 liquidity and returns
* ARC + USDT to the caller. Any accrued USDT reward is paid out
* in the same transaction.
* @param lpStakeId LP stake to cancel
* @param arcAmountMin Minimum ARC to receive when removing liquidity (slippage guard)
* @param usdtAmountMin Minimum USDT to receive when removing liquidity (slippage guard)
*/
function cancelLpStake(
uint256 lpStakeId,
uint256 arcAmountMin,
uint256 usdtAmountMin
) external nonReentrant {
_cancelLpStake(lpStakeId, arcAmountMin, usdtAmountMin);
}
/**
* @notice Cancels multiple LP stakes in a single transaction.
* @dev All lpStakeIds must belong to msg.sender and be active.
* Liquidity is removed per-stake via the router (ARC + USDT sent directly to
* caller each time); all accrued USDT rewards are consolidated into a single
* transfer at the end. The three arrays must have equal length.
* @param lpStakeIds LP stake IDs to cancel (max 20)
* @param arcAmountMins Per-stake minimum ARC to receive when removing liquidity
* @param usdtAmountMins Per-stake minimum USDT to receive when removing liquidity
*/
function batchCancelLpStake(
uint256[] calldata lpStakeIds,
uint256[] calldata arcAmountMins,
uint256[] calldata usdtAmountMins
) external nonReentrant {
_batchCancelLpStake(lpStakeIds, arcAmountMins, usdtAmountMins);
}
// ══════════════════════════════════════════════════════════════════════════
// §4 Reward injection
// ══════════════════════════════════════════════════════════════════════════
/**
* @notice Deposits USDT platform revenue for distribution to stakers.
* @dev In ARC mode feeds the ARC accumulator; in LP mode feeds the LP accumulator.
* Caller must have approved this contract for `amount` USDT.
* @param amount USDT to distribute
*/
function notifyReward(uint256 amount) external nonReentrant {
if (msg.sender != rewarder) revert YieldPoolErrors.NotRewarder();
_notifyReward(amount);
}
// ══════════════════════════════════════════════════════════════════════════
// §5 View functions
// ══════════════════════════════════════════════════════════════════════════
/// @notice USDT reward currently claimable for an ARC stake.
function pendingReward(uint256 stakeId) external view returns (uint256) {
return _pendingArcReward(stakeId);
}
/// @notice USDT reward currently accrued for an LP stake.
function pendingLpReward(uint256 lpStakeId) external view returns (uint256) {
return _pendingLpReward(lpStakeId);
}
/// @notice All ARC stake IDs ever opened by `user` (including closed ones).
function getUserStakeIds(
address user
) external view returns (uint256[] memory) {
return _userStakeIds[user];
}
/// @notice All LP stake IDs ever opened by `user` (including cancelled ones).
function getUserLpStakeIds(
address user
) external view returns (uint256[] memory) {
return _userLpStakeIds[user];
}
}
npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
npm/@openzeppelin/[email protected]/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
npm/@openzeppelin/[email protected]/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
npm/@openzeppelin/[email protected]/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @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 EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* 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].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// 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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = 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();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
npm/@openzeppelin/[email protected]/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
project/contracts/yieldPool/core/YieldPoolCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {YieldPoolStorage} from "./YieldPoolStorage.sol";
import {YieldPoolErrors} from "../lib/YieldPoolErrors.sol";
import {YieldPoolEvents} from "../lib/YieldPoolEvents.sol";
abstract contract YieldPoolCore is YieldPoolStorage {
using SafeERC20 for IERC20;
// ══════════════════════════════════════════════════════════════════════════
// §A Mode switch
// ══════════════════════════════════════════════════════════════════════════
function _activateLpMode(address _lpToken) internal {
if (lpModeActive) revert YieldPoolErrors.LpModeAlreadyActive();
if (
_lpToken == address(0) ||
_lpToken == address(arcToken) ||
_lpToken == address(usdtToken)
) {
revert YieldPoolErrors.InvalidLpToken();
}
lpModeActive = true;
lpToken = _lpToken;
// Anchor the eligibility sweep to today so _processEligibility never
// iterates over days that predate LP mode.
lastProcessedDay = block.timestamp / 1 days;
emit YieldPoolEvents.LpModeActivated(_lpToken);
}
// ══════════════════════════════════════════════════════════════════════════
// §B ARC staking (Phase 1)
// ══════════════════════════════════════════════════════════════════════════
function _stake(address user, uint256 amount) internal {
if (amount == 0) revert YieldPoolErrors.ZeroAmount();
if (lpModeActive) revert YieldPoolErrors.ArcStakingDisabled();
totalStaked += amount;
uint256 stakeId = nextStakeId++;
stakes[stakeId] = Stake({
amount: amount,
rewardDebt: (amount * accRewardPerShare) / PRECISION,
owner: user,
active: true
});
_userStakeIds[user].push(stakeId);
arcToken.safeTransferFrom(msg.sender, address(this), amount);
emit YieldPoolEvents.Staked(user, stakeId, amount);
}
/// @dev Seeds Phase-1 ARC stakes on behalf of many users in one transaction.
/// The caller (msg.sender) funds the entire batch — the summed ARC is pulled
/// from the caller, while each position is credited to the corresponding user.
/// Only callable within BATCH_STAKE_WINDOW of deployment and before LP mode.
///
/// No access control by design: msg.sender can only ever spend its OWN ARC,
/// so no third party or contract balance can be drained. The trade-off is that
/// anyone can create dust positions owned by an arbitrary address, bloating that
/// address's _userStakeIds list; the deploy-time window bounds this exposure.
function _batchStakeFor(
address[] calldata users,
uint256[] calldata amounts
) internal {
if (block.timestamp > deployTime + BATCH_STAKE_WINDOW)
revert YieldPoolErrors.StakeForWindowClosed();
if (lpModeActive) revert YieldPoolErrors.ArcStakingDisabled();
uint256 len = users.length;
if (len == 0) revert YieldPoolErrors.EmptyArray();
if (amounts.length != len) revert YieldPoolErrors.ArrayLengthMismatch();
uint256 acc = accRewardPerShare; // cached; nonReentrant prevents updates mid-call
uint256 totalAmount;
for (uint256 i; i < len; ) {
address user = users[i];
uint256 amount = amounts[i];
if (user == address(0)) revert YieldPoolErrors.ZeroAddress();
if (amount == 0) revert YieldPoolErrors.ZeroAmount();
uint256 stakeId = nextStakeId++;
stakes[stakeId] = Stake({
amount: amount,
rewardDebt: (amount * acc) / PRECISION,
owner: user,
active: true
});
_userStakeIds[user].push(stakeId);
totalAmount += amount;
emit YieldPoolEvents.Staked(user, stakeId, amount);
unchecked {
++i;
}
}
// Effects before interaction (CEI): single transfer for the whole batch.
totalStaked += totalAmount;
arcToken.safeTransferFrom(msg.sender, address(this), totalAmount);
}
function _unstake(uint256 stakeId) internal {
Stake storage s = stakes[stakeId];
if (!s.active) revert YieldPoolErrors.StakeNotActive();
if (s.owner != msg.sender) revert YieldPoolErrors.NotStakeOwner();
uint256 amount = s.amount;
uint256 reward = _computeArcPending(s);
// CEI: effects before interactions.
s.active = false;
s.amount = 0;
s.rewardDebt = 0;
totalStaked -= amount;
arcToken.safeTransfer(msg.sender, amount);
emit YieldPoolEvents.Unstaked(msg.sender, stakeId, amount);
if (reward > 0) {
try usdtToken.transfer(msg.sender, reward) returns (bool ok) {
if (ok) {
emit YieldPoolEvents.Claimed(msg.sender, stakeId, reward);
} else {
frozenRewards[msg.sender] += reward;
emit YieldPoolEvents.RewardFrozen(msg.sender, stakeId, reward);
}
} catch {
frozenRewards[msg.sender] += reward;
emit YieldPoolEvents.RewardFrozen(msg.sender, stakeId, reward);
}
}
}
function _claim(uint256 stakeId) internal {
uint256 reward = _settleArcReward(stakeId);
if (reward == 0) revert YieldPoolErrors.NoRewardToClaim();
usdtToken.safeTransfer(msg.sender, reward);
}
/// @dev Advances the reward checkpoint for `stakeId` and returns the claimable amount.
/// Does NOT transfer — callers that batch must consolidate the transfer.
function _settleArcReward(uint256 stakeId) internal returns (uint256 reward) {
Stake storage s = stakes[stakeId];
if (!s.active) revert YieldPoolErrors.StakeNotActive();
if (s.owner != msg.sender) revert YieldPoolErrors.NotStakeOwner();
reward = _computeArcPending(s);
if (reward > 0) {
s.rewardDebt = (s.amount * accRewardPerShare) / PRECISION;
emit YieldPoolEvents.Claimed(msg.sender, stakeId, reward);
}
}
/// @dev Closes up to 20 ARC stakes in one transaction. ARC is returned in a
/// single transfer; USDT rewards are consolidated and paid together (or frozen
/// atomically if the transfer fails).
function _batchUnstake(uint256[] calldata stakeIds) internal {
uint256 len = stakeIds.length;
if (len == 0) revert YieldPoolErrors.EmptyStakeIds();
if (len > 20) revert YieldPoolErrors.BatchTooLarge();
uint256 totalArc;
uint256 totalReward;
uint256[] memory rewards = new uint256[](len);
uint256 acc = accRewardPerShare; // cached; nonReentrant prevents updates mid-call
for (uint256 i; i < len; ) {
uint256 sid = stakeIds[i];
Stake storage s = stakes[sid];
if (!s.active) revert YieldPoolErrors.StakeNotActive();
if (s.owner != msg.sender) revert YieldPoolErrors.NotStakeOwner();
uint256 amount = s.amount;
uint256 reward = (amount * acc) / PRECISION - s.rewardDebt;
s.active = false;
s.amount = 0;
s.rewardDebt = 0;
totalArc += amount;
rewards[i] = reward;
totalReward += reward;
emit YieldPoolEvents.Unstaked(msg.sender, sid, amount);
unchecked {
++i;
}
}
totalStaked -= totalArc;
arcToken.safeTransfer(msg.sender, totalArc);
if (totalReward > 0) {
bool transferred;
try usdtToken.transfer(msg.sender, totalReward) returns (bool ok) {
transferred = ok;
} catch {}
for (uint256 i; i < len; ) {
uint256 r = rewards[i];
if (r != 0) {
if (transferred) {
emit YieldPoolEvents.Claimed(msg.sender, stakeIds[i], r);
} else {
emit YieldPoolEvents.RewardFrozen(msg.sender, stakeIds[i], r);
}
}
unchecked {
++i;
}
}
if (!transferred) frozenRewards[msg.sender] += totalReward;
}
}
/// @dev Claims rewards for multiple ARC stakes in one transaction.
/// Reward checkpoints are advanced per-stake; a single USDT transfer covers all.
function _batchClaim(uint256[] calldata stakeIds) internal {
uint256 len = stakeIds.length;
if (len == 0) revert YieldPoolErrors.EmptyStakeIds();
uint256 totalReward;
for (uint256 i; i < len; ++i) {
totalReward += _settleArcReward(stakeIds[i]);
}
if (totalReward == 0) revert YieldPoolErrors.NoRewardToClaim();
usdtToken.safeTransfer(msg.sender, totalReward);
}
function _pendingArcReward(uint256 stakeId) internal view returns (uint256) {
Stake storage s = stakes[stakeId];
if (!s.active || s.amount == 0) return 0;
return _computeArcPending(s);
}
function _computeArcPending(Stake storage s) internal view returns (uint256) {
return (s.amount * accRewardPerShare) / PRECISION - s.rewardDebt;
}
// ══════════════════════════════════════════════════════════════════════════
// §C LP staking (Phase 2) — 7-day minimum eligibility
// ══════════════════════════════════════════════════════════════════════════
/// @dev Sweeps calendar days from lastProcessedDay+1 through today, moving any
/// ARC that has matured into the eligible pool and snapshotting the accumulator
/// so newly-enrolled stakes start from the correct baseline.
///
/// Iteration bound: days elapsed since the last call. Because notifyReward is
/// expected to be called at least weekly this is typically ≤7 iterations.
/// The fast path exits in O(1) when no ARC is pending
/// (totalLpArcContributed == totalEligibleArc).
function _processEligibility() internal {
uint256 today = block.timestamp / 1 days;
if (today <= lastProcessedDay) return;
// Fast path: nothing is pending, skip the day loop.
if (totalLpArcContributed == totalEligibleArc) {
lastProcessedDay = today;
return;
}
// Snapshot once — accEligibleRewardPerArc hasn't advanced since last call
// (no epoch runs before this sweep), so every newly-eligible stake gets the
// same baseline regardless of which specific day it fell on.
uint256 snapshot = accEligibleRewardPerArc;
for (uint256 day = lastProcessedDay + 1; day <= today; ) {
uint256 arc = eligibilityByDay[day];
if (arc > 0) {
accEligibilitySnapshot[day] = snapshot;
totalEligibleArc += arc;
// All pending ARC is now enrolled; remaining days are provably empty.
if (totalEligibleArc == totalLpArcContributed) {
break;
}
}
unchecked {
++day;
}
}
lastProcessedDay = today;
}
/// @dev Lazily marks a stake as enrolled and sets its MasterChef rewardDebt to
/// the accumulator value captured when its eligibleDay was swept. After this,
/// pending reward is the standard O(1) MasterChef formula.
/// Caller must have already called _processEligibility() and confirmed
/// lastProcessedDay >= s.eligibleDay.
function _enrollIfNeeded(LpStake storage s) internal {
if (!s.enrolled) {
s.rewardDebt =
(s.arcContributed * accEligibilitySnapshot[s.eligibleDay]) / PRECISION;
s.enrolled = true;
}
}
function _addLiquidityAndStake(
address user,
uint256 arcAmount,
uint256 usdtAmount,
uint256 arcAmountMin,
uint256 usdtAmountMin
) internal {
if (!lpModeActive) revert YieldPoolErrors.LpModeNotActive();
if (arcAmount == 0 || usdtAmount == 0) revert YieldPoolErrors.ZeroAmount();
// Pull tokens from the caller.
arcToken.safeTransferFrom(msg.sender, address(this), arcAmount);
usdtToken.safeTransferFrom(msg.sender, address(this), usdtAmount);
// Grant the router exactly the amounts it may consume.
arcToken.forceApprove(address(uniswapRouter), arcAmount);
usdtToken.forceApprove(address(uniswapRouter), usdtAmount);
// Add liquidity; LP tokens land directly in this contract.
(uint256 arcUsed, uint256 usdtUsed, uint256 lpAmount) = uniswapRouter
.addLiquidity(
address(arcToken),
address(usdtToken),
arcAmount,
usdtAmount,
arcAmountMin,
usdtAmountMin,
address(this),
block.timestamp + 300
);
// Revoke any remaining router allowance and refund unused tokens.
arcToken.forceApprove(address(uniswapRouter), 0);
usdtToken.forceApprove(address(uniswapRouter), 0);
if (arcAmount > arcUsed)
arcToken.safeTransfer(msg.sender, arcAmount - arcUsed);
if (usdtAmount > usdtUsed)
usdtToken.safeTransfer(msg.sender, usdtAmount - usdtUsed);
// eligibleDay = floor((now + MIN_LP_STAKE_DURATION) / 1 day):
// the first calendar day on which this stake's ARC counts toward epochs.
uint256 eligibleDay = (block.timestamp + MIN_LP_STAKE_DURATION) / 1 days;
totalLpArcContributed += arcUsed;
eligibilityByDay[eligibleDay] += arcUsed;
uint256 lpStakeId = nextLpStakeId++;
lpStakes[lpStakeId] = LpStake({
lpAmount: lpAmount,
arcContributed: arcUsed,
rewardDebt: 0, // meaningless until enrolled
eligibleDay: eligibleDay,
owner: user,
active: true,
enrolled: false
});
_userLpStakeIds[user].push(lpStakeId);
emit YieldPoolEvents.LpStaked(user, lpStakeId, lpAmount, arcUsed, usdtUsed);
}
/// @dev Advances the reward checkpoint for `lpStakeId` and returns the claimable amount.
/// Caller must have already called _processEligibility().
/// Does NOT transfer — callers that batch must consolidate the transfer.
function _settleLpReward(
uint256 lpStakeId
) internal returns (uint256 reward) {
LpStake storage s = lpStakes[lpStakeId];
if (!s.active) revert YieldPoolErrors.LpStakeNotActive();
if (s.owner != msg.sender) revert YieldPoolErrors.NotLpStakeOwner();
if (lastProcessedDay < s.eligibleDay)
revert YieldPoolErrors.StakeNotYetEligible();
_enrollIfNeeded(s);
reward =
(s.arcContributed * accEligibleRewardPerArc) / PRECISION -
s.rewardDebt;
if (reward > 0) {
// CEI: advance checkpoint before transfer.
s.rewardDebt = (s.arcContributed * accEligibleRewardPerArc) / PRECISION;
emit YieldPoolEvents.LpRewardClaimed(msg.sender, lpStakeId, reward);
}
}
function _claimLpReward(uint256 lpStakeId) internal {
_processEligibility();
uint256 reward = _settleLpReward(lpStakeId);
if (reward == 0) revert YieldPoolErrors.NoRewardToClaim();
usdtToken.safeTransfer(msg.sender, reward);
}
/// @dev Claims rewards for multiple LP stakes in one transaction.
/// _processEligibility runs once; reward checkpoints advanced per-stake;
/// a single USDT transfer covers all.
function _batchClaimLpReward(uint256[] calldata lpStakeIds) internal {
uint256 len = lpStakeIds.length;
if (len == 0) revert YieldPoolErrors.EmptyStakeIds();
if (len > 20) revert YieldPoolErrors.BatchTooLarge();
_processEligibility();
uint256 totalReward;
for (uint256 i; i < len; ++i) {
totalReward += _settleLpReward(lpStakeIds[i]);
}
if (totalReward == 0) revert YieldPoolErrors.NoRewardToClaim();
usdtToken.safeTransfer(msg.sender, totalReward);
}
/// @dev Core cancel work for a single LP stake.
/// Caller must have already called _processEligibility().
/// Removes liquidity via the router (ARC + USDT go directly to msg.sender),
/// clears state, and returns the accrued reward without transferring it —
/// callers are responsible for the USDT transfer so batches can consolidate.
///
/// Eligibility accounting:
/// • Before eligible — ARC lives in eligibilityByDay[eligibleDay]; remove it there.
/// • After eligible — ARC lives in totalEligibleArc; remove it there.
function _executeCancelLpStake(
uint256 lpStakeId,
uint256 arcAmountMin,
uint256 usdtAmountMin
) internal returns (uint256 reward) {
LpStake storage s = lpStakes[lpStakeId];
if (!s.active) revert YieldPoolErrors.LpStakeNotActive();
if (s.owner != msg.sender) revert YieldPoolErrors.NotLpStakeOwner();
uint256 lpAmount = s.lpAmount;
uint256 arcContributed = s.arcContributed;
uint256 eligibleDay = s.eligibleDay;
bool eligible = lastProcessedDay >= eligibleDay;
if (eligible) {
_enrollIfNeeded(s);
reward =
(s.arcContributed * accEligibleRewardPerArc) / PRECISION -
s.rewardDebt;
}
// Effects — clear stake state first (CEI).
s.active = false;
s.lpAmount = 0;
s.arcContributed = 0;
s.rewardDebt = 0;
totalLpArcContributed -= arcContributed;
if (eligible) {
totalEligibleArc -= arcContributed;
} else {
eligibilityByDay[eligibleDay] -= arcContributed;
}
// Interaction — router removes liquidity and sends tokens directly to caller.
IERC20(lpToken).forceApprove(address(uniswapRouter), lpAmount);
(uint256 arcOut, uint256 usdtOut) = uniswapRouter.removeLiquidity(
address(arcToken),
address(usdtToken),
lpAmount,
arcAmountMin,
usdtAmountMin,
msg.sender,
block.timestamp + 300
);
IERC20(lpToken).forceApprove(address(uniswapRouter), 0);
emit YieldPoolEvents.LpUnstaked(msg.sender, lpStakeId, arcOut, usdtOut);
// NOTE: LpRewardClaimed / RewardFrozen is emitted by the caller after
// it knows whether the USDT transfer succeeded or was frozen.
}
/// @dev Cancels a single LP stake.
/// _processEligibility runs first to keep rewards up-to-date.
/// If USDT is paused or blacklisted the reward is frozen in frozenRewards
/// so the user can reclaim it later via claimFrozenRewards(); the LP
/// liquidity is always returned regardless of USDT state.
function _cancelLpStake(
uint256 lpStakeId,
uint256 arcAmountMin,
uint256 usdtAmountMin
) internal {
_processEligibility();
uint256 reward = _executeCancelLpStake(
lpStakeId,
arcAmountMin,
usdtAmountMin
);
if (reward > 0) {
try usdtToken.transfer(msg.sender, reward) returns (bool ok) {
if (ok) {
emit YieldPoolEvents.LpRewardClaimed(msg.sender, lpStakeId, reward);
} else {
frozenRewards[msg.sender] += reward;
emit YieldPoolEvents.RewardFrozen(msg.sender, lpStakeId, reward);
}
} catch {
frozenRewards[msg.sender] += reward;
emit YieldPoolEvents.RewardFrozen(msg.sender, lpStakeId, reward);
}
}
}
/// @dev Cancels up to 20 LP stakes in one transaction. _processEligibility runs
/// once; each cancel is delegated to _executeCancelLpStake (keeping per-iteration
/// stack depth low); all accrued USDT rewards are consolidated into a single
/// safeTransfer at the end.
function _batchCancelLpStake(
uint256[] calldata lpStakeIds,
uint256[] calldata arcAmountMins,
uint256[] calldata usdtAmountMins
) internal {
uint256 len = lpStakeIds.length;
if (len == 0) revert YieldPoolErrors.EmptyStakeIds();
if (len > 20) revert YieldPoolErrors.BatchTooLarge();
if (arcAmountMins.length != len || usdtAmountMins.length != len) {
revert YieldPoolErrors.ArrayLengthMismatch();
}
_processEligibility();
uint256 totalReward;
for (uint256 i; i < len; ) {
uint256 lpStakeId = lpStakeIds[i];
uint256 reward = _executeCancelLpStake(
lpStakeId,
arcAmountMins[i],
usdtAmountMins[i]
);
if (reward > 0) {
totalReward += reward;
emit YieldPoolEvents.LpRewardClaimed(msg.sender, lpStakeId, reward);
}
unchecked {
++i;
}
}
// safeTransfer reverts the entire tx on failure, which also rolls back all
// LpRewardClaimed events emitted above — so events only survive on success.
if (totalReward > 0) usdtToken.safeTransfer(msg.sender, totalReward);
}
function _pendingLpReward(uint256 lpStakeId) internal view returns (uint256) {
LpStake storage s = lpStakes[lpStakeId];
if (!s.active || s.arcContributed == 0) return 0;
return _computeLpPending(s);
}
/// @dev O(1) pending calculation.
/// Returns 0 if the stake's eligibleDay has not yet been swept (which implies
/// no epochs have been created for it — correct because _processEligibility always
/// runs before any epoch is written).
/// After sweeping, uses the snapshot to give the stake a zero baseline for all
/// epochs that pre-date its eligibility, then applies the standard MasterChef formula.
function _computeLpPending(
LpStake storage s
) internal view returns (uint256) {
if (lastProcessedDay < s.eligibleDay) return 0;
uint256 baseDebt =
s.enrolled
? s.rewardDebt
: (s.arcContributed * accEligibilitySnapshot[s.eligibleDay]) /
PRECISION;
return (s.arcContributed * accEligibleRewardPerArc) / PRECISION - baseDebt;
}
// ══════════════════════════════════════════════════════════════════════════
// §D Reward injection (mode-aware)
// ══════════════════════════════════════════════════════════════════════════
function _notifyReward(uint256 amount) internal {
if (amount == 0) revert YieldPoolErrors.ZeroAmount();
usdtToken.safeTransferFrom(msg.sender, address(this), amount);
if (!lpModeActive) {
// ── ARC pool ──────────────────────────────────────────────────
if (totalStaked == 0) {
queuedRewards += amount;
} else {
uint256 toDistribute = amount;
if (queuedRewards > 0) {
toDistribute += queuedRewards;
emit YieldPoolEvents.QueuedRewardFlushed(queuedRewards);
queuedRewards = 0;
}
accRewardPerShare += (toDistribute * PRECISION) / totalStaked;
}
} else {
// ── LP pool ───────────────────────────────────────────────────
// Advance eligibility before creating the epoch so that any ARC
// that matured today is included in the denominator.
_processEligibility();
if (totalEligibleArc == 0) {
queuedLpRewards += amount;
} else {
uint256 toDistribute = amount;
if (queuedLpRewards > 0) {
toDistribute += queuedLpRewards;
emit YieldPoolEvents.QueuedRewardFlushed(queuedLpRewards);
queuedLpRewards = 0;
}
accEligibleRewardPerArc +=
(toDistribute * PRECISION) / totalEligibleArc;
}
}
emit YieldPoolEvents.RewardNotified(msg.sender, amount);
}
}
project/contracts/yieldPool/core/YieldPoolStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IUniswapV2Router02} from "../lib/IUniswapV2.sol";
abstract contract YieldPoolStorage {
// ─── Structs ───────────────────────────────────────────────────────────────
struct Stake {
uint256 amount;
uint256 rewardDebt; // snapshot of accRewardPerShare; prevents double-claiming
address owner;
bool active;
}
struct LpStake {
uint256 lpAmount; // LP tokens held by this contract for this position
uint256 arcContributed; // ARC actually consumed by Uniswap — the reward weight
uint256 rewardDebt; // MasterChef debt against accEligibleRewardPerArc (valid after enrollment)
uint256 eligibleDay; // first calendar day (floor(ts/1day)) this stake may earn epoch rewards
address owner;
bool active;
bool enrolled; // true once eligibleDay has been swept by _processEligibility
}
// ─── Constants ─────────────────────────────────────────────────────────────
/// @dev 1e24: 24 digits of sub-unit precision avoiding integer-division dust
uint256 internal constant PRECISION = 1e24;
/// @dev Minimum time a stake must be held before it earns LP epoch rewards.
uint256 internal constant MIN_LP_STAKE_DURATION = 7 days;
/// @dev Window after deployment during which batchStakeFor may seed Phase-1 stakes.
uint256 internal constant BATCH_STAKE_WINDOW = 1 days;
// ─── Tokens ────────────────────────────────────────────────────────────────
IERC20 public arcToken;
IERC20 public usdtToken;
/// @notice Timestamp the contract was deployed; upper-bounds the batchStakeFor window.
uint256 public immutable deployTime;
// ─── Access ────────────────────────────────────────────────────────────────
/// @notice Authorised to call notifyReward (treasury / multisig)
address public rewarder;
/// @notice Authorised to call activateLpMode exactly once
address public lpActivator;
// ─── Mode flag ─────────────────────────────────────────────────────────────
/// @notice false = ARC-only staking; true = LP staking (set permanently by activateLpMode)
bool public lpModeActive;
// ─── LP infrastructure ─────────────────────────────────────────────────────
IUniswapV2Router02 public uniswapRouter;
/// @notice ARC/USDT Uniswap V2 LP token; set permanently by activateLpMode
address public lpToken;
// ══════════════════════════════════════════════════════════════════════════
// ARC staking pool
// ══════════════════════════════════════════════════════════════════════════
uint256 public totalStaked;
uint256 public accRewardPerShare;
uint256 public queuedRewards;
uint256 public nextStakeId;
mapping(uint256 => Stake) public stakes;
mapping(address => uint256[]) internal _userStakeIds;
mapping(address => uint256) public frozenRewards;
// ══════════════════════════════════════════════════════════════════════════
// LP staking pool — epoch-eligible MasterChef accumulator
// ══════════════════════════════════════════════════════════════════════════
/// @notice Total ARC across all active LP stakes (eligible + pending).
uint256 public totalLpArcContributed;
/// @notice ARC from stakes whose eligibleDay has been processed; denominator for epochs.
uint256 public totalEligibleArc;
/// @notice MasterChef accumulator that advances only when epochs are created.
uint256 public accEligibleRewardPerArc;
/// @notice USDT queued while totalEligibleArc == 0; flushed into the next epoch.
uint256 public queuedLpRewards;
/// @dev ARC amount keyed by the calendar day it transitions from pending to eligible.
/// eligibilityByDay[day] += arcUsed on stake; -= arcUsed on cancel-before-eligible.
mapping(uint256 => uint256) public eligibilityByDay;
/// @dev Snapshot of accEligibleRewardPerArc at the moment each calendar day was first swept.
/// Serves as the zero-earning baseline for stakes whose eligibleDay == that day.
mapping(uint256 => uint256) public accEligibilitySnapshot;
/// @dev Last calendar day (floor(timestamp/1day)) swept by _processEligibility.
uint256 public lastProcessedDay;
uint256 public nextLpStakeId;
mapping(uint256 => LpStake) public lpStakes;
mapping(address => uint256[]) internal _userLpStakeIds;
}
project/contracts/yieldPool/lib/IUniswapV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IUniswapV2Router02 {
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
}
project/contracts/yieldPool/lib/YieldPoolErrors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
library YieldPoolErrors {
// ─── Shared ────────────────────────────────────────────────────────────────
/// @dev amount argument must be greater than zero
error ZeroAmount();
/// @dev address argument must not be the zero address
error ZeroAddress();
/// @dev there is no accrued reward to claim
error NoRewardToClaim();
/// @dev caller is not the designated rewarder address
error NotRewarder();
/// @dev caller has no frozen rewards to claim
error NoFrozenRewards();
/// @dev batchClaim / batchUnstake was called with an empty array
error EmptyStakeIds();
/// @dev a batch function was called with an empty array
error EmptyArray();
/// @dev batchUnstake / batchCancelLpStake was called with more than the allowed number of ids
error BatchTooLarge();
/// @dev parallel arrays passed to a batch function must have the same length
error ArrayLengthMismatch();
// ─── ARC staking ───────────────────────────────────────────────────────────
/// @dev the stake has already been unstaked or never existed
error StakeNotActive();
/// @dev caller is not the owner of the given stake
error NotStakeOwner();
/// @dev LP mode is active; new pure-ARC stakes are no longer accepted
error ArcStakingDisabled();
/// @dev the post-deploy window for batchStakeFor seeding has elapsed
error StakeForWindowClosed();
// ─── Mode switch ───────────────────────────────────────────────────────────
/// @dev caller is not the lpActivator
error NotLpActivator();
/// @dev activateLpMode has already been called; it can only be called once
error LpModeAlreadyActive();
/// @dev the provided LP token address is invalid
error InvalidLpToken();
// ─── LP staking ────────────────────────────────────────────────────────────
/// @dev LP mode is not yet active; addLiquidityAndStake / claimLpReward / cancelLpStake are disabled
error LpModeNotActive();
/// @dev the LP stake has already been cancelled or never existed
error LpStakeNotActive();
/// @dev caller is not the owner of the given LP stake
error NotLpStakeOwner();
/// @dev the LP stake has not yet satisfied the minimum staking duration for rewards
error StakeNotYetEligible();
}
project/contracts/yieldPool/lib/YieldPoolEvents.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
library YieldPoolEvents {
// ─── ARC staking ───────────────────────────────────────────────────────────
/// @dev emitted when a user opens a new ARC stake position
event Staked(address indexed user, uint256 indexed stakeId, uint256 amount);
/// @dev emitted when a user closes an ARC stake position (ARC returned)
event Unstaked(address indexed user, uint256 indexed stakeId, uint256 amount);
/// @dev emitted whenever USDT rewards are transferred to an ARC staker
event Claimed(address indexed user, uint256 indexed stakeId, uint256 reward);
/// @dev emitted when a USDT reward transfer fails on unstake (token paused / blacklisted);
/// the amount is tracked in frozenRewards and claimable once USDT is operational
event RewardFrozen(
address indexed user,
uint256 indexed stakeId,
uint256 amount
);
// ─── Mode switch ───────────────────────────────────────────────────────────
/// @dev emitted when the lpActivator enables LP-only staking mode
event LpModeActivated(address indexed lpToken);
// ─── Shared reward injection ────────────────────────────────────────────────
/// @dev emitted when the rewarder deposits USDT into the active pool
event RewardNotified(address indexed notifier, uint256 amount);
/// @dev emitted when queued rewards (deposited while no stakers existed) are flushed
event QueuedRewardFlushed(uint256 amount);
// ─── LP staking ────────────────────────────────────────────────────────────
/// @dev emitted when a user provides ARC+USDT liquidity and opens an LP stake
event LpStaked(
address indexed user,
uint256 indexed lpStakeId,
uint256 lpAmount,
uint256 arcContributed,
uint256 usdtContributed
);
/// @dev emitted when an LP stake is cancelled and underlying tokens are returned
event LpUnstaked(
address indexed user,
uint256 indexed lpStakeId,
uint256 arcReturned,
uint256 usdtReturned
);
/// @dev emitted when USDT reward is paid to an LP staker (on claim or cancel)
event LpRewardClaimed(
address indexed user,
uint256 indexed lpStakeId,
uint256 reward
);
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.