Verified contractExactMIT
StableYieldAccumulator
Address0xb9639e6be92033f55e6d9e375fd1c28ceedba50e
- Balance
0 ETH
- Transactions
48
- Compiler
solc 0.8.30
- Same code
1 more contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 10,000 runs
- EVM version
- prague
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,694,966
- Creation transaction
- 0x9205b2aa5d…898aa4557a
20 files
- lib/stable-yield-accumulator/src/StableYieldAccumulator.solmain26.95 KB
- lib/pauser/src/interfaces/IPausable.sol1.41 KB
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol4.75 KB
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13.31 KB
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/utils/Pausable.sol2.71 KB
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol4.77 KB
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/phlimbo-ea/src/IFlax.sol644 B
- lib/phlimbo-ea/src/interfaces/IPhlimbo.sol5.59 KB
- lib/stable-yield-accumulator/lib/mutable/yield-claim-nft/src/interfaces/INFTMinter.sol3.45 KB
- lib/stable-yield-accumulator/lib/mutable/yield-claim-nft/src/interfaces/ITokenMinter.sol2.51 KB
- lib/stable-yield-accumulator/src/interfaces/IStableYieldAccumulator.sol11.92 KB
- lib/vault/src/interfaces/IYieldStrategy.sol4.5 KB
lib/stable-yield-accumulator/src/StableYieldAccumulator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "pauser/interfaces/IPausable.sol";
import "./interfaces/IStableYieldAccumulator.sol";
import "vault/interfaces/IYieldStrategy.sol";
import "phlimbo-ea/interfaces/IPhlimbo.sol";
import "yield-claim-nft/interfaces/INFTMinter.sol";
/**
* @title StableYieldAccumulator
* @notice Consolidates yield strategy rewards into a single stablecoin for simplified distribution
* @dev Implements pausable functionality following the Behodler3 pattern where both owner and pauser
* can unpause the contract, providing redundancy in case the pauser is compromised or unavailable.
*
* ## Pausable Architecture
*
* This contract inherits from both OpenZeppelin's Pausable and implements IPausable from the pauser
* dependency. The pausable functionality provides an emergency stop mechanism that can halt
* state-changing operations when needed.
*
* ### Pause Permissions
* - **Pause**: Only the designated pauser address can pause the contract
* - **Unpause**: Both the owner AND the pauser can unpause (Behodler3 pattern for redundancy)
*
* ### Protected Functions
* State-changing functions that could pose risk are protected with the `whenNotPaused` modifier.
* View functions remain operational even when paused to allow monitoring and inspection.
*
* ## Purpose and Architecture
*
* In the Phoenix architecture, multiple yield strategies exist, each corresponding to a different
* stablecoin. Phlimbo distributes these rewards, but as yield strategies grow in number, this becomes
* unwieldy and gas-intensive. Additionally, Limbo stakers would need to manage many different reward tokens.
*
* StableYieldAccumulator consolidates all yield strategy rewards into a single stablecoin before
* Phlimbo distribution. This provides:
*
* 1. **Simplified rewards** - Limbo stakers only deal with 2 tokens: phUSD and one stablecoin
* 2. **Future-proof Phlimbo** - No upgrades/migrations needed when yield strategies change
* 3. **Decentralized conversion** - External actors perform the token swaps, not the protocol
*
* ### How It Works
*
* 1. **Yield Strategy Registry** - Maintains a dynamic list of yield strategies
* 2. **Exchange Rate Mappings** - Tracks decimal places (6 for USDC, 18 for Dola, etc.) and exchange rates
* 3. **No Oracles/AMMs** - Uses assumed 1:1 exchange rates for stablecoins (owner can adjust for permanent depegs)
* 4. **Claim Mechanism** - External users swap their reward token holdings for pending yield strategy rewards
* 5. **NFT Gate** - Claims require holding a valid NFT from the NFTMinter contract; exactly 1 NFT is burned per claim
*/
contract StableYieldAccumulator is Ownable, Pausable, ReentrancyGuard, IPausable, IStableYieldAccumulator {
using SafeERC20 for IERC20;
/*//////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////*/
/**
* @notice Address authorized to pause the contract
* @dev Starts as address(0), requiring explicit setPauser() call by owner
* This prevents accidental pausing before a pauser is designated
* The public visibility satisfies IPausable.pauser() getter requirement
*/
address public pauser;
/**
* @notice The single stablecoin used for consolidated reward distribution
* @dev This is the token that claimers pay with to receive yield strategy rewards
*/
address public rewardToken;
/**
* @notice Dynamic array tracking all registered yield strategies
* @dev Used to iterate over strategies for yield collection and calculation
*/
address[] public yieldStrategies;
/**
* @notice Mapping of token addresses to their configuration
* @dev Stores decimals, normalized exchange rate, and pause status for each token
*/
mapping(address => TokenConfig) public tokenConfigs;
/**
* @notice Global discount rate applied to all claims
* @dev Stored in basis points (e.g., 200 = 2%), max 10000 (100%)
*/
uint256 public discountRate;
/**
* @notice Address where claimed reward tokens are transferred to
* @dev This is the Phlimbo contract that distributes rewards to Limbo stakers
*/
address public phlimbo;
/**
* @notice Address of the minter contract that holds deposits in yield strategies
* @dev Used to query yield strategies for the minter's accumulated yield
*/
address public minterAddress;
/**
* @notice Mapping to check if a strategy is registered (O(1) lookup)
* @dev Used to avoid O(n) iteration for duplicate/existence checks
*/
mapping(address => bool) public isRegisteredStrategy;
/**
* @notice Mapping from strategy address to its underlying token address
* @dev Each yield strategy handles a specific token (e.g., USDC, USDT, DAI)
*/
mapping(address => address) public strategyTokens;
/*//////////////////////////////////////////////////////////////
NFT MINTER STATE VARIABLES
//////////////////////////////////////////////////////////////*/
/**
* @notice ERC1155 NFTMinter contract address for claim gating
* @dev Claims require holding at least 1 NFT from this contract; exactly 1 is burned per claim
*/
address public nftMinter;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when the pauser address is updated
* @param oldPauser Previous pauser address (may be address(0))
* @param newPauser New pauser address (may be address(0) to remove pauser)
*/
event PauserUpdated(address indexed oldPauser, address indexed newPauser);
/**
* @notice Emitted when the minter address is updated
* @param oldMinter Previous minter address (may be address(0))
* @param newMinter New minter address
*/
event MinterUpdated(address indexed oldMinter, address indexed newMinter);
/**
* @notice Emitted when the NFT minter address is updated
* @param oldNFTMinter Previous NFT minter address
* @param newNFTMinter New NFT minter address
*/
event NFTMinterUpdated(address indexed oldNFTMinter, address indexed newNFTMinter);
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the contract with msg.sender as owner
* @dev Pauser starts as address(0) and must be explicitly set via setPauser()
*/
constructor() Ownable(msg.sender) {
// Pauser defaults to address(0), requiring explicit initialization
}
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Restricts function access to only the designated pauser
* @dev Reverts with descriptive error if caller is not the pauser
*/
modifier onlyPauser() {
require(msg.sender == pauser, "Only pauser can call this function");
_;
}
/*//////////////////////////////////////////////////////////////
PAUSER MANAGEMENT
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets or updates the authorized pauser address
* @dev Only callable by the contract owner
* Emits PauserUpdated event with old and new pauser addresses
* Can be set to address(0) to effectively disable pausing
* @param _pauser New pauser address (use address(0) to remove pausing capability)
*/
function setPauser(address _pauser) external onlyOwner {
address oldPauser = pauser;
pauser = _pauser;
emit PauserUpdated(oldPauser, _pauser);
}
/*//////////////////////////////////////////////////////////////
PAUSE/UNPAUSE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Pauses all state-changing operations protected by whenNotPaused
* @dev Only callable by the designated pauser address
*/
function pause() external override onlyPauser {
_pause();
}
/**
* @notice Unpauses the contract, resuming normal operations
* @dev Callable by EITHER the owner OR the pauser (Behodler3 pattern)
*/
function unpause() external override {
require(msg.sender == owner() || msg.sender == pauser, "Only owner or pauser can unpause");
_unpause();
}
/*//////////////////////////////////////////////////////////////
YIELD STRATEGY MANAGEMENT
//////////////////////////////////////////////////////////////*/
/**
* @notice Adds a new yield strategy to the registry
* @dev Validates zero address and duplicate registration
* @param strategy Address of the yield strategy to add
* @param token Address of the underlying token that the strategy handles
*/
function addYieldStrategy(address strategy, address token) external override onlyOwner {
if (strategy == address(0)) revert ZeroAddress();
if (token == address(0)) revert ZeroAddress();
if (isRegisteredStrategy[strategy]) revert StrategyAlreadyRegistered();
yieldStrategies.push(strategy);
isRegisteredStrategy[strategy] = true;
strategyTokens[strategy] = token;
emit YieldStrategyAdded(strategy);
}
/**
* @notice Removes a yield strategy from the registry
* @dev Validates existence and removes from array by swapping with last element
* @param strategy Address of the yield strategy to remove
*/
function removeYieldStrategy(address strategy) external override onlyOwner {
if (!isRegisteredStrategy[strategy]) revert StrategyNotRegistered();
// Find and remove strategy from array
for (uint256 i = 0; i < yieldStrategies.length; i++) {
if (yieldStrategies[i] == strategy) {
// Swap with last element and pop
yieldStrategies[i] = yieldStrategies[yieldStrategies.length - 1];
yieldStrategies.pop();
break;
}
}
isRegisteredStrategy[strategy] = false;
delete strategyTokens[strategy];
emit YieldStrategyRemoved(strategy);
}
/**
* @notice Gets all registered yield strategies
* @return Array of yield strategy addresses
*/
function getYieldStrategies() external view override returns (address[] memory) {
return yieldStrategies;
}
/*//////////////////////////////////////////////////////////////
TOKEN CONFIGURATION
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets or updates the configuration for a token
* @dev Validates zero address and decimal constraints
* @param token Address of the token
* @param decimals Number of decimal places (must be <= 18)
* @param normalizedExchangeRate Exchange rate normalized to 18 decimals
*/
function setTokenConfig(address token, uint8 decimals, uint256 normalizedExchangeRate)
external
override
onlyOwner
{
if (token == address(0)) revert ZeroAddress();
if (decimals > 18) revert InvalidDecimals();
tokenConfigs[token].decimals = decimals;
tokenConfigs[token].normalizedExchangeRate = normalizedExchangeRate;
emit TokenConfigSet(token, decimals, normalizedExchangeRate);
}
/**
* @notice Pauses a token, preventing claims with it
* @param token Address of the token to pause
*/
function pauseToken(address token) external override onlyOwner {
tokenConfigs[token].paused = true;
emit TokenPaused(token);
}
/**
* @notice Unpauses a token, allowing claims with it
* @param token Address of the token to unpause
*/
function unpauseToken(address token) external override onlyOwner {
tokenConfigs[token].paused = false;
emit TokenUnpaused(token);
}
/**
* @notice Gets the configuration for a token
* @param token Address of the token
* @return TokenConfig struct with decimals, normalizedExchangeRate, and paused status
*/
function getTokenConfig(address token) external view override returns (TokenConfig memory) {
return tokenConfigs[token];
}
/*//////////////////////////////////////////////////////////////
DISCOUNT RATE
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets the discount rate for claims
* @param rate Discount rate in basis points (e.g., 200 = 2%)
*/
function setDiscountRate(uint256 rate) external override onlyOwner {
if (rate > 10000) revert ExceedsMaxDiscount();
uint256 oldRate = discountRate;
discountRate = rate;
emit DiscountRateSet(oldRate, rate);
}
/**
* @notice Gets the current discount rate
* @return Discount rate in basis points
*/
function getDiscountRate() external view override returns (uint256) {
return discountRate;
}
/*//////////////////////////////////////////////////////////////
PHLIMBO MANAGEMENT
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets the phlimbo address where claimed reward tokens are transferred
* @param _phlimbo Address of the Phlimbo contract
*/
function setPhlimbo(address _phlimbo) external onlyOwner {
if (_phlimbo == address(0)) revert ZeroAddress();
address oldPhlimbo = phlimbo;
phlimbo = _phlimbo;
emit PhlimboUpdated(oldPhlimbo, _phlimbo);
}
/**
* @notice Sets the minter address that holds deposits in yield strategies
* @param _minter Address of the minter contract
*/
function setMinter(address _minter) external onlyOwner {
if (_minter == address(0)) revert ZeroAddress();
address oldMinter = minterAddress;
minterAddress = _minter;
emit MinterUpdated(oldMinter, _minter);
}
/**
* @notice Sets the reward token address
* @param _rewardToken Address of the reward token (e.g., USDC)
*/
function setRewardToken(address _rewardToken) external onlyOwner {
if (_rewardToken == address(0)) revert ZeroAddress();
rewardToken = _rewardToken;
}
/**
* @notice Approves Phlimbo to spend reward tokens from this contract
* @param amount Amount of reward tokens to approve
*/
function approvePhlimbo(uint256 amount) external onlyOwner {
if (phlimbo == address(0)) revert ZeroAddress();
if (rewardToken == address(0)) revert ZeroAddress();
IERC20(rewardToken).forceApprove(phlimbo, amount);
}
/*//////////////////////////////////////////////////////////////
NFT MINTER CONFIGURATION
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets the NFTMinter contract address for claim gating
* @dev The NFTMinter must be an ERC1155 contract that also implements INFTMinter.
* The StableYieldAccumulator must be registered as an authorized burner on the NFTMinter.
* @param _nftMinter Address of the NFTMinter contract
*/
function setNFTMinter(address _nftMinter) external onlyOwner {
address oldNFTMinter = nftMinter;
nftMinter = _nftMinter;
emit NFTMinterUpdated(oldNFTMinter, _nftMinter);
}
/*//////////////////////////////////////////////////////////////
CLAIM MECHANISM
//////////////////////////////////////////////////////////////*/
/**
* @notice Claims all pending yield from all strategies by paying with reward token
* @dev Full claim flow:
* 1. Verify caller holds a valid NFT and burn 1 unit
* 2. Calculate total pending yield across all strategies (normalized to 18 decimals)
* 3. Apply discount to get claimer payment amount
* 4. Transfer rewardToken FROM claimer TO phlimbo
* 5. Withdraw yield FROM each strategy TO claimer
*/
function claim(uint256 nftIndex, uint256 minRewardTokenSupplied) external override whenNotPaused nonReentrant {
if (phlimbo == address(0)) revert ZeroAddress();
if (rewardToken == address(0)) revert ZeroAddress();
if (minterAddress == address(0)) revert ZeroAddress();
// NFT gate: verify caller holds a valid NFT and burn 1 unit
_validateAndBurnNFT(msg.sender, nftIndex);
uint256 totalNormalizedYield = 0;
uint256 strategiesWithYield = 0;
// Single pass: withdraw yield from each strategy and accumulate total
for (uint256 i = 0; i < yieldStrategies.length; i++) {
address strategy = yieldStrategies[i];
address token = strategyTokens[strategy];
if (token == address(0)) continue;
if (tokenConfigs[token].paused) continue;
uint256 yield = _getYieldForStrategy(strategy, token);
if (yield > 0) {
// Withdraw yield from strategy to claimer
IYieldStrategy(strategy).withdrawFrom(token, minterAddress, yield, msg.sender);
emit RewardsCollected(strategy, yield);
// Accumulate normalized yield for payment calculation
totalNormalizedYield += _normalizeAmount(yield, token);
strategiesWithYield++;
}
}
if (totalNormalizedYield == 0) revert ZeroAmount();
// Calculate and collect claimer payment (apply discount)
uint256 claimerPayment = totalNormalizedYield * (10000 - discountRate) / 10000;
uint256 actualPayment = _denormalizeAmount(claimerPayment, rewardToken);
// Slippage protection: revert if actual payment is below caller's minimum
if (actualPayment < minRewardTokenSupplied) revert InsufficientYield();
// Transfer reward tokens FROM claimer TO this contract, then have Phlimbo collect them
IERC20(rewardToken).safeTransferFrom(msg.sender, address(this), actualPayment);
IPhlimbo(phlimbo).collectReward(actualPayment);
emit RewardsClaimed(msg.sender, actualPayment, strategiesWithYield);
}
/**
* @notice Internal helper to validate NFT ownership and burn 1 unit
* @dev Uses the provided index for O(1) lookup instead of iterating all dispatcher configs
* @param caller The address to check for NFT ownership
* @param index The dispatcher config index in NFTMinter
*/
function _validateAndBurnNFT(address caller, uint256 index) internal {
require(nftMinter != address(0), "NFT minter not configured");
require(index > 0, "Invalid index");
if (IERC1155(nftMinter).balanceOf(caller, index) > 0) {
INFTMinter(nftMinter).burn(caller, index, 1);
} else {
revert NoValidNFT();
}
}
/**
* @notice Internal helper to get yield for a specific strategy
* @param strategy Address of the yield strategy
* @param token Address of the strategy's underlying token
* @return yield The pending yield amount
*/
function _getYieldForStrategy(address strategy, address token) internal view returns (uint256) {
IYieldStrategy yieldStrategy = IYieldStrategy(strategy);
uint256 totalBalance = yieldStrategy.totalBalanceOf(token, minterAddress);
uint256 principal = yieldStrategy.principalOf(token, minterAddress);
if (totalBalance > principal) {
return totalBalance - principal;
}
return 0;
}
/**
* @notice Internal helper to get normalized yield for a specific strategy
* @param strategy Address of the yield strategy
* @param token Address of the strategy's underlying token
* @return Yield amount normalized to 18 decimals
*/
function _getNormalizedYieldForStrategy(address strategy, address token) internal view returns (uint256) {
uint256 yield = _getYieldForStrategy(strategy, token);
if (yield > 0) {
return _normalizeAmount(yield, token);
}
return 0;
}
/**
* @notice Normalizes an amount from token decimals to 18 decimals
* @param amount The amount in token decimals
* @param token The token address to get decimals from
* @return The amount normalized to 18 decimals
*/
function _normalizeAmount(uint256 amount, address token) internal view returns (uint256) {
uint8 decimals = tokenConfigs[token].decimals;
uint256 exchangeRate = tokenConfigs[token].normalizedExchangeRate;
// If no config set, assume 18 decimals and 1:1 rate
if (decimals == 0 && exchangeRate == 0) {
return amount;
}
// Scale to 18 decimals
uint256 scaled = amount;
if (decimals < 18) {
scaled = amount * (10 ** (18 - decimals));
} else if (decimals > 18) {
scaled = amount / (10 ** (decimals - 18));
}
// Apply exchange rate (already normalized to 18 decimals)
if (exchangeRate > 0 && exchangeRate != 1e18) {
scaled = scaled * exchangeRate / 1e18;
}
return scaled;
}
/**
* @notice Denormalizes an amount from 18 decimals to token decimals
* @param amount The amount in 18 decimals
* @param token The token address to get decimals from
* @return The amount in token decimals
*/
function _denormalizeAmount(uint256 amount, address token) internal view returns (uint256) {
uint8 decimals = tokenConfigs[token].decimals;
uint256 exchangeRate = tokenConfigs[token].normalizedExchangeRate;
// If no config set, assume 18 decimals and 1:1 rate
if (decimals == 0 && exchangeRate == 0) {
return amount;
}
// Reverse exchange rate first
uint256 scaled = amount;
if (exchangeRate > 0 && exchangeRate != 1e18) {
scaled = scaled * 1e18 / exchangeRate;
}
// Scale from 18 decimals to token decimals
if (decimals < 18) {
scaled = scaled / (10 ** (18 - decimals));
} else if (decimals > 18) {
scaled = scaled * (10 ** (decimals - 18));
}
return scaled;
}
/**
* @notice Calculates how much the claimer would pay for total pending yield
* @return paymentAmount Amount of reward token claimer would pay (in reward token decimals)
*/
function calculateClaimAmount()
external
view
override
returns (uint256)
{
if (minterAddress == address(0)) return 0;
uint256 totalNormalizedYield = 0;
for (uint256 i = 0; i < yieldStrategies.length; i++) {
address strategy = yieldStrategies[i];
address token = strategyTokens[strategy];
if (token == address(0)) continue;
if (tokenConfigs[token].paused) continue;
uint256 yield = _getYieldForStrategy(strategy, token);
if (yield > 0) {
totalNormalizedYield += _normalizeAmount(yield, token);
}
}
if (totalNormalizedYield == 0) return 0;
// Apply discount
uint256 claimerPayment = totalNormalizedYield * (10000 - discountRate) / 10000;
// Denormalize to reward token decimals
return _denormalizeAmount(claimerPayment, rewardToken);
}
/*//////////////////////////////////////////////////////////////
BOT HELPER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Checks if a specific caller can claim based on NFT holdings
* @dev Returns true if the caller holds any valid NFT from the minter
* @param caller Address to check
* @return True if the caller holds a valid NFT
*/
function canClaim(address caller) external view returns (bool) {
if (nftMinter == address(0)) {
return false;
}
uint256 count = INFTMinter(nftMinter).nextIndex();
for (uint256 i = 1; i < count; i++) {
if (IERC1155(nftMinter).balanceOf(caller, i) > 0) {
return true;
}
}
return false;
}
/*//////////////////////////////////////////////////////////////
YIELD CALCULATION
//////////////////////////////////////////////////////////////*/
/**
* @notice Gets the pending yield for a specific strategy
* @param strategy Address of the yield strategy
* @return Pending yield amount (in native token decimals)
*/
function getYield(address strategy) external view override returns (uint256) {
if (!isRegisteredStrategy[strategy]) revert StrategyNotRegistered();
if (minterAddress == address(0)) return 0;
address token = strategyTokens[strategy];
if (token == address(0)) return 0;
// Query the yield strategy for minter's total balance and principal
IYieldStrategy yieldStrategy = IYieldStrategy(strategy);
uint256 totalBalance = yieldStrategy.totalBalanceOf(token, minterAddress);
uint256 principal = yieldStrategy.principalOf(token, minterAddress);
// Yield = total balance - principal (accumulated yield)
if (totalBalance > principal) {
return totalBalance - principal;
}
return 0;
}
/**
* @notice Gets the total pending yield across all strategies
* @return Total pending yield normalized to 18 decimals
*/
function getTotalYield() external view override returns (uint256) {
if (minterAddress == address(0)) return 0;
uint256 total = 0;
for (uint256 i = 0; i < yieldStrategies.length; i++) {
address strategy = yieldStrategies[i];
address token = strategyTokens[strategy];
if (token == address(0)) continue;
total += _getNormalizedYieldForStrategy(strategy, token);
}
return total;
}
}
lib/pauser/src/interfaces/IPausable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title IPausable
* @notice Interface that pausable contracts must implement to be compatible with the Global Pauser
* @dev Contracts implementing this interface can be registered with the Global Pauser
* and will be paused/unpaused when the Global Pauser is triggered
*
* Implementation requirements:
* - pause() should revert if caller is not the authorized pauser
* - unpause() should revert if caller is not the authorized pauser
* - Contracts should maintain internal state to track pause status
*/
interface IPausable {
/**
* @notice Pause the contract
* @dev Should revert if caller is not the authorized pauser
* Should set internal pause state to prevent operations while paused
*/
function pause() external;
/**
* @notice Unpause the contract
* @dev Should revert if caller is not the authorized pauser
* Should clear internal pause state to resume normal operations
*/
function unpause() external;
/**
* @notice Get the authorized pauser address
* @dev This getter is required for backward compatibility with Behodler3
* Pausable contracts should expose: address public pauser;
* @return The address authorized to pause/unpause this contract
*/
function pauser() external view returns (address);
}
lib/phUSD-stable-minter/lib/openzeppelin-contracts/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);
}
}
lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/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);
}
lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/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";
lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/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";
lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/IERC1155.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[ERC].
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the value of tokens of token type `id` owned by `account`.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the zero address.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {IERC1155Receiver-onERC1155Received} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `value` amount.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {IERC1155Receiver-onERC1155BatchReceived} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
*
* Requirements:
*
* - `ids` and `values` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
}
lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/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);
}
lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/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)
}
}
}
lib/phUSD-stable-minter/lib/openzeppelin-contracts/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;
}
}
lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/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;
}
}
lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/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
}
}
}
lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/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);
}
lib/phlimbo-ea/src/IFlax.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IFlax
* @notice Interface for Flax token (phUSD) with minting capabilities
*/
interface IFlax is IERC20 {
struct MinterInfo {
bool canMint;
uint256 mintVersion;
}
function mint(address recipient, uint256 amount) external;
function burn(address holder, uint256 amount) external;
function authorizedMinters(address minter) external view returns (MinterInfo memory);
function mintVersion() external view returns (uint256);
function revokeAllMintPrivileges() external;
}
lib/phlimbo-ea/src/interfaces/IPhlimbo.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../IFlax.sol";
/**
* @title IPhlimbo
* @notice Interface for the PhlimboEA staking yield farm contract
*/
interface IPhlimbo {
// ========================== EVENTS ==========================
/**
* @notice Emitted when a user makes an emergency withdrawal while contract is paused
* @param user Address of the user withdrawing
* @param amount Amount of phUSD withdrawn
*/
event EmergencyWithdrawal(address indexed user, uint256 amount);
/**
* @notice Emitted when a user stakes phUSD
* @param user Address of the user staking
* @param amount Amount of phUSD staked
*/
event Staked(address indexed user, uint256 amount);
/**
* @notice Emitted when a user withdraws staked phUSD
* @param user Address of the user withdrawing
* @param amount Amount of phUSD withdrawn
*/
event Withdrawn(address indexed user, uint256 amount);
/**
* @notice Emitted when a user claims rewards
* @param user Address of the user claiming rewards
* @param phUSDAmount Amount of phUSD rewards claimed
* @param stableAmount Amount of stable token rewards claimed
*/
event RewardsClaimed(address indexed user, uint256 phUSDAmount, uint256 stableAmount);
// ========================== ADMIN FUNCTIONS ==========================
/**
* @notice Updates the desired APY and recalculates emission rate
* @param bps New APY in basis points
*/
function setDesiredAPY(uint256 bps) external;
/**
* @notice Sets the depletion duration for reward distribution
* @param _duration New depletion duration in seconds
*/
function setDepletionDuration(uint256 _duration) external;
/**
* @notice Sets the address authorized to pause the contract
* @param _pauser Address to authorize for pausing (can be zero address to disable pausing)
*/
function setPauser(address _pauser) external;
/**
* @notice Emergency function to transfer all tokens to a recipient
* @param recipient Address to receive the tokens
*/
function emergencyTransfer(address recipient) external;
/**
* @notice Allows users to withdraw their staked phUSD when contract is paused
* @dev Emergency exit mechanism - does NOT claim rewards or update pool
* @param amount Amount of phUSD to withdraw
*/
function pauseWithdraw(uint256 amount) external;
// ========================== REWARD COLLECTION ==========================
/**
* @notice Collects rewards and updates linear depletion rate
* @dev Anyone with approved tokens can contribute rewards
* @param amount Amount of reward tokens to collect
*/
function collectReward(uint256 amount) external;
// ========================== CORE STAKING FUNCTIONS ==========================
/**
* @notice Stake phUSD tokens
* @param amount Amount of phUSD to stake
* @param recipient Address to receive the staked position (use address(0) for msg.sender)
*/
function stake(uint256 amount, address recipient) external;
/**
* @notice Withdraw staked phUSD and claim rewards
* @param amount Amount of phUSD to withdraw
*/
function withdraw(uint256 amount) external;
/**
* @notice Claim pending rewards without withdrawing stake
*/
function claim() external;
// ========================== VIEW FUNCTIONS ==========================
/**
* @notice Returns pending phUSD rewards for a user
* @param user Address to check
* @return Pending phUSD amount
*/
function pendingPhUSD(address user) external view returns (uint256);
/**
* @notice Returns pending stable rewards for a user
* @param user Address to check
* @return Pending stable amount
*/
function pendingStable(address user) external view returns (uint256);
/**
* @notice Returns current pool information
* @return _totalStaked Total staked amount
* @return _accPhUSDPerShare Accumulated phUSD per share
* @return _accStablePerShare Accumulated stable per share
* @return _phUSDPerSecond Current emission rate
* @return _lastRewardTime Last update time
*/
function getPoolInfo() external view returns (
uint256 _totalStaked,
uint256 _accPhUSDPerShare,
uint256 _accStablePerShare,
uint256 _phUSDPerSecond,
uint256 _lastRewardTime
);
// ========================== STATE VARIABLE GETTERS ==========================
function phUSD() external view returns (IFlax);
function rewardToken() external view returns (IERC20);
function desiredAPYBps() external view returns (uint256);
function phUSDPerSecond() external view returns (uint256);
function rewardBalance() external view returns (uint256);
function depletionDuration() external view returns (uint256);
function rewardPerSecond() external view returns (uint256);
function lastRewardTime() external view returns (uint256);
function accPhUSDPerShare() external view returns (uint256);
function accStablePerShare() external view returns (uint256);
function totalStaked() external view returns (uint256);
function PRECISION() external view returns (uint256);
function SECONDS_PER_YEAR() external view returns (uint256);
function userInfo(address user) external view returns (uint256 amount, uint256 phUSDDebt, uint256 stableDebt);
}
lib/stable-yield-accumulator/lib/mutable/yield-claim-nft/src/interfaces/INFTMinter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {ITokenMinter} from "./ITokenMinter.sol";
/// @notice Comprehensive interface for NFTMinter exposing all NFTMinter-specific
/// public functions (mint, burn, admin, views) for dependency injection.
interface INFTMinter is ITokenMinter {
// --- Burn ---
/// @notice Burns claim NFTs from a holder. Only callable by authorized burners.
/// @param holder The address holding the NFTs to burn.
/// @param tokenId The token ID to burn.
/// @param quantity The number of tokens to burn.
function burn(address holder, uint256 tokenId, uint256 quantity) external;
/// @notice Returns whether an address is an authorized burner.
/// @param burner The address to check.
/// @return True if the address is authorized to burn.
function authorizedBurners(address burner) external view returns (bool);
/// @notice Sets or removes an address as an authorized burner. Only callable by owner.
/// @param burner The address to authorize or deauthorize.
/// @param authorized Whether the address is authorized to burn.
function setAuthorizedBurner(address burner, bool authorized) external;
// --- Admin ---
/// @notice Sets the authorized pauser address. Only callable by owner.
/// @param newPauser The new pauser address.
function setPauser(address newPauser) external;
/// @notice Enables or disables minting for a dispatcher. Only callable by owner.
/// @param index The dispatcher index.
/// @param disabled If true, new mints are blocked; if false, mints are re-enabled.
function setDispatcherDisabled(uint256 index, bool disabled) external;
/// @notice Rescues any ERC20 token stuck in this contract. Only callable by owner.
/// @param token The ERC20 token address to withdraw.
function emergencyWithdraw(address token) external;
/// @notice Pauses or unpauses a registered dispatcher. Only callable by owner.
/// @param dispatcher The dispatcher contract address.
/// @param active If true, unpauses the dispatcher; if false, pauses it.
function setDispatcherActive(address dispatcher, bool active) external;
// --- Views ---
/// @notice Whether the contract is currently paused.
function paused() external view returns (bool);
/// @notice Auto-incrementing dispatcher index (starts at 1 so 0 is invalid).
function nextIndex() external view returns (uint256);
/// @notice Maps dispatcher index to its configuration.
/// @param index The dispatcher index.
/// @return dispatcher The dispatcher contract address.
/// @return price The current mint price.
/// @return growthBasisPoints Price growth per mint in basis points.
/// @return disabled Whether minting is disabled for this dispatcher.
function configs(uint256 index) external view returns (address dispatcher, uint256 price, uint256 growthBasisPoints, bool disabled);
/// @notice Maps dispatcher contract address to its index.
/// @param dispatcher The dispatcher address.
/// @return The dispatcher index.
function dispatcherToIndex(address dispatcher) external view returns (uint256);
/// @notice Reverse lookup: maps token ID to the dispatcher address that produces it.
/// @param tokenId The token ID.
/// @return The dispatcher address.
function tokenIdToDispatcher(uint256 tokenId) external view returns (address);
}
lib/stable-yield-accumulator/lib/mutable/yield-claim-nft/src/interfaces/ITokenMinter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface ITokenMinter {
/// @notice Mints a claim NFT by paying with a registered protocol token.
/// @param token The ERC20 token address to pay with.
/// @param index The dispatcher index to route the payment to.
/// @param recipient The address that receives the claim NFT.
/// @return success True if the mint was successful.
function mint(address token, uint256 index, address recipient) external returns (bool);
/// @notice Mints a claim NFT, forwarding arbitrary extra data to the dispatcher.
/// @param token The ERC20 token address to pay with.
/// @param index The dispatcher index to route the payment to.
/// @param recipient The address that receives the claim NFT.
/// @param extraData Dispatcher-specific encoded data (e.g. slippage parameters).
/// @return success True if the mint was successful.
function mint(address token, uint256 index, address recipient, bytes calldata extraData) external returns (bool);
/// @notice Registers a new token dispatcher. Only callable by owner.
/// @param dispatcher The dispatcher contract address.
/// @param initialPrice The initial mint price in the dispatcher's prime token units.
/// @param growthBasisPoints Price growth per mint in basis points (100 = 1%).
function registerDispatcher(address dispatcher, uint256 initialPrice, uint256 growthBasisPoints) external;
/// @notice Returns the current mint price for a given dispatcher index.
/// @param index The dispatcher index.
/// @return The current price in token units.
function getPrice(uint256 index) external view returns (uint256);
/// @notice Returns all dispatcher indexes registered for a given token.
/// @param token The ERC20 token address.
/// @return An array of dispatcher indexes.
function getDispatchers(address token) external view returns (uint256[] memory);
/// @notice Sets the mint price for a given dispatcher index. Only callable by owner.
/// @param index The dispatcher index.
/// @param newPrice The new price in token units.
function setPrice(uint256 index, uint256 newPrice) external;
/// @notice Sets the growth factor for a given dispatcher index. Only callable by owner.
/// @param index The dispatcher index.
/// @param newGrowthBasisPoints The new growth factor in basis points.
function setGrowthFactor(uint256 index, uint256 newGrowthBasisPoints) external;
}
lib/stable-yield-accumulator/src/interfaces/IStableYieldAccumulator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title IStableYieldAccumulator
* @notice Interface for the StableYieldAccumulator contract
* @dev Defines all events, errors, and function signatures for the core logic
*/
interface IStableYieldAccumulator {
/*//////////////////////////////////////////////////////////////
STRUCTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Configuration for a reward token
* @param decimals Number of decimal places for the token (max 18)
* @param normalizedExchangeRate Exchange rate normalized to 18 decimals
* @param paused Whether the token is currently paused
*/
struct TokenConfig {
uint8 decimals;
uint256 normalizedExchangeRate;
bool paused;
}
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when a yield strategy is added to the registry
* @param strategy Address of the added yield strategy
*/
event YieldStrategyAdded(address indexed strategy);
/**
* @notice Emitted when a yield strategy is removed from the registry
* @param strategy Address of the removed yield strategy
*/
event YieldStrategyRemoved(address indexed strategy);
/**
* @notice Emitted when a token configuration is set or updated
* @param token Address of the token
* @param decimals Number of decimal places
* @param normalizedExchangeRate Exchange rate normalized to 18 decimals
*/
event TokenConfigSet(address indexed token, uint8 decimals, uint256 normalizedExchangeRate);
/**
* @notice Emitted when a token is paused
* @param token Address of the paused token
*/
event TokenPaused(address indexed token);
/**
* @notice Emitted when a token is unpaused
* @param token Address of the unpaused token
*/
event TokenUnpaused(address indexed token);
/**
* @notice Emitted when the discount rate is updated
* @param oldRate Previous discount rate in basis points
* @param newRate New discount rate in basis points
*/
event DiscountRateSet(uint256 oldRate, uint256 newRate);
/**
* @notice Emitted when the phlimbo address is updated
* @param oldPhlimbo Previous phlimbo address
* @param newPhlimbo New phlimbo address
*/
event PhlimboUpdated(address indexed oldPhlimbo, address indexed newPhlimbo);
/**
* @notice Emitted when a user claims rewards
* @param claimer Address that performed the claim
* @param amountPaid Amount of reward token paid
* @param strategiesClaimed Number of strategies claimed from
*/
event RewardsClaimed(
address indexed claimer,
uint256 amountPaid,
uint256 strategiesClaimed
);
/**
* @notice Emitted when yield is collected from a strategy
* @param strategy Address of the yield strategy
* @param amount Amount collected
*/
event RewardsCollected(address indexed strategy, uint256 amount);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
/**
* @notice Thrown when a function is not yet implemented (red phase stub)
*/
error NotImplemented();
/**
* @notice Thrown when a zero address is provided where it's not allowed
*/
error ZeroAddress();
/**
* @notice Thrown when token decimals exceed 18
*/
error InvalidDecimals();
/**
* @notice Thrown when discount rate exceeds 10000 basis points (100%)
*/
error ExceedsMaxDiscount();
/**
* @notice Thrown when trying to interact with a strategy that's not registered
*/
error StrategyNotRegistered();
/**
* @notice Thrown when trying to add a strategy that's already registered
*/
error StrategyAlreadyRegistered();
/**
* @notice Thrown when trying to claim more than available pending rewards
*/
error InsufficientPending();
/**
* @notice Thrown when trying to claim zero amount
*/
error ZeroAmount();
/**
* @notice Thrown when caller has no valid NFT for claiming
*/
error NoValidNFT();
/**
* @notice Thrown when actual yield payment is less than the caller's minimum acceptable amount
* @dev Used for slippage protection against MEV front-running during claim
*/
error InsufficientYield();
/*//////////////////////////////////////////////////////////////
YIELD STRATEGY MANAGEMENT
//////////////////////////////////////////////////////////////*/
/**
* @notice Adds a new yield strategy to the registry
* @param strategy Address of the yield strategy to add
* @param token Address of the underlying token that the strategy handles
*/
function addYieldStrategy(address strategy, address token) external;
/**
* @notice Removes a yield strategy from the registry
* @param strategy Address of the yield strategy to remove
*/
function removeYieldStrategy(address strategy) external;
/**
* @notice Gets all registered yield strategies
* @return Array of yield strategy addresses
*/
function getYieldStrategies() external view returns (address[] memory);
/**
* @notice Gets the token address associated with a yield strategy
* @param strategy Address of the yield strategy
* @return Address of the token the strategy handles
*/
function strategyTokens(address strategy) external view returns (address);
/*//////////////////////////////////////////////////////////////
TOKEN CONFIGURATION
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets or updates the configuration for a token
* @param token Address of the token
* @param decimals Number of decimal places (must be <= 18)
* @param normalizedExchangeRate Exchange rate normalized to 18 decimals
*/
function setTokenConfig(address token, uint8 decimals, uint256 normalizedExchangeRate) external;
/**
* @notice Pauses a token, preventing claims with it
* @param token Address of the token to pause
*/
function pauseToken(address token) external;
/**
* @notice Unpauses a token, allowing claims with it
* @param token Address of the token to unpause
*/
function unpauseToken(address token) external;
/**
* @notice Gets the configuration for a token
* @param token Address of the token
* @return TokenConfig struct with decimals, normalizedExchangeRate, and paused status
*/
function getTokenConfig(address token) external view returns (TokenConfig memory);
/*//////////////////////////////////////////////////////////////
DISCOUNT RATE
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets the discount rate for claims
* @param rate Discount rate in basis points (e.g., 200 = 2%)
*/
function setDiscountRate(uint256 rate) external;
/**
* @notice Gets the current discount rate
* @return Discount rate in basis points
*/
function getDiscountRate() external view returns (uint256);
/*//////////////////////////////////////////////////////////////
PHLIMBO MANAGEMENT
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets the phlimbo address where claimed reward tokens are transferred
* @param _phlimbo Address of the Phlimbo contract
*/
function setPhlimbo(address _phlimbo) external;
/**
* @notice Gets the current phlimbo address
* @return Address of the Phlimbo contract
*/
function phlimbo() external view returns (address);
/**
* @notice Sets the minter address that holds deposits in yield strategies
* @param _minter Address of the minter contract
*/
function setMinter(address _minter) external;
/**
* @notice Gets the current minter address
* @return Address of the minter contract
*/
function minterAddress() external view returns (address);
/*//////////////////////////////////////////////////////////////
CLAIM MECHANISM
//////////////////////////////////////////////////////////////*/
/**
* @notice Gets the reward token address used for claim payments
* @return Address of the reward token (e.g., USDC)
*/
function rewardToken() external view returns (address);
/**
* @notice Claims all pending yield from all strategies by paying with reward token
* @dev Full flow:
* 1. Verify caller holds a valid NFT at the given index and burn 1 unit
* 2. Calculate total pending yield (normalized)
* 3. Apply discount to get claimer payment
* 4. TransferFrom claimer to phlimbo
* 5. WithdrawFrom each strategy to claimer
* @param nftIndex The dispatcher config index in NFTMinter identifying which NFT to validate and burn
* @param minRewardTokenSupplied Minimum acceptable payment amount in reward token decimals.
* Reverts with InsufficientYield if actual payment is less than this value.
* Pass 0 to disable slippage protection.
*/
function claim(uint256 nftIndex, uint256 minRewardTokenSupplied) external;
/**
* @notice Calculates how much the claimer would pay for total pending yield
* @dev Returns the discounted amount in reward token decimals
* @return Amount of reward token claimer would pay
*/
function calculateClaimAmount()
external
view
returns (uint256);
/*//////////////////////////////////////////////////////////////
YIELD CALCULATION
//////////////////////////////////////////////////////////////*/
/**
* @notice Gets the pending yield for a specific strategy
* @dev Returns yield in the strategy's native token decimals (NOT normalized)
* @param strategy Address of the yield strategy
* @return Pending yield amount in native token decimals
*/
function getYield(address strategy) external view returns (uint256);
/**
* @notice Gets the total pending yield across all strategies
* @dev Returns yield normalized to 18 decimals for cross-token comparison
* @return Total pending yield normalized to 18 decimals
*/
function getTotalYield() external view returns (uint256);
/*//////////////////////////////////////////////////////////////
NFT MINTER CONFIGURATION
//////////////////////////////////////////////////////////////*/
/**
* @notice Sets the NFTMinter contract address for claim gating
* @param _nftMinter Address of the NFTMinter ERC1155 contract
*/
function setNFTMinter(address _nftMinter) external;
/**
* @notice Gets the current NFTMinter address
* @return Address of the NFTMinter contract
*/
function nftMinter() external view returns (address);
/*//////////////////////////////////////////////////////////////
BOT HELPER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Checks if a specific caller can claim based on NFT holdings
* @dev Returns true if the caller holds any valid NFT from the minter
* @param caller Address to check
* @return True if the caller holds a valid NFT
*/
function canClaim(address caller) external view returns (bool);
}
lib/vault/src/interfaces/IYieldStrategy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @title IYieldStrategy
* @notice Interface for yield strategy adapter that handles token deposits and withdrawals
*/
interface IYieldStrategy {
/**
* @notice Deposit tokens into the vault
* @param token The token address to deposit
* @param amount The amount of tokens to deposit
* @param recipient The address that will own the deposited tokens
*/
function deposit(address token, uint256 amount, address recipient) external;
/**
* @notice Withdraw tokens from the vault
* @param token The token address to withdraw
* @param amount The amount of tokens to withdraw
* @param recipient The address that will receive the tokens
*/
function withdraw(address token, uint256 amount, address recipient) external;
/**
* @notice Get the balance of a token for a specific address
* @param token The token address
* @param account The account address
* @return The token balance
* @dev DEPRECATED: This method's semantics are ambiguous (principal vs principal+yield).
* Use principalOf() for principal-only queries or totalBalanceOf() for principal+yield.
* For backward compatibility, existing implementations should maintain current behavior,
* but new code should use the explicit methods instead.
*/
function balanceOf(address token, address account) external view returns (uint256);
/**
* @notice Returns the principal balance for a specific address
* @dev Principal represents the amount originally deposited, excluding any accumulated yield.
* This is the basis for calculating surplus yield in the SurplusTracker system.
* @param token The token address to query
* @param account The account address to query the principal balance for
* @return The principal balance of the account (deposits only, no yield)
*/
function principalOf(address token, address account) external view returns (uint256);
/**
* @notice Returns the total balance including accumulated yield for a specific address
* @dev Total balance represents principal + yield. This is the amount that would be
* received if the account withdrew all their funds. The difference between
* totalBalanceOf() and principalOf() represents the accumulated yield that can
* be extracted via the SurplusWithdrawer system.
* @param token The token address to query
* @param account The account address to query the total balance for
* @return The total balance of the account (principal + accumulated yield)
*/
function totalBalanceOf(address token, address account) external view returns (uint256);
/**
* @notice Set client authorization for deposit/withdraw operations
* @param client The address of the client contract
* @param _auth Whether to authorize (true) or deauthorize (false) the client
* @dev This function should be restricted to the contract owner
*/
function setClient(address client, bool _auth) external;
/**
* @notice Emergency withdraw function for owner to withdraw funds
* @param amount The amount of tokens to withdraw
* @dev This function should be restricted to the contract owner
*/
function emergencyWithdraw(uint256 amount) external;
/**
* @notice Two-phase total withdrawal function for emergency fund migration
* @param token The token address to withdraw from
* @param client The client address whose tokens to withdraw
* @dev Phase 1: Initiates 24-hour waiting period. Phase 2: Executes withdrawal within 48-hour window.
* This provides community protection against rugpulls while allowing legitimate fund migrations.
* Only the contract owner can initiate this process.
*/
function totalWithdrawal(address token, address client) external;
/**
* @notice Withdraw surplus from a client's balance to a specified recipient
* @param token The token address to withdraw
* @param client The client address whose balance to withdraw from
* @param amount The amount to withdraw
* @param recipient The address that will receive the withdrawn tokens
* @dev Only authorized withdrawers can call this function. This is used to extract surplus yield.
*/
function withdrawFrom(address token, address client, uint256 amount, address recipient) external;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 10000,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@phlimbo-ea/=lib/phlimbo-ea/src/",
"@phUSD-stable-minter/=lib/phUSD-stable-minter/src/",
"@stable-yield-accumulator/=lib/stable-yield-accumulator/src/",
"@openzeppelin/contracts/=lib/phUSD-stable-minter/lib/openzeppelin-contracts/contracts/",
"@forge-std/=lib/forge-std/src/",
"@vault-interfaces/=lib/vault/src/interfaces/",
"@vault/=lib/vault/src/",
"@pauser/=lib/pauser/src/",
"pauser/=lib/pauser/src/",
"forge-std/=lib/forge-std/src/",
"lib/mutable/pauser/=lib/pauser/",
"vault/interfaces/=lib/vault/src/interfaces/",
"phlimbo-ea/=lib/phlimbo-ea/src/",
"lib/phUSD-stable-minter/lib/mutable/pauser/=lib/pauser/",
"lib/stable-yield-accumulator/lib/mutable/pauser/=lib/pauser/",
"lib/phlimbo-ea/lib/mutable/pauser/=lib/pauser/",
"lib/phUSD-stable-minter/lib/mutable/vault/=lib/vault/",
"openzeppelin-contracts/=lib/phUSD-stable-minter/lib/openzeppelin-contracts/",
"erc4626-tests/=lib/phUSD-stable-minter/lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/phUSD-stable-minter/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"v4-core/=lib/stable-yield-accumulator/lib/v4-periphery/lib/v4-core/src/",
"v4-periphery/=lib/stable-yield-accumulator/lib/v4-periphery/",
"@uniswap/v4-core/=lib/stable-yield-accumulator/lib/v4-periphery/lib/v4-core/",
"lib/stable-yield-accumulator/lib/openzeppelin-contracts/=lib/stable-yield-accumulator/lib/openzeppelin-contracts/",
"@flax-token/=lib/flax-token-v2/src/",
"yield-claim-nft/=lib/stable-yield-accumulator/lib/mutable/yield-claim-nft/src/",
"@yield-claim-nft/=lib/yield-claim-nft/src/",
"lib/yield-claim-nft/src/interfaces/IBurnable.sol=lib/pauser/src/interfaces/IBurnable.sol"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.