Verified contractExactMIT
YieldManager
Address0x320d5a1ce8f2c1bcf4875d59c3dc480201cb3e42
- Balance
0 ETH
- Transactions
18
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,603,166
- Creation transaction
- 0xd7eb5f33d6…33c9ea41ee
15 files
- src/YieldManager.solmain7.15 KB
- @openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- @openzeppelin/contracts/interfaces/IERC165.sol193 B
- @openzeppelin/contracts/interfaces/IERC20.sol182 B
- @openzeppelin/contracts/interfaces/IERC20Metadata.sol216 B
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol13.96 KB
- @openzeppelin/contracts/utils/ReentrancyGuardTransient.sol2.85 KB
- @openzeppelin/contracts/utils/TransientSlot.sol5.08 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- src/interfaces/IGateway.sol8.68 KB
- src/interfaces/IPeggedToken.sol882 B
- src/interfaces/ITreasury.sol2.51 KB
- src/interfaces/IYieldDistributor.sol2.11 KB
src/YieldManager.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {IPeggedToken} from "./interfaces/IPeggedToken.sol";
import {ITreasury} from "./interfaces/ITreasury.sol";
import {IGateway} from "./interfaces/IGateway.sol";
import {IYieldDistributor} from "./interfaces/IYieldDistributor.sol";
/// @title YieldManager: One-shot yield operations for keepers
/// @notice Chains `Treasury.harvest` -> `Gateway.deposit` (backed mint) -> `YieldDistributor.distribute`
/// so a keeper turns treasury excess into staker yield in a single call.
/// @dev Grant this contract UMM_ROLE (Treasury) and DISTRIBUTOR_ROLE (YieldDistributor) to enable it.
contract YieldManager is ReentrancyGuardTransient {
using SafeERC20 for IERC20;
using SafeERC20 for IPeggedToken;
/*/////////////////////////////////////////////////////////////
STATE VARIABLES
/////////////////////////////////////////////////////////////*/
string public constant VERSION = "1.0.0";
// Inlined role IDs matching Treasury's definitions to avoid chained external calls
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
bytes32 public constant KEEPER_ROLE = keccak256("KEEPER_ROLE");
/// @notice Pegged token
IPeggedToken public immutable PEGGED_TOKEN;
/// @notice Yield distributor
IYieldDistributor public immutable YIELD_DISTRIBUTOR;
/*/////////////////////////////////////////////////////////////
EVENTS
/////////////////////////////////////////////////////////////*/
event HarvestedAndDistributed(address indexed token, uint256 tokenAmount, uint256 peggedTokenAmount);
event Swept(address indexed token, uint256 amount, address indexed receiver);
/*/////////////////////////////////////////////////////////////
ERRORS
/////////////////////////////////////////////////////////////*/
error AccessControlUnauthorizedAccount(address account, bytes32 role);
error AddressIsZero();
error AssetMismatch();
error NothingHarvested();
/*/////////////////////////////////////////////////////////////
MODIFIERS
/////////////////////////////////////////////////////////////*/
modifier onlyRole(bytes32 role_) {
_requireRole(role_);
_;
}
/*/////////////////////////////////////////////////////////////
FUNCTIONS
/////////////////////////////////////////////////////////////*/
/// @param peggedToken_ Pegged token
/// @param yieldDistributor_ Yield distributor (its asset must be `peggedToken_`)
constructor(IPeggedToken peggedToken_, IYieldDistributor yieldDistributor_) {
if (address(peggedToken_) == address(0) || address(yieldDistributor_) == address(0)) revert AddressIsZero();
if (address(yieldDistributor_.asset()) != address(peggedToken_)) revert AssetMismatch();
PEGGED_TOKEN = peggedToken_;
YIELD_DISTRIBUTOR = yieldDistributor_;
}
/*/////////////////////////////////////////////////////////////
EXTERNAL FUNCTIONS
/////////////////////////////////////////////////////////////*/
/**
* @notice KEEPER_ROLE: Harvest treasury excess payable in `token_`, mint pegged tokens by re-depositing
* it through the Gateway, and distribute the minted amount as staker yield.
* @dev Compute `minPeggedTokenOut_` off-chain (e.g. eth_call-simulate this function); deriving it
* on-chain from `previewDeposit` is circular and never reverts. Keeper-gated for timing: each
* `distribute` re-spreads remaining yield over a fresh period, so an open call could stretch the drip.
* @param token_ Whitelisted collateral token to harvest the excess in
* @param minPeggedTokenOut_ Minimum pegged tokens the Gateway mint must produce
* @return _distributed Amount of pegged tokens sent to the YieldDistributor
*/
function harvestAndDistribute(address token_, uint256 minPeggedTokenOut_)
external
nonReentrant
onlyRole(KEEPER_ROLE)
returns (uint256 _distributed)
{
uint256 _harvested = treasury().harvest(token_, address(this));
if (_harvested == 0) revert NothingHarvested();
IGateway _gateway = gateway();
IERC20(token_).forceApprove(address(_gateway), _harvested);
_gateway.deposit(token_, _harvested, minPeggedTokenOut_, address(this));
_distributed = PEGGED_TOKEN.balanceOf(address(this));
if (_distributed == 0) revert NothingHarvested();
PEGGED_TOKEN.forceApprove(address(YIELD_DISTRIBUTOR), _distributed);
YIELD_DISTRIBUTOR.distribute(_distributed);
emit HarvestedAndDistributed(token_, _harvested, _distributed);
}
/**
* @notice DEFAULT_ADMIN_ROLE: Sweep tokens accidentally sent to this contract.
* @param token_ Token to sweep
* @param receiver_ Address to receive the swept tokens
*/
function sweep(address token_, address receiver_) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (receiver_ == address(0)) revert AddressIsZero();
uint256 _amount = IERC20(token_).balanceOf(address(this));
IERC20(token_).safeTransfer(receiver_, _amount);
emit Swept(token_, _amount, receiver_);
}
/*/////////////////////////////////////////////////////////////
EXTERNAL/PUBLIC VIEW FUNCTIONS
/////////////////////////////////////////////////////////////*/
/// @notice Returns the gateway
function gateway() public view returns (IGateway) {
return IGateway(PEGGED_TOKEN.gateway());
}
/**
* @notice The yield available to harvest, i.e. the excess of the treasury reserve over
* the pegged token's backed supply: `reserve - (totalSupply - amoSupply)`.
* @dev Reverts if any whitelisted token's oracle is stale or out of tolerance.
* @return _excessPegged Harvestable excess in pegged token units, or 0 if none.
*/
function harvestable() public view returns (uint256 _excessPegged) {
uint256 _backedSupply = PEGGED_TOKEN.totalSupply() - gateway().amoSupply();
uint256 _reserve = treasury().reserve();
return _reserve > _backedSupply ? _reserve - _backedSupply : 0;
}
/// @notice Returns the treasury
function treasury() public view returns (ITreasury) {
return ITreasury(PEGGED_TOKEN.treasury());
}
/*/////////////////////////////////////////////////////////////
PRIVATE FUNCTIONS
/////////////////////////////////////////////////////////////*/
/// @dev Reverts unless `msg.sender` holds `role_` on the Treasury
function _requireRole(bytes32 role_) private view {
if (!treasury().hasRole(role_, msg.sender)) {
revert AccessControlUnauthorizedAccount(msg.sender, role_);
}
}
}
@openzeppelin/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);
}
@openzeppelin/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";
@openzeppelin/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";
@openzeppelin/contracts/interfaces/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
@openzeppelin/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);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/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";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.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 Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
bytes4 selector = IERC20Metadata.decimals.selector;
assembly ("memory-safe") {
mstore(0x00, selector)
success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
decimals := mul(success, mload(0x00))
}
}
/**
* @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)
}
}
}
@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*
* @custom:stateless
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @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, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
_reentrancyGuardStorageSlot().asBoolean().tstore(false);
}
/**
* @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().asBoolean().tload();
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
@openzeppelin/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represents a slot holding an address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
@openzeppelin/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);
}
src/interfaces/IGateway.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {IPeggedToken} from "./IPeggedToken.sol";
/// @title IGateway - Interface for PeggedToken Gateway
interface IGateway {
/// @notice Adds address to instant redeem whitelist
/// @param account_ Address to whitelist
function addToInstantRedeemWhitelist(address account_) external;
/// @notice Returns current AMO mint limit above reserve
function amoMintLimit() external view returns (uint256);
/// @notice Returns current AMO-minted supply tracked by treasury
function amoSupply() external view returns (uint256);
/// @notice Burns AMO-minted PeggedToken to reduce AMO supply
/// @param amount_ Amount of PeggedToken to burn
function burnFromAMO(uint256 amount_) external;
/// @notice Cancels redeem request and returns locked peggedToken to user
function cancelRedeemRequest() external;
/// @notice Deposits tokens to receive PeggedToken
/// @param tokenIn_ Token to deposit
/// @param amountIn_ Amount of tokens to deposit
/// @param minPeggedTokenOut_ Minimum PeggedToken to receive
/// @param receiver_ Address to receive the PeggedToken
/// @return Amount of PeggedToken minted
function deposit(address tokenIn_, uint256 amountIn_, uint256 minPeggedTokenOut_, address receiver_)
external
returns (uint256);
/// @notice Gets all whitelisted addresses
/// @return Array of whitelisted addresses
function getInstantRedeemWhitelist() external view returns (address[] memory);
/// @notice Gets redeem request details for a user
/// @param user_ User address
/// @return amountLocked Amount of peggedToken locked in Gateway contract
/// @return claimableAt Timestamp when request can be claimed
function getRedeemRequest(address user_) external view returns (uint256 amountLocked, uint256 claimableAt);
/// @notice Checks if address is whitelisted for instant redeem/withdraw
/// @param account_ Address to check
/// @return True if whitelisted
function isInstantRedeemWhitelisted(address account_) external view returns (bool);
/// @notice Returns remaining AMO mint capacity
function maxAmoMint() external view returns (uint256);
/// @notice Returns maximum deposit amount possible
function maxDeposit() external pure returns (uint256);
/// @notice Returns remaining mint capacity
function maxMint() external view returns (uint256);
/// @notice Returns maximum PeggedToken amount owner can redeem
/// @param owner_ Address to check redeem limit for
function maxRedeem(address owner_) external view returns (uint256);
/// @notice Returns maximum token amount that can be withdrawn
/// @param tokenOut_ Token to withdraw
function maxWithdraw(address tokenOut_) external view returns (uint256);
/// @notice Mints exact PeggedToken amount by depositing tokens
/// @param tokenIn_ Token to deposit
/// @param peggedTokenOut_ Exact PeggedToken amount to mint
/// @param maxAmountIn_ Maximum tokens to deposit
/// @param receiver_ Address to receive the PeggedToken
/// @return Amount of tokens deposited
function mint(address tokenIn_, uint256 peggedTokenOut_, uint256 maxAmountIn_, address receiver_)
external
returns (uint256);
/// @notice Gets the mint fee for a specific token
/// @param token_ Token address
/// @return The mint fee in BPS
function mintFee(address token_) external view returns (uint256);
/// @notice Returns current mint limit in PeggedToken
function mintLimit() external view returns (uint256);
/// @notice Mints PeggedToken to AMO operations (UMM role)
/// @param amount_ Amount of PeggedToken to mint
/// @param receiver_ Address to receive the minted PeggedToken
function mintToAMO(uint256 amount_, address receiver_) external;
// solhint-disable-next-line func-name-mixedcase
function NAME() external view returns (string memory);
/// @notice Returns contract owner address
function owner() external view returns (address);
/// @notice Returns PeggedToken token contract
// solhint-disable-next-line func-name-mixedcase
function PEGGED_TOKEN() external view returns (IPeggedToken);
/// @notice Simulates deposit of tokens for PeggedToken
/// @param tokenIn_ Token to deposit
/// @param amountIn_ Amount of tokens to deposit
/// @return _peggedTokenOut Expected PeggedToken output
function previewDeposit(address tokenIn_, uint256 amountIn_) external view returns (uint256 _peggedTokenOut);
/// @notice Simulates minting exact PeggedToken amount
/// @param tokenIn_ Token to deposit
/// @param peggedTokenOut_ PeggedToken amount to mint
/// @return _amountIn Required token input
function previewMint(address tokenIn_, uint256 peggedTokenOut_) external view returns (uint256 _amountIn);
/// @notice Simulates redeeming PeggedToken for tokens
/// @param tokenOut_ Token to receive
/// @param peggedTokenIn_ PeggedToken amount to redeem
/// @return _amountOut Expected token output
function previewRedeem(address tokenOut_, uint256 peggedTokenIn_) external view returns (uint256 _amountOut);
/// @notice Simulates withdrawing exact token amount
/// @param tokenOut_ Token to withdraw
/// @param amountOut_ Token amount to withdraw
/// @return _peggedTokenIn Required PeggedToken input
function previewWithdraw(address tokenOut_, uint256 amountOut_) external view returns (uint256 _peggedTokenIn);
/// @notice Redeems PeggedToken for exact token amount
/// @param tokenOut_ Token to receive
/// @param peggedTokenIn_ PeggedToken amount to burn
/// @param minAmountOut_ Minimum tokens to receive
/// @param receiver_ Address to receive the tokens
/// @return Amount of tokens received
function redeem(address tokenOut_, uint256 peggedTokenIn_, uint256 minAmountOut_, address receiver_)
external
returns (uint256);
/// @notice Gets the redeem fee for a specific token
/// @param token_ Token address
/// @return The redeem fee in BPS
function redeemFee(address token_) external view returns (uint256);
/// @notice Removes address from instant redeem whitelist
/// @param account_ Address to remove from whitelist
function removeFromInstantRedeemWhitelist(address account_) external;
/// @notice Requests a redeem with delay period (locks peggedToken in contract)
/// @param peggedTokenAmount_ Amount of peggedToken to lock in request
function requestRedeem(uint256 peggedTokenAmount_) external;
/// @notice Sets the withdrawal delay feature enabled or disabled
/// @param enabled_ The intended state for withdrawal delay
function setWithdrawalDelayEnabled(bool enabled_) external;
/// @notice Returns treasury contract address
function treasury() external view returns (address);
/// @notice Updates the AMO mint limit
/// @param newAmoMintLimit_ New limit value
function updateAmoMintLimit(uint256 newAmoMintLimit_) external;
/// @notice Updates the mint fee for a specific token
/// @param token_ Token address
/// @param newMintFee_ New fee in basis points (1 = 0.01%)
function updateMintFee(address token_, uint256 newMintFee_) external;
/// @notice Updates the maximum mint limit
/// @param newMintLimit_ New maximum mint limit in PeggedToken
function updateMintLimit(uint256 newMintLimit_) external;
/// @notice Updates the redeem fee for a specific token
/// @param token_ Token address
/// @param newRedeemFee_ New fee in basis points (1 = 0.01%)
function updateRedeemFee(address token_, uint256 newRedeemFee_) external;
/// @notice Updates the withdrawal delay period
/// @param newDelay_ New delay period in seconds
function updateWithdrawalDelay(uint256 newDelay_) external;
/// @notice Withdraws exact token amount by burning PeggedToken
/// @param tokenOut_ Token to receive
/// @param amountOut_ Exact token amount to receive
/// @param maxPeggedTokenIn_ Maximum PeggedToken to burn
/// @param receiver_ Address to receive the tokens
/// @return Amount of PeggedToken burnt
function withdraw(address tokenOut_, uint256 amountOut_, uint256 maxPeggedTokenIn_, address receiver_)
external
returns (uint256);
/// @notice Returns withdrawal delay period in seconds
function withdrawalDelay() external view returns (uint256);
/// @notice Returns withdrawal delay enabled status
function withdrawalDelayEnabled() external view returns (bool);
}
src/interfaces/IPeggedToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
/// @title IPeggedToken - Interface for PeggedToken stablecoin
interface IPeggedToken is IERC20 {
function addToBlacklist(address account_) external;
function burnFrom(address account_, uint256 amount_) external;
function gateway() external view returns (address _gateway);
function getBlacklistedAddresses() external view returns (address[] memory);
function isBlacklisted(address account_) external view returns (bool);
function mint(address account_, uint256 amount_) external;
function removeFromBlacklist(address account_) external;
function treasury() external view returns (address _treasury);
function updateGateway(address newGateway_) external;
function updateTreasury(address newTreasury_) external;
}
src/interfaces/ITreasury.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {IPeggedToken} from "./IPeggedToken.sol";
/// @title ITreasury - Interface for PeggedToken Treasury
/// @dev hasRole(), DEFAULT_ADMIN_ROLE(), and getRoleAdmin() are inherited from AccessControl via
/// AccessControlDefaultAdminRules and therefore not repeated here.
interface ITreasury {
function addToWhitelist(address token_, address vault_, address oracle_, uint256 stalePeriod_) external;
function deposit(address token_, uint256 amount_) external;
function gateway() external view returns (address);
function getPrice(address token_) external view returns (uint256 _latestPrice, uint256 _unitPrice);
function harvest(address token_, address receiver_) external returns (uint256);
function hasRole(bytes32 role, address account) external view returns (bool);
function isWhitelistedToken(address token_) external view returns (bool);
// solhint-disable-next-line func-name-mixedcase
function MAINTAINER_ROLE() external view returns (bytes32);
function migrate(address newTreasury_) external;
function owner() external view returns (address);
// solhint-disable-next-line func-name-mixedcase
function PEGGED_TOKEN() external view returns (IPeggedToken);
function priceTolerance() external view returns (uint256);
function pull(address token_, uint256 amount_) external;
function push(address token_, uint256 amount_) external;
function removeFromWhitelist(address token_) external;
function reserve() external view returns (uint256 _reserve);
function setDepositActive(address token_, bool active_) external;
function setWithdrawActive(address token_, bool active_) external;
function swap(address tokenIn_, address tokenOut_, uint256 amountIn_, uint256 minAmountOut_)
external
returns (uint256);
function sweep(address fromToken_, address receiver_) external;
// solhint-disable-next-line func-name-mixedcase
function UMM_ROLE() external view returns (bytes32);
function updateOracle(address token_, address oracle_, uint256 newStalePeriod_) external;
function updatePriceTolerance(uint256 newPriceTolerance_) external;
function updateSwapper(address swapper_) external;
function whitelistedTokens() external view returns (address[] memory);
function withdraw(address token_, uint256 amount_, address tokenReceiver_) external;
function withdrawable(address token_) external view returns (uint256);
}
src/interfaces/IYieldDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
/**
* @title IYieldDistributor
* @notice Interface for the YieldDistributor contract
*/
interface IYieldDistributor {
/// @notice Get the asset token
/// @return The asset token
function asset() external view returns (IERC20);
/// @notice Distribute yield to the vault over the yield duration
/// @param amount_ The amount of yield to distribute
function distribute(uint256 amount_) external;
/// @notice Get the last update timestamp
/// @return The timestamp of last yield pull
function lastUpdateTime() external view returns (uint256);
/// @notice Get pending yield available to pull
/// @return The amount of pending yield
function pendingYield() external view returns (uint256);
/// @notice Get the period finish timestamp
/// @return The timestamp when current distribution ends
function periodFinish() external view returns (uint256);
/// @notice Pull accrued yield to the vault
/// @return amount The amount of yield pulled
function pullYield() external returns (uint256 amount);
/// @notice Rescue tokens accidentally sent to the contract
/// @param token_ The token to rescue
/// @param to_ The address to send the tokens to
/// @param amount_ The amount to rescue
function rescueTokens(address token_, address to_, uint256 amount_) external;
/// @notice Get the current reward rate
/// @return The reward rate (tokens per second, scaled by 1e18)
function rewardRate() external view returns (uint256);
/// @notice Update the yield duration period
/// @param duration_ The new yield duration in seconds
function updateYieldDuration(uint256 duration_) external;
/// @notice Get the vault address
/// @return The vault address
function vault() external view returns (address);
/// @notice Get the yield duration period
/// @return The yield duration in seconds
function yieldDuration() external view returns (uint256);
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.