// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
import {FixedPointMathLib} from "../utils/FixedPointMathLib.sol";
/// @notice Minimal ERC4626 tokenized Vault implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/mixins/ERC4626.sol)
abstract contract ERC4626 is ERC20 {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/*//////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
ERC20 public immutable asset;
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol, _asset.decimals()) {
asset = _asset;
}
/*//////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
//////////////////////////////////////////////////////////////*/
function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {
// Check for rounding error since we round down in previewDeposit.
require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES");
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {
assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function withdraw(
uint256 assets,
address receiver,
address owner
) public virtual returns (uint256 shares) {
shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
function redeem(
uint256 shares,
address receiver,
address owner
) public virtual returns (uint256 assets) {
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
// Check for rounding error since we round down in previewRedeem.
require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS");
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
/*//////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
function totalAssets() public view virtual returns (uint256);
function convertToShares(uint256 assets) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());
}
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
}
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return convertToShares(assets);
}
function previewMint(uint256 shares) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);
}
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());
}
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return convertToAssets(shares);
}
/*//////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LIMIT LOGIC
//////////////////////////////////////////////////////////////*/
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxWithdraw(address owner) public view virtual returns (uint256) {
return convertToAssets(balanceOf[owner]);
}
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf[owner];
}
/*//////////////////////////////////////////////////////////////
INTERNAL HOOKS LOGIC
//////////////////////////////////////////////////////////////*/
function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
function afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/*//////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
uint256 internal constant MAX_UINT256 = 2**256 - 1;
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
/*//////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
revert(0, 0)
}
// Divide x * y by the denominator.
z := div(mul(x, y), denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
revert(0, 0)
}
// If x * y modulo the denominator is strictly greater than 0,
// 1 is added to round up the division of x * y by the denominator.
z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
}
}
function rpow(
uint256 x,
uint256 n,
uint256 scalar
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := scalar
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store scalar in z for now.
z := scalar
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, scalar)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, scalar)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, scalar)
}
}
}
}
}
/*//////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let y := x // We start y at x, which will help us make our initial estimate.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// We check y >= 2^(k + 8) but shift right by k bits
// each branch to ensure that if x >= 256, then y >= 256.
if iszero(lt(y, 0x10000000000000000000000000000000000)) {
y := shr(128, y)
z := shl(64, z)
}
if iszero(lt(y, 0x1000000000000000000)) {
y := shr(64, y)
z := shl(32, z)
}
if iszero(lt(y, 0x10000000000)) {
y := shr(32, y)
z := shl(16, z)
}
if iszero(lt(y, 0x1000000)) {
y := shr(16, y)
z := shl(8, z)
}
// Goal was to get z*z*y within a small factor of x. More iterations could
// get y in a tighter range. Currently, we will have y in [256, 256*2^16).
// We ensured y >= 256 so that the relative difference between y and y+1 is small.
// That's not possible if x < 256 but we can just verify those cases exhaustively.
// Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
// Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
// Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.
// For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
// (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.
// Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
// sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.
// There is no overflow risk here since y < 2^136 after the first branch above.
z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If x+1 is a perfect square, the Babylonian method cycles between
// floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
// Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
// If you don't care whether the floor or ceil square root is returned, you can remove this statement.
z := sub(z, lt(div(x, z), z))
}
}
function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Mod x by y. Note this will return
// 0 instead of reverting if y is zero.
z := mod(x, y)
}
}
function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
// Divide x by y. Note this will return
// 0 instead of reverting if y is zero.
r := div(x, y)
}
}
function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Add 1 to x * y if x % y > 0. Note this will
// return 0 instead of reverting if y is zero.
z := add(gt(mod(x, y), 0), div(x, y))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (type(uint256).max - denominator + 1) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
unchecked {
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.0;
import {ERC20} from "solmate/tokens/ERC20.sol";
import {IBondAuctioneer} from "../interfaces/IBondAuctioneer.sol";
import {IBondTeller} from "../interfaces/IBondTeller.sol";
interface IBondAggregator {
/// @notice Register a auctioneer with the aggregator
/// @notice Only Guardian
/// @param auctioneer_ Address of the Auctioneer to register
/// @dev A auctioneer must be registered with an aggregator to create markets
function registerAuctioneer(IBondAuctioneer auctioneer_) external;
/// @notice Register a new market with the aggregator
/// @notice Only registered depositories
/// @param payoutToken_ Token to be paid out by the market
/// @param quoteToken_ Token to be accepted by the market
/// @param marketId ID of the market being created
function registerMarket(
ERC20 payoutToken_,
ERC20 quoteToken_
) external returns (uint256 marketId);
/// @notice Get the auctioneer for the provided market ID
/// @param id_ ID of Market
function getAuctioneer(uint256 id_) external view returns (IBondAuctioneer);
/// @notice Calculate current market price of payout token in quote tokens
/// @dev Accounts for debt and control variable decay since last deposit (vs _marketPrice())
/// @param id_ ID of market
/// @return Price for market (see the specific auctioneer for units)
//
// if price is below minimum price, minimum price is returned
// this is enforced on deposits by manipulating total debt (see _decay())
function marketPrice(uint256 id_) external view returns (uint256);
/// @notice Scale value to use when converting between quote token and payout token amounts with marketPrice()
/// @param id_ ID of market
/// @return Scaling factor for market in configured decimals
function marketScale(uint256 id_) external view returns (uint256);
/// @notice Payout due for amount of quote tokens
/// @dev Accounts for debt and control variable decay so it is up to date
/// @param amount_ Amount of quote tokens to spend
/// @param id_ ID of market
/// @param referrer_ Address of referrer, used to get fees to calculate accurate payout amount.
/// Inputting the zero address will take into account just the protocol fee.
/// @return amount of payout tokens to be paid
function payoutFor(
uint256 amount_,
uint256 id_,
address referrer_
) external view returns (uint256);
/// @notice Returns maximum amount of quote token accepted by the market
/// @param id_ ID of market
/// @param referrer_ Address of referrer, used to get fees to calculate accurate payout amount.
/// Inputting the zero address will take into account just the protocol fee.
function maxAmountAccepted(uint256 id_, address referrer_) external view returns (uint256);
/// @notice Does market send payout immediately
/// @param id_ Market ID to search for
function isInstantSwap(uint256 id_) external view returns (bool);
/// @notice Is a given market accepting deposits
/// @param id_ ID of market
function isLive(uint256 id_) external view returns (bool);
/// @notice Returns array of active market IDs within a range
/// @dev Should be used if length exceeds max to query entire array
function liveMarketsBetween(
uint256 firstIndex_,
uint256 lastIndex_
) external view returns (uint256[] memory);
/// @notice Returns an array of all active market IDs for a given quote token
/// @param token_ Address of token to query by
/// @param isPayout_ If true, search by payout token, else search for quote token
function liveMarketsFor(
address token_,
bool isPayout_
) external view returns (uint256[] memory);
/// @notice Returns an array of all active market IDs for a given owner
/// @param owner_ Address of owner to query by
/// @param firstIndex_ Market ID to start at
/// @param lastIndex_ Market ID to end at (non-inclusive)
function liveMarketsBy(
address owner_,
uint256 firstIndex_,
uint256 lastIndex_
) external view returns (uint256[] memory);
/// @notice Returns an array of all active market IDs for a given payout and quote token
/// @param payout_ Address of payout token
/// @param quote_ Address of quote token
function marketsFor(address payout_, address quote_) external view returns (uint256[] memory);
/// @notice Returns the market ID with the highest current payoutToken payout for depositing quoteToken
/// @param payout_ Address of payout token
/// @param quote_ Address of quote token
/// @param amountIn_ Amount of quote tokens to deposit
/// @param minAmountOut_ Minimum amount of payout tokens to receive as payout
/// @param maxExpiry_ Latest acceptable vesting timestamp for bond
/// Inputting the zero address will take into account just the protocol fee.
function findMarketFor(
address payout_,
address quote_,
uint256 amountIn_,
uint256 minAmountOut_,
uint256 maxExpiry_
) external view returns (uint256 id);
/// @notice Returns the Teller that services the market ID
function getTeller(uint256 id_) external view returns (IBondTeller);
/// @notice Returns current capacity of a market
function currentCapacity(uint256 id_) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.0;
import {ERC20} from "solmate/tokens/ERC20.sol";
import {IBondTeller} from "../interfaces/IBondTeller.sol";
import {IBondAggregator} from "../interfaces/IBondAggregator.sol";
interface IBondAuctioneer {
/// @notice Creates a new bond market
/// @param params_ Configuration data needed for market creation, encoded in a bytes array
/// @dev See specific auctioneer implementations for details on encoding the parameters.
/// @return id ID of new bond market
function createMarket(bytes memory params_) external returns (uint256);
/// @notice Disable existing bond market
/// @notice Must be market owner
/// @param id_ ID of market to close
function closeMarket(uint256 id_) external;
/// @notice Exchange quote tokens for a bond in a specified market
/// @notice Must be teller
/// @param id_ ID of the Market the bond is being purchased from
/// @param amount_ Amount to deposit in exchange for bond (after fee has been deducted)
/// @param minAmountOut_ Minimum acceptable amount of bond to receive. Prevents frontrunning
/// @return payout Amount of payout token to be received from the bond
function purchaseBond(
uint256 id_,
uint256 amount_,
uint256 minAmountOut_
) external returns (uint256 payout);
/// @notice Set market intervals to different values than the defaults
/// @notice Must be market owner
/// @dev Changing the intervals could cause markets to behave in unexpected way
/// tuneInterval should be greater than tuneAdjustmentDelay
/// @param id_ Market ID
/// @param intervals_ Array of intervals (3)
/// 1. Tune interval - Frequency of tuning
/// 2. Tune adjustment delay - Time to implement downward tuning adjustments
/// 3. Debt decay interval - Interval over which debt should decay completely
function setIntervals(uint256 id_, uint32[3] calldata intervals_) external;
/// @notice Designate a new owner of a market
/// @notice Must be market owner
/// @dev Doesn't change permissions until newOwner calls pullOwnership
/// @param id_ Market ID
/// @param newOwner_ New address to give ownership to
function pushOwnership(uint256 id_, address newOwner_) external;
/// @notice Accept ownership of a market
/// @notice Must be market newOwner
/// @dev The existing owner must call pushOwnership prior to the newOwner calling this function
/// @param id_ Market ID
function pullOwnership(uint256 id_) external;
/// @notice Set the auctioneer defaults
/// @notice Must be policy
/// @param defaults_ Array of default values
/// 1. Tune interval - amount of time between tuning adjustments
/// 2. Tune adjustment delay - amount of time to apply downward tuning adjustments
/// 3. Minimum debt decay interval - minimum amount of time to let debt decay to zero
/// 4. Minimum deposit interval - minimum amount of time to wait between deposits
/// 5. Minimum market duration - minimum amount of time a market can be created for
/// 6. Minimum debt buffer - the minimum amount of debt over the initial debt to trigger a market shutdown
/// @dev The defaults set here are important to avoid edge cases in market behavior, e.g. a very short market reacts doesn't tune well
/// @dev Only applies to new markets that are created after the change
function setDefaults(uint32[6] memory defaults_) external;
/// @notice Change the status of the auctioneer to allow creation of new markets
/// @dev Setting to false and allowing active markets to end will sunset the auctioneer
/// @param status_ Allow market creation (true) : Disallow market creation (false)
function setAllowNewMarkets(bool status_) external;
/// @notice Change whether a market creator is allowed to use a callback address in their markets or not
/// @notice Must be guardian
/// @dev Callback is believed to be safe, but a whitelist is implemented to prevent abuse
/// @param creator_ Address of market creator
/// @param status_ Allow callback (true) : Disallow callback (false)
function setCallbackAuthStatus(address creator_, bool status_) external;
/* ========== VIEW FUNCTIONS ========== */
/// @notice Provides information for the Teller to execute purchases on a Market
/// @param id_ Market ID
/// @return owner Address of the market owner (tokens transferred from this address if no callback)
/// @return callbackAddr Address of the callback contract to get tokens for payouts
/// @return payoutToken Payout Token (token paid out) for the Market
/// @return quoteToken Quote Token (token received) for the Market
/// @return vesting Timestamp or duration for vesting, implementation-dependent
/// @return maxPayout Maximum amount of payout tokens you can purchase in one transaction
function getMarketInfoForPurchase(
uint256 id_
)
external
view
returns (
address owner,
address callbackAddr,
ERC20 payoutToken,
ERC20 quoteToken,
uint48 vesting,
uint256 maxPayout
);
/// @notice Calculate current market price of payout token in quote tokens
/// @param id_ ID of market
/// @return Price for market in configured decimals
//
// if price is below minimum price, minimum price is returned
function marketPrice(uint256 id_) external view returns (uint256);
/// @notice Scale value to use when converting between quote token and payout token amounts with marketPrice()
/// @param id_ ID of market
/// @return Scaling factor for market in configured decimals
function marketScale(uint256 id_) external view returns (uint256);
/// @notice Payout due for amount of quote tokens
/// @dev Accounts for debt and control variable decay so it is up to date
/// @param amount_ Amount of quote tokens to spend
/// @param id_ ID of market
/// @param referrer_ Address of referrer, used to get fees to calculate accurate payout amount.
/// Inputting the zero address will take into account just the protocol fee.
/// @return amount of payout tokens to be paid
function payoutFor(
uint256 amount_,
uint256 id_,
address referrer_
) external view returns (uint256);
/// @notice Returns maximum amount of quote token accepted by the market
/// @param id_ ID of market
/// @param referrer_ Address of referrer, used to get fees to calculate accurate payout amount.
/// Inputting the zero address will take into account just the protocol fee.
function maxAmountAccepted(uint256 id_, address referrer_) external view returns (uint256);
/// @notice Does market send payout immediately
/// @param id_ Market ID to search for
function isInstantSwap(uint256 id_) external view returns (bool);
/// @notice Is a given market accepting deposits
/// @param id_ ID of market
function isLive(uint256 id_) external view returns (bool);
/// @notice Returns the address of the market owner
/// @param id_ ID of market
function ownerOf(uint256 id_) external view returns (address);
/// @notice Returns the Teller that services the Auctioneer
function getTeller() external view returns (IBondTeller);
/// @notice Returns the Aggregator that services the Auctioneer
function getAggregator() external view returns (IBondAggregator);
/// @notice Returns current capacity of a market
function currentCapacity(uint256 id_) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.0;
import {ERC20} from "solmate/tokens/ERC20.sol";
import {IBondAuctioneer} from "../interfaces/IBondAuctioneer.sol";
interface IBondSDA is IBondAuctioneer {
/// @notice Main information pertaining to bond market
struct BondMarket {
address owner; // market owner. sends payout tokens, receives quote tokens (defaults to creator)
ERC20 payoutToken; // token to pay depositors with
ERC20 quoteToken; // token to accept as payment
address callbackAddr; // address to call for any operations on bond purchase. Must inherit to IBondCallback.
bool capacityInQuote; // capacity limit is in payment token (true) or in payout (false, default)
uint256 capacity; // capacity remaining
uint256 totalDebt; // total payout token debt from market
uint256 minPrice; // minimum price (hard floor for the market)
uint256 maxPayout; // max payout tokens out in one order
uint256 sold; // payout tokens out
uint256 purchased; // quote tokens in
uint256 scale; // scaling factor for the market (see MarketParams struct)
}
/// @notice Information used to control how a bond market changes
struct BondTerms {
uint256 controlVariable; // scaling variable for price
uint256 maxDebt; // max payout token debt accrued
uint48 vesting; // length of time from deposit to expiry if fixed-term, vesting timestamp if fixed-expiry
uint48 conclusion; // timestamp when market no longer offered
}
/// @notice Data needed for tuning bond market
/// @dev Durations are stored in uint32 (not int32) and timestamps are stored in uint48, so is not subject to Y2K38 overflow
struct BondMetadata {
uint48 lastTune; // last timestamp when control variable was tuned
uint48 lastDecay; // last timestamp when market was created and debt was decayed
uint32 length; // time from creation to conclusion.
uint32 depositInterval; // target frequency of deposits
uint32 tuneInterval; // frequency of tuning
uint32 tuneAdjustmentDelay; // time to implement downward tuning adjustments
uint32 debtDecayInterval; // interval over which debt should decay completely
uint256 tuneIntervalCapacity; // capacity expected to be used during a tuning interval
uint256 tuneBelowCapacity; // capacity that the next tuning will occur at
uint256 lastTuneDebt; // target debt calculated at last tuning
}
/// @notice Control variable adjustment data
struct Adjustment {
uint256 change;
uint48 lastAdjustment;
uint48 timeToAdjusted; // how long until adjustment happens
bool active;
}
/// @notice Parameters to create a new bond market
/// @dev Note price should be passed in a specific format:
/// formatted price = (payoutPriceCoefficient / quotePriceCoefficient)
/// * 10**(36 + scaleAdjustment + quoteDecimals - payoutDecimals + payoutPriceDecimals - quotePriceDecimals)
/// where:
/// payoutDecimals - Number of decimals defined for the payoutToken in its ERC20 contract
/// quoteDecimals - Number of decimals defined for the quoteToken in its ERC20 contract
/// payoutPriceCoefficient - The coefficient of the payoutToken price in scientific notation (also known as the significant digits)
/// payoutPriceDecimals - The significand of the payoutToken price in scientific notation (also known as the base ten exponent)
/// quotePriceCoefficient - The coefficient of the quoteToken price in scientific notation (also known as the significant digits)
/// quotePriceDecimals - The significand of the quoteToken price in scientific notation (also known as the base ten exponent)
/// scaleAdjustment - see below
/// * In the above definitions, the "prices" need to have the same unit of account (i.e. both in OHM, $, ETH, etc.)
/// If price is not provided in this format, the market will not behave as intended.
/// @param params_ Encoded bytes array, with the following elements
/// @dev 0. Payout Token (token paid out)
/// @dev 1. Quote Token (token to be received)
/// @dev 2. Callback contract address, should conform to IBondCallback. If 0x00, tokens will be transferred from market.owner
/// @dev 3. Is Capacity in Quote Token?
/// @dev 4. Capacity (amount in quoteDecimals or amount in payoutDecimals)
/// @dev 5. Formatted initial price (see note above)
/// @dev 6. Formatted minimum price (see note above)
/// @dev 7. Debt buffer. Percent with 3 decimals. Percentage over the initial debt to allow the market to accumulate at anyone time.
/// @dev Works as a circuit breaker for the market in case external conditions incentivize massive buying (e.g. stablecoin depeg).
/// @dev Minimum is the greater of 10% or initial max payout as a percentage of capacity.
/// @dev If the value is too small, the market will not be able function normally and close prematurely.
/// @dev If the value is too large, the market will not circuit break when intended. The value must be > 10% but can exceed 100% if desired.
/// @dev A good heuristic to calculate a debtBuffer with is to determine the amount of capacity that you think is reasonable to be expended
/// @dev in a short duration as a percent, e.g. 25%. Then a reasonable debtBuffer would be: 0.25 * 1e3 * decayInterval / marketDuration
/// @dev where decayInterval = max(3 days, 5 * depositInterval) and marketDuration = conclusion - creation time.
/// @dev 8. Is fixed term ? Vesting length (seconds) : Vesting expiry (timestamp).
/// @dev A 'vesting' param longer than 50 years is considered a timestamp for fixed expiry.
/// @dev 9. Conclusion (timestamp)
/// @dev 10. Deposit interval (seconds)
/// @dev 11. Market scaling factor adjustment, ranges from -24 to +24 within the configured market bounds.
/// @dev Should be calculated as: (payoutDecimals - quoteDecimals) - ((payoutPriceDecimals - quotePriceDecimals) / 2)
/// @dev Providing a scaling factor adjustment that doesn't follow this formula could lead to under or overflow errors in the market.
/// @return ID of new bond market
struct MarketParams {
ERC20 payoutToken;
ERC20 quoteToken;
address callbackAddr;
bool capacityInQuote;
uint256 capacity;
uint256 formattedInitialPrice;
uint256 formattedMinimumPrice;
uint32 debtBuffer;
uint48 vesting;
uint48 conclusion;
uint32 depositInterval;
int8 scaleAdjustment;
}
/* ========== VIEW FUNCTIONS ========== */
/// @notice Calculate current market price of payout token in quote tokens
/// @dev Accounts for debt and control variable decay since last deposit (vs _marketPrice())
/// @param id_ ID of market
/// @return Price for market in configured decimals (see MarketParams)
//
// price is derived from the equation
//
// p = c * d
//
// where
// p = price
// c = control variable
// d = debt
//
// d -= ( d * (dt / l) )
//
// where
// dt = change in time
// l = length of program
//
// if price is below minimum price, minimum price is returned
// this is enforced on deposits by manipulating total debt (see _decay())
function marketPrice(uint256 id_) external view override returns (uint256);
/// @notice Calculate debt factoring in decay
/// @dev Accounts for debt decay since last deposit
/// @param id_ ID of market
/// @return Current debt for market in payout token decimals
function currentDebt(uint256 id_) external view returns (uint256);
/// @notice Up to date control variable
/// @dev Accounts for control variable adjustment
/// @param id_ ID of market
/// @return Control variable for market in payout token decimals
function currentControlVariable(uint256 id_) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.0;
import {ERC20} from "solmate/tokens/ERC20.sol";
interface IBondTeller {
/// @notice Exchange quote tokens for a bond in a specified market
/// @param recipient_ Address of recipient of bond. Allows deposits for other addresses
/// @param referrer_ Address of referrer who will receive referral fee. For frontends to fill.
/// Direct calls can use the zero address for no referrer fee.
/// @param id_ ID of the Market the bond is being purchased from
/// @param amount_ Amount to deposit in exchange for bond
/// @param minAmountOut_ Minimum acceptable amount of bond to receive. Prevents frontrunning
/// @return Amount of payout token to be received from the bond
/// @return Timestamp at which the bond token can be redeemed for the underlying token
function purchase(
address recipient_,
address referrer_,
uint256 id_,
uint256 amount_,
uint256 minAmountOut_
) external returns (uint256, uint48);
/// @notice Get current fee charged by the teller based on the combined protocol and referrer fee
/// @param referrer_ Address of the referrer
/// @return Fee in basis points (3 decimal places)
function getFee(address referrer_) external view returns (uint48);
/// @notice Set protocol fee
/// @notice Must be guardian
/// @param fee_ Protocol fee in basis points (3 decimal places)
function setProtocolFee(uint48 fee_) external;
/// @notice Set the discount for creating bond tokens from the base protocol fee
/// @dev The discount is subtracted from the protocol fee to determine the fee
/// when using create() to mint bond tokens without using an Auctioneer
/// @param discount_ Create Fee Discount in basis points (3 decimal places)
function setCreateFeeDiscount(uint48 discount_) external;
/// @notice Set your fee as a referrer to the protocol
/// @notice Fee is set for sending address
/// @param fee_ Referrer fee in basis points (3 decimal places)
function setReferrerFee(uint48 fee_) external;
/// @notice Claim fees accrued by sender in the input tokens and sends them to the provided address
/// @param tokens_ Array of tokens to claim fees for
/// @param to_ Address to send fees to
function claimFees(ERC20[] memory tokens_, address to_) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
interface IYieldRepo {
// ========= CORE FUNCTIONS ========= //
/// @notice Triggers the yield repurchase facility functionality
/// Access controlled to the "heart" role
/// @dev Increments the epoch and triggers various actions depending on the new epoch number
/// When epoch == epochLength (21), withdraws the last week's yield and interest from the treasury
/// When epoch % 3 == 0 (once a day), triggers the creation of a bond market with the currently bid amount
/// Otherwise, does nothing.
/// The contract can be shutdown and this function will still work, but executes no logic.
function endEpoch() external;
/// ========== VIEWS ========== //
/// @notice Returns the current epoch
function epoch() external view returns (uint48);
/// @notice Returns whether the contract is shutdown
function isShutdown() external view returns (bool);
/// @notice Returns the current balance of yield generating reserves in the treasury and clearinghouse
function getReserveBalance() external view returns (uint256);
/// @notice Returns the next yield amount which is converted to the bid budget
/// @dev This value uses the current sDAI balance, but always assumes a week's worth of interest for the clearinghouse
/// Therefore, it's only accurate when called close to the end of the epoch
function getNextYield() external view returns (uint256);
/// @notice Returns the contract's OHM balance and the DAI balance to be returned for burning the OHM
/// @dev This computes a DAI amount using contract ohm balance and backing of 11.33 DAI
function getOhmBalanceAndBacking() external view returns (uint256, uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.15;
// ███████ █████ █████ █████ ██████ ██████ ███████████ █████ █████ █████████
// ███░░░░░███ ░░███ ░░███ ░░███ ░░██████ ██████ ░░███░░░░░███░░███ ░░███ ███░░░░░███
// ███ ░░███ ░███ ░░███ ███ ░███░█████░███ ░███ ░███ ░███ ░███ ░███ ░░░
// ░███ ░███ ░███ ░░█████ ░███░░███ ░███ ░██████████ ░███ ░███ ░░█████████
// ░███ ░███ ░███ ░░███ ░███ ░░░ ░███ ░███░░░░░░ ░███ ░███ ░░░░░░░░███
// ░░███ ███ ░███ █ ░███ ░███ ░███ ░███ ░███ ░███ ███ ░███
// ░░░███████░ ███████████ █████ █████ █████ █████ ░░████████ ░░█████████
// ░░░░░░░ ░░░░░░░░░░░ ░░░░░ ░░░░░ ░░░░░ ░░░░░ ░░░░░░░░ ░░░░░░░░░
//============================================================================================//
// GLOBAL TYPES //
//============================================================================================//
/// @notice Actions to trigger state changes in the kernel. Passed by the executor
enum Actions {
InstallModule,
UpgradeModule,
ActivatePolicy,
DeactivatePolicy,
ChangeExecutor,
MigrateKernel
}
/// @notice Used by executor to select an action and a target contract for a kernel action
struct Instruction {
Actions action;
address target;
}
/// @notice Used to define which module functions a policy needs access to
struct Permissions {
Keycode keycode;
bytes4 funcSelector;
}
type Keycode is bytes5;
//============================================================================================//
// UTIL FUNCTIONS //
//============================================================================================//
error TargetNotAContract(address target_);
error InvalidKeycode(Keycode keycode_);
// solhint-disable-next-line func-visibility
function toKeycode(bytes5 keycode_) pure returns (Keycode) {
return Keycode.wrap(keycode_);
}
// solhint-disable-next-line func-visibility
function fromKeycode(Keycode keycode_) pure returns (bytes5) {
return Keycode.unwrap(keycode_);
}
// solhint-disable-next-line func-visibility
function ensureContract(address target_) view {
if (target_.code.length == 0) revert TargetNotAContract(target_);
}
// solhint-disable-next-line func-visibility
function ensureValidKeycode(Keycode keycode_) pure {
bytes5 unwrapped = Keycode.unwrap(keycode_);
for (uint256 i = 0; i < 5; ) {
bytes1 char = unwrapped[i];
if (char < 0x41 || char > 0x5A) revert InvalidKeycode(keycode_); // A-Z only
unchecked {
i++;
}
}
}
//============================================================================================//
// COMPONENTS //
//============================================================================================//
/// @notice Generic adapter interface for kernel access in modules and policies.
abstract contract KernelAdapter {
error KernelAdapter_OnlyKernel(address caller_);
Kernel public kernel;
constructor(Kernel kernel_) {
kernel = kernel_;
}
/// @notice Modifier to restrict functions to be called only by kernel.
modifier onlyKernel() {
if (msg.sender != address(kernel)) revert KernelAdapter_OnlyKernel(msg.sender);
_;
}
/// @notice Function used by kernel when migrating to a new kernel.
function changeKernel(Kernel newKernel_) external onlyKernel {
kernel = newKernel_;
}
}
/// @notice Base level extension of the kernel. Modules act as independent state components to be
/// interacted with and mutated through policies.
/// @dev Modules are installed and uninstalled via the executor.
abstract contract Module is KernelAdapter {
error Module_PolicyNotPermitted(address policy_);
constructor(Kernel kernel_) KernelAdapter(kernel_) {}
/// @notice Modifier to restrict which policies have access to module functions.
modifier permissioned() {
if (
msg.sender == address(kernel) ||
!kernel.modulePermissions(KEYCODE(), Policy(msg.sender), msg.sig)
) revert Module_PolicyNotPermitted(msg.sender);
_;
}
/// @notice 5 byte identifier for a module.
function KEYCODE() public pure virtual returns (Keycode) {}
/// @notice Returns which semantic version of a module is being implemented.
/// @return major - Major version upgrade indicates breaking change to the interface.
/// @return minor - Minor version change retains backward-compatible interface.
function VERSION() external pure virtual returns (uint8 major, uint8 minor) {}
/// @notice Initialization function for the module
/// @dev This function is called when the module is installed or upgraded by the kernel.
/// @dev MUST BE GATED BY onlyKernel. Used to encompass any initialization or upgrade logic.
function INIT() external virtual onlyKernel {}
}
/// @notice Policies are application logic and external interface for the kernel and installed modules.
/// @dev Policies are activated and deactivated in the kernel by the executor.
/// @dev Module dependencies and function permissions must be defined in appropriate functions.
abstract contract Policy is KernelAdapter {
error Policy_ModuleDoesNotExist(Keycode keycode_);
error Policy_WrongModuleVersion(bytes expected_);
constructor(Kernel kernel_) KernelAdapter(kernel_) {}
/// @notice Easily accessible indicator for if a policy is activated or not.
function isActive() external view returns (bool) {
return kernel.isPolicyActive(this);
}
/// @notice Function to grab module address from a given keycode.
function getModuleAddress(Keycode keycode_) internal view returns (address) {
address moduleForKeycode = address(kernel.getModuleForKeycode(keycode_));
if (moduleForKeycode == address(0)) revert Policy_ModuleDoesNotExist(keycode_);
return moduleForKeycode;
}
/// @notice Define module dependencies for this policy.
/// @return dependencies - Keycode array of module dependencies.
function configureDependencies() external virtual returns (Keycode[] memory dependencies) {}
/// @notice Function called by kernel to set module function permissions.
/// @return requests - Array of keycodes and function selectors for requested permissions.
function requestPermissions() external view virtual returns (Permissions[] memory requests) {}
}
/// @notice Main contract that acts as a central component registry for the protocol.
/// @dev The kernel manages modules and policies. The kernel is mutated via predefined Actions,
/// @dev which are input from any address assigned as the executor. The executor can be changed as needed.
contract Kernel {
// ========= EVENTS ========= //
event PermissionsUpdated(
Keycode indexed keycode_,
Policy indexed policy_,
bytes4 funcSelector_,
bool granted_
);
event ActionExecuted(Actions indexed action_, address indexed target_);
// ========= ERRORS ========= //
error Kernel_OnlyExecutor(address caller_);
error Kernel_ModuleAlreadyInstalled(Keycode module_);
error Kernel_InvalidModuleUpgrade(Keycode module_);
error Kernel_PolicyAlreadyActivated(address policy_);
error Kernel_PolicyNotActivated(address policy_);
// ========= PRIVILEGED ADDRESSES ========= //
/// @notice Address that is able to initiate Actions in the kernel. Can be assigned to a multisig or governance contract.
address public executor;
// ========= MODULE MANAGEMENT ========= //
/// @notice Array of all modules currently installed.
Keycode[] public allKeycodes;
/// @notice Mapping of module address to keycode.
mapping(Keycode => Module) public getModuleForKeycode;
/// @notice Mapping of keycode to module address.
mapping(Module => Keycode) public getKeycodeForModule;
/// @notice Mapping of a keycode to all of its policy dependents. Used to efficiently reconfigure policy dependencies.
mapping(Keycode => Policy[]) public moduleDependents;
/// @notice Helper for module dependent arrays. Prevents the need to loop through array.
mapping(Keycode => mapping(Policy => uint256)) public getDependentIndex;
/// @notice Module <> Policy Permissions.
/// @dev Keycode -> Policy -> Function Selector -> bool for permission
mapping(Keycode => mapping(Policy => mapping(bytes4 => bool))) public modulePermissions;
// ========= POLICY MANAGEMENT ========= //
/// @notice List of all active policies
Policy[] public activePolicies;
/// @notice Helper to get active policy quickly. Prevents need to loop through array.
mapping(Policy => uint256) public getPolicyIndex;
//============================================================================================//
// CORE FUNCTIONS //
//============================================================================================//
constructor() {
executor = msg.sender;
}
/// @notice Modifier to check if caller is the executor.
modifier onlyExecutor() {
if (msg.sender != executor) revert Kernel_OnlyExecutor(msg.sender);
_;
}
function isPolicyActive(Policy policy_) public view returns (bool) {
return activePolicies.length > 0 && activePolicies[getPolicyIndex[policy_]] == policy_;
}
/// @notice Main kernel function. Initiates state changes to kernel depending on Action passed in.
function executeAction(Actions action_, address target_) external onlyExecutor {
if (action_ == Actions.InstallModule) {
ensureContract(target_);
ensureValidKeycode(Module(target_).KEYCODE());
_installModule(Module(target_));
} else if (action_ == Actions.UpgradeModule) {
ensureContract(target_);
ensureValidKeycode(Module(target_).KEYCODE());
_upgradeModule(Module(target_));
} else if (action_ == Actions.ActivatePolicy) {
ensureContract(target_);
_activatePolicy(Policy(target_));
} else if (action_ == Actions.DeactivatePolicy) {
ensureContract(target_);
_deactivatePolicy(Policy(target_));
} else if (action_ == Actions.ChangeExecutor) {
executor = target_;
} else if (action_ == Actions.MigrateKernel) {
ensureContract(target_);
_migrateKernel(Kernel(target_));
}
emit ActionExecuted(action_, target_);
}
function _installModule(Module newModule_) internal {
Keycode keycode = newModule_.KEYCODE();
if (address(getModuleForKeycode[keycode]) != address(0))
revert Kernel_ModuleAlreadyInstalled(keycode);
getModuleForKeycode[keycode] = newModule_;
getKeycodeForModule[newModule_] = keycode;
allKeycodes.push(keycode);
newModule_.INIT();
}
function _upgradeModule(Module newModule_) internal {
Keycode keycode = newModule_.KEYCODE();
Module oldModule = getModuleForKeycode[keycode];
if (address(oldModule) == address(0) || oldModule == newModule_)
revert Kernel_InvalidModuleUpgrade(keycode);
getKeycodeForModule[oldModule] = Keycode.wrap(bytes5(0));
getKeycodeForModule[newModule_] = keycode;
getModuleForKeycode[keycode] = newModule_;
newModule_.INIT();
_reconfigurePolicies(keycode);
}
function _activatePolicy(Policy policy_) internal {
if (isPolicyActive(policy_)) revert Kernel_PolicyAlreadyActivated(address(policy_));
// Add policy to list of active policies
activePolicies.push(policy_);
getPolicyIndex[policy_] = activePolicies.length - 1;
// Record module dependencies
Keycode[] memory dependencies = policy_.configureDependencies();
uint256 depLength = dependencies.length;
for (uint256 i; i < depLength; ) {
Keycode keycode = dependencies[i];
moduleDependents[keycode].push(policy_);
getDependentIndex[keycode][policy_] = moduleDependents[keycode].length - 1;
unchecked {
++i;
}
}
// Grant permissions for policy to access restricted module functions
Permissions[] memory requests = policy_.requestPermissions();
_setPolicyPermissions(policy_, requests, true);
}
function _deactivatePolicy(Policy policy_) internal {
if (!isPolicyActive(policy_)) revert Kernel_PolicyNotActivated(address(policy_));
// Revoke permissions
Permissions[] memory requests = policy_.requestPermissions();
_setPolicyPermissions(policy_, requests, false);
// Remove policy from all policy data structures
uint256 idx = getPolicyIndex[policy_];
Policy lastPolicy = activePolicies[activePolicies.length - 1];
activePolicies[idx] = lastPolicy;
activePolicies.pop();
getPolicyIndex[lastPolicy] = idx;
delete getPolicyIndex[policy_];
// Remove policy from module dependents
_pruneFromDependents(policy_);
}
/// @notice All functionality will move to the new kernel. WARNING: ACTION WILL BRICK THIS KERNEL.
/// @dev New kernel must add in all of the modules and policies via executeAction.
/// @dev NOTE: Data does not get cleared from this kernel.
function _migrateKernel(Kernel newKernel_) internal {
uint256 keycodeLen = allKeycodes.length;
for (uint256 i; i < keycodeLen; ) {
Module module = Module(getModuleForKeycode[allKeycodes[i]]);
module.changeKernel(newKernel_);
unchecked {
++i;
}
}
uint256 policiesLen = activePolicies.length;
for (uint256 j; j < policiesLen; ) {
Policy policy = activePolicies[j];
// Deactivate before changing kernel
policy.changeKernel(newKernel_);
unchecked {
++j;
}
}
}
function _reconfigurePolicies(Keycode keycode_) internal {
Policy[] memory dependents = moduleDependents[keycode_];
uint256 depLength = dependents.length;
for (uint256 i; i < depLength; ) {
dependents[i].configureDependencies();
unchecked {
++i;
}
}
}
function _setPolicyPermissions(
Policy policy_,
Permissions[] memory requests_,
bool grant_
) internal {
uint256 reqLength = requests_.length;
for (uint256 i = 0; i < reqLength; ) {
Permissions memory request = requests_[i];
modulePermissions[request.keycode][policy_][request.funcSelector] = grant_;
emit PermissionsUpdated(request.keycode, policy_, request.funcSelector, grant_);
unchecked {
++i;
}
}
}
function _pruneFromDependents(Policy policy_) internal {
Keycode[] memory dependencies = policy_.configureDependencies();
uint256 depcLength = dependencies.length;
for (uint256 i; i < depcLength; ) {
Keycode keycode = dependencies[i];
Policy[] storage dependents = moduleDependents[keycode];
uint256 origIndex = getDependentIndex[keycode][policy_];
Policy lastPolicy = dependents[dependents.length - 1];
// Swap with last and pop
dependents[origIndex] = lastPolicy;
dependents.pop();
// Record new index and delete deactivated policy index
getDependentIndex[keycode][lastPolicy] = origIndex;
delete getDependentIndex[keycode][policy_];
unchecked {
++i;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.15;
import {ROLESv1} from "src/modules/ROLES/ROLES.v1.sol";
import "src/Kernel.sol";
/// @notice Abstract contract to have the `onlyRole` modifier
/// @dev Inheriting this automatically makes ROLES module a dependency
abstract contract RolesConsumer {
ROLESv1 public ROLES;
modifier onlyRole(bytes32 role_) {
ROLES.requireRole(role_, msg.sender);
_;
}
}
/// @notice Module that holds multisig roles needed by various policies.
contract OlympusRoles is ROLESv1 {
//============================================================================================//
// MODULE SETUP //
//============================================================================================//
constructor(Kernel kernel_) Module(kernel_) {}
/// @inheritdoc Module
function KEYCODE() public pure override returns (Keycode) {
return toKeycode("ROLES");
}
/// @inheritdoc Module
function VERSION() external pure override returns (uint8 major, uint8 minor) {
major = 1;
minor = 0;
}
//============================================================================================//
// CORE FUNCTIONS //
//============================================================================================//
/// @inheritdoc ROLESv1
function saveRole(bytes32 role_, address addr_) external override permissioned {
if (hasRole[addr_][role_]) revert ROLES_AddressAlreadyHasRole(addr_, role_);
ensureValidRole(role_);
// Grant role to the address
hasRole[addr_][role_] = true;
emit RoleGranted(role_, addr_);
}
/// @inheritdoc ROLESv1
function removeRole(bytes32 role_, address addr_) external override permissioned {
if (!hasRole[addr_][role_]) revert ROLES_AddressDoesNotHaveRole(addr_, role_);
hasRole[addr_][role_] = false;
emit RoleRevoked(role_, addr_);
}
//============================================================================================//
// VIEW FUNCTIONS //
//============================================================================================//
/// @inheritdoc ROLESv1
function requireRole(bytes32 role_, address caller_) external view override {
if (!hasRole[caller_][role_]) revert ROLES_RequireRole(role_);
}
/// @inheritdoc ROLESv1
function ensureValidRole(bytes32 role_) public pure override {
for (uint256 i = 0; i < 32; ) {
bytes1 char = role_[i];
if ((char < 0x61 || char > 0x7A) && char != 0x5f && char != 0x00) {
revert ROLES_InvalidRole(role_); // a-z only
}
unchecked {
i++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.15;
import {AggregatorV2V3Interface} from "interfaces/AggregatorV2V3Interface.sol";
import "src/Kernel.sol";
/// @notice Price oracle data storage
/// @dev The Olympus Price Oracle contract provides a standard interface for OHM price data against a reserve asset.
/// It also implements a moving average price calculation (same as a TWAP) on the price feed data over a configured
/// duration and observation frequency. The data provided by this contract is used by the Olympus Range Operator to
/// perform market operations. The Olympus Price Oracle is updated each epoch by the Olympus Heart contract.
abstract contract PRICEv1 is Module {
// ========= EVENTS ========= //
event NewObservation(uint256 timestamp_, uint256 price_, uint256 movingAverage_);
event MovingAverageDurationChanged(uint48 movingAverageDuration_);
event ObservationFrequencyChanged(uint48 observationFrequency_);
event UpdateThresholdsChanged(uint48 ohmEthUpdateThreshold_, uint48 reserveEthUpdateThreshold_);
event MinimumTargetPriceChanged(uint256 minimumTargetPrice_);
// ========= ERRORS ========= //
error Price_InvalidParams();
error Price_NotInitialized();
error Price_AlreadyInitialized();
error Price_BadFeed(address priceFeed);
// ========= STATE ========= //
/// @dev Price feeds. Chainlink typically provides price feeds for an asset in ETH. Therefore, we use two price feeds against ETH, one for OHM and one for the Reserve asset, to calculate the relative price of OHM in the Reserve asset.
/// @dev Update thresholds are the maximum amount of time that can pass between price feed updates before the price oracle is considered stale. These should be set based on the parameters of the price feed.
/// @notice OHM/ETH price feed
AggregatorV2V3Interface public ohmEthPriceFeed;
/// @notice Maximum expected time between OHM/ETH price feed updates
uint48 public ohmEthUpdateThreshold;
/// @notice Reserve/ETH price feed
AggregatorV2V3Interface public reserveEthPriceFeed;
/// @notice Maximum expected time between OHM/ETH price feed updates
uint48 public reserveEthUpdateThreshold;
/// @notice Running sum of observations to calculate the moving average price from
/// @dev See getMovingAverage()
uint256 public cumulativeObs;
/// @notice Array of price observations. Check nextObsIndex to determine latest data point.
/// @dev Observations are stored in a ring buffer where the moving average is the sum of all observations divided by the number of observations.
/// Observations can be cleared by changing the movingAverageDuration or observationFrequency and must be re-initialized.
uint256[] public observations;
/// @notice Index of the next observation to make. The current value at this index is the oldest observation.
uint32 public nextObsIndex;
/// @notice Number of observations used in the moving average calculation. Computed from movingAverageDuration / observationFrequency.
uint32 public numObservations;
/// @notice Frequency (in seconds) that observations should be stored.
uint48 public observationFrequency;
/// @notice Duration (in seconds) over which the moving average is calculated.
uint48 public movingAverageDuration;
/// @notice Unix timestamp of last observation (in seconds).
uint48 public lastObservationTime;
/// @notice Whether the price module is initialized (and therefore active).
bool public initialized;
/// @notice Number of decimals in the price values provided by the contract.
uint8 public constant decimals = 18;
/// @notice Minimum target price for RBS system. Set manually to correspond to the liquid backing of OHM.
uint256 public minimumTargetPrice;
// ========= FUNCTIONS ========= //
/// @notice Trigger an update of the moving average. Permissioned.
/// @dev This function does not have a time-gating on the observationFrequency on this contract. It is set on the Heart policy contract.
/// The Heart beat frequency should be set to the same value as the observationFrequency.
function updateMovingAverage() external virtual;
/// @notice Initialize the price module
/// @notice Access restricted to activated policies
/// @param startObservations_ - Array of observations to initialize the moving average with. Must be of length numObservations.
/// @param lastObservationTime_ - Unix timestamp of last observation being provided (in seconds).
/// @dev This function must be called after the Price module is deployed to activate it and after updating the observationFrequency
/// or movingAverageDuration (in certain cases) in order for the Price module to function properly.
function initialize(
uint256[] memory startObservations_,
uint48 lastObservationTime_
) external virtual;
/// @notice Change the moving average window (duration)
/// @param movingAverageDuration_ - Moving average duration in seconds, must be a multiple of observation frequency
/// @dev Changing the moving average duration will erase the current observations array
/// and require the initialize function to be called again. Ensure that you have saved
/// the existing data and can re-populate before calling this function.
function changeMovingAverageDuration(uint48 movingAverageDuration_) external virtual;
/// @notice Change the observation frequency of the moving average (i.e. how often a new observation is taken)
/// @param observationFrequency_ - Observation frequency in seconds, must be a divisor of the moving average duration
/// @dev Changing the observation frequency clears existing observation data since it will not be taken at the right time intervals.
/// Ensure that you have saved the existing data and/or can re-populate before calling this function.
function changeObservationFrequency(uint48 observationFrequency_) external virtual;
/// @notice Change the update thresholds for the price feeds
/// @param ohmEthUpdateThreshold_ - Maximum allowed time between OHM/ETH price feed updates
/// @param reserveEthUpdateThreshold_ - Maximum allowed time between Reserve/ETH price feed updates
/// @dev The update thresholds should be set based on the update threshold of the chainlink oracles.
function changeUpdateThresholds(
uint48 ohmEthUpdateThreshold_,
uint48 reserveEthUpdateThreshold_
) external virtual;
/// @notice Change the minimum target price
/// @param minimumTargetPrice_ - Minimum target price for RBS system with 18 decimals, expressed as number of Reserve per OHM
/// @dev The minimum target price should be set based on the liquid backing of OHM.
function changeMinimumTargetPrice(uint256 minimumTargetPrice_) external virtual;
/// @notice Get the current price of OHM in the Reserve asset from the price feeds
function getCurrentPrice() external view virtual returns (uint256);
/// @notice Get the last stored price observation of OHM in the Reserve asset
function getLastPrice() external view virtual returns (uint256);
/// @notice Get the moving average of OHM in the Reserve asset over the defined window (see movingAverageDuration and observationFrequency).
function getMovingAverage() external view virtual returns (uint256);
/// @notice Get target price of OHM in the Reserve asset for the RBS system
/// @dev Returns the maximum of the moving average and the minimum target price
function getTargetPrice() external view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.15;
import {ERC20} from "solmate/tokens/ERC20.sol";
import "src/Kernel.sol";
abstract contract RANGEv2 is Module {
// ========= EVENTS ========= //
event WallUp(bool high_, uint256 timestamp_, uint256 capacity_);
event WallDown(bool high_, uint256 timestamp_, uint256 capacity_);
event CushionUp(bool high_, uint256 timestamp_, uint256 capacity_);
event CushionDown(bool high_, uint256 timestamp_);
event PricesChanged(
uint256 wallLowPrice_,
uint256 cushionLowPrice_,
uint256 cushionHighPrice_,
uint256 wallHighPrice_
);
event SpreadsChanged(bool high_, uint256 cushionSpread_, uint256 wallSpread_);
event ThresholdFactorChanged(uint256 thresholdFactor_);
// ========= ERRORS ========= //
error RANGE_InvalidParams();
// ========= STATE ========= //
struct Line {
uint256 price; // Price for the specified level
uint256 spread; // Spread of the level, percent with 2 decimal places (i.e. 1000 = 10% spread)
}
struct Side {
bool active; // Whether or not the side is active (i.e. the Operator is performing market operations on this side, true = active, false = inactive)
uint48 lastActive; // Unix timestamp when the side was last active (in seconds)
uint256 capacity; // Amount of tokens that can be used to defend the side of the range. Specified in OHM tokens on the high side and Reserve tokens on the low side.
uint256 threshold; // Minimum number of tokens required in capacity to maintain an active side. Specified in OHM tokens on the high side and Reserve tokens on the low side.
uint256 market; // Market ID of the cushion bond market for the side. If no market is active, the market ID is set to max uint256 value.
Line cushion; // Cushion data for the side
Line wall; // Wall data for the side
}
struct Range {
Side low; // Data specific to the low side of the range
Side high; // Data specific to the high side of the range
}
// Range data singleton. See range().
Range internal _range;
/// @notice Threshold factor for the change, a percent in 2 decimals (i.e. 1000 = 10%). Determines how much of the capacity must be spent before the side is taken down.
/// @dev A threshold is required so that a wall is not "active" with a capacity near zero, but unable to be depleted practically (dust).
uint256 public thresholdFactor;
/// @notice OHM token contract address
ERC20 public ohm;
/// @notice Reserve token contract address
ERC20 public reserve;
// ========= FUNCTIONS ========= //
/// @notice Update the capacity for a side of the range.
/// @notice Access restricted to activated policies.
/// @param high_ - Specifies the side of the range to update capacity for (true = high side, false = low side).
/// @param capacity_ - Amount to set the capacity to (OHM tokens for high side, Reserve tokens for low side).
function updateCapacity(bool high_, uint256 capacity_) external virtual;
/// @notice Update the prices for the low and high sides.
/// @notice Access restricted to activated policies.
/// @param target_ - Target price to set range prices from.
function updatePrices(uint256 target_) external virtual;
/// @notice Regenerate a side of the range to a specific capacity.
/// @notice Access restricted to activated policies.
/// @param high_ - Specifies the side of the range to regenerate (true = high side, false = low side).
/// @param capacity_ - Amount to set the capacity to (OHM tokens for high side, Reserve tokens for low side).
function regenerate(bool high_, uint256 capacity_) external virtual;
/// @notice Update the market ID (cushion) for a side of the range.
/// @notice Access restricted to activated policies.
/// @param high_ - Specifies the side of the range to update market for (true = high side, false = low side).
/// @param market_ - Market ID to set for the side.
/// @param marketCapacity_ - Amount to set the last market capacity to (OHM tokens for high side, Reserve tokens for low side).
function updateMarket(bool high_, uint256 market_, uint256 marketCapacity_) external virtual;
/// @notice Set the wall and cushion spreads.
/// @notice Access restricted to activated policies.
/// @param high_ - Specifies the side of the range to set spreads for (true = high side, false = low side).
/// @param cushionSpread_ - Percent spread to set the cushions at above/below the moving average, assumes 2 decimals (i.e. 1000 = 10%).
/// @param wallSpread_ - Percent spread to set the walls at above/below the moving average, assumes 2 decimals (i.e. 1000 = 10%).
/// @dev The new spreads will not go into effect until the next time updatePrices() is called.
function setSpreads(bool high_, uint256 cushionSpread_, uint256 wallSpread_) external virtual;
/// @notice Set the threshold factor for when a wall is considered "down".
/// @notice Access restricted to activated policies.
/// @param thresholdFactor_ - Percent of capacity that the wall should close below, assumes 2 decimals (i.e. 1000 = 10%).
/// @dev The new threshold factor will not go into effect until the next time regenerate() is called for each side of the wall.
function setThresholdFactor(uint256 thresholdFactor_) external virtual;
/// @notice Get the full Range data in a struct.
function range() external view virtual returns (Range memory);
/// @notice Get the capacity for a side of the range.
/// @param high_ - Specifies the side of the range to get capacity for (true = high side, false = low side).
function capacity(bool high_) external view virtual returns (uint256);
/// @notice Get the status of a side of the range (whether it is active or not).
/// @param high_ - Specifies the side of the range to get status for (true = high side, false = low side).
function active(bool high_) external view virtual returns (bool);
/// @notice Get the price for the wall or cushion for a side of the range.
/// @param high_ - Specifies the side of the range to get the price for (true = high side, false = low side).
/// @param wall_ - Specifies the band to get the price for (true = wall, false = cushion).
function price(bool high_, bool wall_) external view virtual returns (uint256);
/// @notice Get the spread for the wall or cushion band.
/// @param high_ - Specifies the side of the range to get the spread for (true = high side, false = low side).
/// @param wall_ - Specifies the band to get the spread for (true = wall, false = cushion).
function spread(bool high_, bool wall_) external view virtual returns (uint256);
/// @notice Get the market ID for a side of the range.
/// @param high_ - Specifies the side of the range to get market for (true = high side, false = low side).
function market(bool high_) external view virtual returns (uint256);
/// @notice Get the timestamp when the range was last active.
/// @param high_ - Specifies the side of the range to get timestamp for (true = high side, false = low side).
function lastActive(bool high_) external view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.15;
import "src/Kernel.sol";
abstract contract ROLESv1 is Module {
// ========= EVENTS ========= //
event RoleGranted(bytes32 indexed role_, address indexed addr_);
event RoleRevoked(bytes32 indexed role_, address indexed addr_);
// ========= ERRORS ========= //
error ROLES_InvalidRole(bytes32 role_);
error ROLES_RequireRole(bytes32 role_);
error ROLES_AddressAlreadyHasRole(address addr_, bytes32 role_);
error ROLES_AddressDoesNotHaveRole(address addr_, bytes32 role_);
error ROLES_RoleDoesNotExist(bytes32 role_);
// ========= STATE ========= //
/// @notice Mapping for if an address has a policy-defined role.
mapping(address => mapping(bytes32 => bool)) public hasRole;
// ========= FUNCTIONS ========= //
/// @notice Function to grant policy-defined roles to some address. Can only be called by admin.
function saveRole(bytes32 role_, address addr_) external virtual;
/// @notice Function to revoke policy-defined roles from some address. Can only be called by admin.
function removeRole(bytes32 role_, address addr_) external virtual;
/// @notice "Modifier" to restrict policy function access to certain addresses with a role.
/// @dev Roles are defined in the policy and granted by the ROLES admin.
function requireRole(bytes32 role_, address caller_) external virtual;
/// @notice Function that checks if role is valid (all lower case)
function ensureValidRole(bytes32 role_) external pure virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
uint256 private locked = 1;
modifier nonReentrant() virtual {
require(locked == 1, "REENTRANCY");
locked = 2;
_;
locked = 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
/*//////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
/*//////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "APPROVE_FAILED");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.15;
import {ERC20} from "solmate/tokens/ERC20.sol";
import "src/Kernel.sol";
/// @notice Treasury holds all other assets under the control of the protocol.
abstract contract TRSRYv1 is Module {
// ========= EVENTS ========= //
event IncreaseWithdrawApproval(
address indexed withdrawer_,
ERC20 indexed token_,
uint256 newAmount_
);
event DecreaseWithdrawApproval(
address indexed withdrawer_,
ERC20 indexed token_,
uint256 newAmount_
);
event Withdrawal(
address indexed policy_,
address indexed withdrawer_,
ERC20 indexed token_,
uint256 amount_
);
event IncreaseDebtorApproval(address indexed debtor_, ERC20 indexed token_, uint256 newAmount_);
event DecreaseDebtorApproval(address indexed debtor_, ERC20 indexed token_, uint256 newAmount_);
event DebtIncurred(ERC20 indexed token_, address indexed policy_, uint256 amount_);
event DebtRepaid(ERC20 indexed token_, address indexed policy_, uint256 amount_);
event DebtSet(ERC20 indexed token_, address indexed policy_, uint256 amount_);
// ========= ERRORS ========= //
error TRSRY_NoDebtOutstanding();
error TRSRY_NotActive();
// ========= STATE ========= //
/// @notice Status of the treasury. If false, no withdrawals or debt can be incurred.
bool public active;
/// @notice Mapping of who is approved for withdrawal.
/// @dev withdrawer -> token -> amount. Infinite approval is max(uint256).
mapping(address => mapping(ERC20 => uint256)) public withdrawApproval;
/// @notice Mapping of who is approved to incur debt.
/// @dev debtor -> token -> amount. Infinite approval is max(uint256).
mapping(address => mapping(ERC20 => uint256)) public debtApproval;
/// @notice Total debt for token across all withdrawals.
mapping(ERC20 => uint256) public totalDebt;
/// @notice Debt for particular token and debtor address
mapping(ERC20 => mapping(address => uint256)) public reserveDebt;
// ========= FUNCTIONS ========= //
modifier onlyWhileActive() {
if (!active) revert TRSRY_NotActive();
_;
}
/// @notice Increase approval for specific withdrawer addresses
function increaseWithdrawApproval(
address withdrawer_,
ERC20 token_,
uint256 amount_
) external virtual;
/// @notice Decrease approval for specific withdrawer addresses
function decreaseWithdrawApproval(
address withdrawer_,
ERC20 token_,
uint256 amount_
) external virtual;
/// @notice Allow withdrawal of reserve funds from pre-approved addresses.
function withdrawReserves(address to_, ERC20 token_, uint256 amount_) external virtual;
/// @notice Increase approval for someone to accrue debt in order to withdraw reserves.
/// @dev Debt will generally be taken by contracts to allocate treasury funds in yield sources.
function increaseDebtorApproval(
address debtor_,
ERC20 token_,
uint256 amount_
) external virtual;
/// @notice Decrease approval for someone to withdraw reserves as debt.
function decreaseDebtorApproval(
address debtor_,
ERC20 token_,
uint256 amount_
) external virtual;
/// @notice Pre-approved policies can get a loan to perform operations with treasury assets.
function incurDebt(ERC20 token_, uint256 amount_) external virtual;
/// @notice Repay a debtor debt.
/// @dev Only confirmed to safely handle standard and non-standard ERC20s.
/// @dev Can have unforeseen consequences with ERC777. Be careful with ERC777 as reserve.
function repayDebt(address debtor_, ERC20 token_, uint256 amount_) external virtual;
/// @notice An escape hatch for setting debt in special cases, like swapping reserves to another token.
function setDebt(address debtor_, ERC20 token_, uint256 amount_) external virtual;
/// @notice Get total balance of assets inside the treasury + any debt taken out against those assets.
function getReserveBalance(ERC20 token_) external view virtual returns (uint256);
/// @notice Emergency shutdown of withdrawals.
function deactivate() external virtual;
/// @notice Re-activate withdrawals after shutdown.
function activate() external virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "solmate/tokens/ERC20.sol";
/// @notice Safe ERC20 and ETH transfer library that safely handles missing return values.
/// @author Modified from Uniswap & old Solmate (https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/TransferHelper.sol)
library TransferHelper {
function safeTransferFrom(ERC20 token, address from, address to, uint256 amount) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(ERC20.transferFrom.selector, from, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FROM_FAILED");
}
function safeTransfer(ERC20 token, address to, uint256 amount) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(ERC20.transfer.selector, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED");
}
function safeApprove(ERC20 token, address to, uint256 amount) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(ERC20.approve.selector, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED");
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.15;
import "src/Kernel.sol";
import {ReentrancyGuard} from "solmate/utils/ReentrancyGuard.sol";
import {ERC20} from "solmate/tokens/ERC20.sol";
import {ERC4626} from "solmate/mixins/ERC4626.sol";
import {TransferHelper} from "libraries/TransferHelper.sol";
import {FullMath} from "libraries/FullMath.sol";
import {IBondSDA} from "interfaces/IBondSDA.sol";
import {IYieldRepo} from "policies/interfaces/IYieldRepo.sol";
import {RolesConsumer, ROLESv1} from "modules/ROLES/OlympusRoles.sol";
import {TRSRYv1} from "modules/TRSRY/TRSRY.v1.sol";
import {PRICEv1} from "modules/PRICE/PRICE.v1.sol";
import {RANGEv2} from "modules/RANGE/RANGE.v2.sol";
interface BurnableERC20 {
function burn(uint256 amount) external;
}
interface Clearinghouse {
function principalReceivables() external view returns (uint256);
}
/// @notice the Yield Repurchase Facility (Yield Repo) contract pulls a derived amount of yield from
/// the Olympus treasury each week and uses it, along with the backing of previously purchased
/// OHM, to purchase OHM off the market using a Bond Protocol SDA market.
contract YieldRepurchaseFacility is IYieldRepo, Policy, RolesConsumer {
using FullMath for uint256;
using TransferHelper for ERC20;
///////////////////////// EVENTS /////////////////////////
event RepoMarket(uint256 marketId, uint256 bidAmount);
event NextYieldSet(uint256 nextYield);
event Shutdown();
///////////////////////// STATE /////////////////////////
// Tokens
ERC4626 public immutable sdai; // = ERC4626(0x83F20F44975D03b1b09e64809B757c47f942BEeA);
ERC20 public immutable dai; // = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
uint8 internal immutable _daiDecimals; // = 18;
ERC20 public immutable ohm; // = ERC20(0x64aa3364F17a4D01c6f1751Fd97C2BD3D7e7f1D5);
uint8 internal immutable _ohmDecimals; // = 9;
uint8 internal _oracleDecimals;
// Modules
TRSRYv1 public TRSRY;
PRICEv1 public PRICE;
RANGEv2 public RANGE;
// Policies
Clearinghouse public immutable clearinghouse; // = Clearinghouse(0xE6343ad0675C9b8D3f32679ae6aDbA0766A2ab4c);
// External contracts
address public immutable teller; // = 0x007F7735baF391e207E3aA380bb53c4Bd9a5Fed6;
IBondSDA public immutable auctioneer; // = IBondSDA(0x007F7A1cb838A872515c8ebd16bE4b14Ef43a222);
// System variables
uint48 public epoch; // a running counter to keep time
uint256 public nextYield; // the amount of DAI to pull as yield at the start of the next week
uint256 public lastReserveBalance; // the SDAI reserve balance, in DAI, at the end of the last week
uint256 public lastConversionRate; // the SDAI conversion rate at the end of the last week
// we use this to compute yield accrued
// yield = last reserve balance * ((current conversion rate / last conversion rate) - 1)
// + current clearinghouse principal receivables * clearinghouse APR / 52 weeks
bool public isShutdown;
// Constants
uint48 public constant epochLength = 21; // one week
uint256 public constant backingPerToken = 1133 * 1e7; // assume backing of $11.33
///////////////////////// SETUP /////////////////////////
constructor(
Kernel kernel_,
address ohm_,
address dai_,
address sdai_,
address teller_,
address auctioneer_,
address clearinghouse_
) Policy(kernel_) {
// Set immutable variables
ohm = ERC20(ohm_);
dai = ERC20(dai_);
sdai = ERC4626(sdai_);
teller = teller_;
auctioneer = IBondSDA(auctioneer_);
clearinghouse = Clearinghouse(clearinghouse_);
// Cache token decimals
_daiDecimals = dai.decimals();
_ohmDecimals = ohm.decimals();
// Disable until initialization
isShutdown = true;
}
function initialize(
uint256 initialReserveBalance,
uint256 initialConversionRate,
uint256 initialYield
) external onlyRole("loop_daddy") {
// Initialize system variables
epoch = 20;
lastReserveBalance = initialReserveBalance;
lastConversionRate = initialConversionRate;
nextYield = initialYield;
emit NextYieldSet(initialYield);
// Enable
isShutdown = false;
}
function configureDependencies() external override returns (Keycode[] memory dependencies) {
dependencies = new Keycode[](4);
dependencies[0] = toKeycode("TRSRY");
dependencies[1] = toKeycode("PRICE");
dependencies[2] = toKeycode("RANGE");
dependencies[3] = toKeycode("ROLES");
TRSRY = TRSRYv1(getModuleAddress(dependencies[0]));
PRICE = PRICEv1(getModuleAddress(dependencies[1]));
RANGE = RANGEv2(getModuleAddress(dependencies[2]));
ROLES = ROLESv1(getModuleAddress(dependencies[3]));
_oracleDecimals = PRICE.decimals();
}
function requestPermissions()
external
view
override
returns (Permissions[] memory permissions)
{
Keycode TRSRY_KEYCODE = TRSRY.KEYCODE();
permissions = new Permissions[](2);
permissions[0] = Permissions(TRSRY_KEYCODE, TRSRYv1.withdrawReserves.selector);
permissions[1] = Permissions(TRSRY_KEYCODE, TRSRYv1.increaseWithdrawApproval.selector);
}
///////////////////////// EXTERNAL /////////////////////////
/// @notice create a new bond market at the end of the day with some portion of remaining funds
function endEpoch() public override onlyRole("heart") {
if (isShutdown) return; // disabling this contract will not interfere with heartbeat
epoch++;
if (epoch % 3 != 0) return; // only execute once per day
if (epoch == epochLength) {
// reset at end of week
epoch = 0;
_withdraw(nextYield);
nextYield = getNextYield();
emit NextYieldSet(nextYield);
lastConversionRate = sdai.previewRedeem(1e18);
lastReserveBalance = getReserveBalance();
}
_getBackingForPurchased(); // convert yesterdays ohm purchases into sdai
uint256 daiBalance = dai.balanceOf(address(this));
uint256 totalBalanceInDAI = daiBalance + sdai.previewRedeem(sdai.balanceOf(address(this)));
// use portion of dai balance based on day of the week
// i.e. day one, use 1/7th; day two, use 1/6th; 1/5th; 1/4th; ...
uint256 bidAmount = totalBalanceInDAI / (7 - (epoch / 3));
// contract holds funds in sDAI except for the day's inventory, so we need to redeem before opening a market
uint256 bidAmountFromSDAI = daiBalance < bidAmount
? bidAmount - dai.balanceOf(address(this))
: 0;
if (bidAmountFromSDAI != 0)
sdai.redeem(sdai.previewWithdraw(bidAmountFromSDAI), address(this), address(this));
_createMarket(bidAmount);
}
/// @notice allow manager to increase (by maximum 10%) or decrease yield for week if contract is inaccurate
/// @param newNextYield to fund
function adjustNextYield(uint256 newNextYield) external onlyRole("loop_daddy") {
if (newNextYield > nextYield && ((newNextYield * 1e18) / nextYield) > (11 * 1e17))
revert("Too much increase");
nextYield = newNextYield;
emit NextYieldSet(nextYield);
}
/// @notice retire contract by burning ohm balance and transferring tokens to treasury
/// @param tokensToTransfer list of tokens to transfer back to treasury (i.e. DAI)
function shutdown(ERC20[] memory tokensToTransfer) external onlyRole("loop_daddy") {
isShutdown = true;
emit Shutdown();
// Burn OHM in contract
BurnableERC20(address(ohm)).burn(ohm.balanceOf(address(this)));
// Transfer all tokens to treasury
for (uint256 i; i < tokensToTransfer.length; i++) {
ERC20 token = tokensToTransfer[i];
token.safeTransfer(address(TRSRY), token.balanceOf(address(this)));
}
}
///////////////////////// INTERNAL /////////////////////////
/// @notice create bond protocol market with given budget
/// @param bidAmount amount of DAI to fund bond market with
function _createMarket(uint256 bidAmount) internal {
// Calculate inverse prices from the oracle feed
// The start price is the current market price, which is also the last price since this is called on a heartbeat
// The min price is the upper cushion price, since we don't want to buy above this level
uint256 minPrice = 10 ** (_oracleDecimals * 2) / RANGE.price(true, true); // upper wall = (true, true) => high = true, wall = true
uint256 initialPrice = 10 ** (_oracleDecimals * 2) / ((PRICE.getLastPrice() * 97) / 100); // 3% below current stated price in case oracle is stale
// If the min price is greater than or equal to the initial price, we don't want to create a market
if (minPrice >= initialPrice) return;
// Calculate scaleAdjustment for bond market
// Price decimals are returned from the perspective of the quote token
// so the operations assume payoutPriceDecimal is zero and quotePriceDecimals
// is the priceDecimal value
int8 priceDecimals = _getPriceDecimals(initialPrice);
int8 scaleAdjustment = int8(_daiDecimals) - int8(_ohmDecimals) + (priceDecimals / 2);
// Calculate oracle scale and bond scale with scale adjustment and format prices for bond market
uint256 oracleScale = 10 ** uint8(int8(_oracleDecimals) - priceDecimals);
uint256 bondScale = 10 **
uint8(36 + scaleAdjustment + int8(_ohmDecimals) - int8(_daiDecimals) - priceDecimals);
// Approve DAI on the bond teller
dai.safeApprove(address(teller), bidAmount);
// Create new bond market to buy OHM with the reserve
uint256 marketId = auctioneer.createMarket(
abi.encode(
IBondSDA.MarketParams({
payoutToken: dai,
quoteToken: ohm,
callbackAddr: address(0),
capacityInQuote: false,
capacity: bidAmount,
formattedInitialPrice: initialPrice.mulDiv(bondScale, oracleScale),
formattedMinimumPrice: minPrice.mulDiv(bondScale, oracleScale),
debtBuffer: 100_000, // 100%
vesting: uint48(0), // Instant swaps
conclusion: uint48(block.timestamp + 1 days), // 1 day from now
depositInterval: uint32(4 hours), // 4 hours
scaleAdjustment: scaleAdjustment
})
)
);
emit RepoMarket(marketId, bidAmount);
}
/// @notice internal function to burn ohm and retrieve backing
function _getBackingForPurchased() internal {
// Get backing for purchased OHM
(uint256 ohmBalance, uint256 backing) = getOhmBalanceAndBacking();
// Burn OHM in contract
BurnableERC20(address(ohm)).burn(ohmBalance);
// Withdraw backing for purchased ohm
_withdraw(backing);
}
/// @notice internal function to withdraw sDAI from treasury
/// @dev note amount given is in DAI, not sDAI
/// @param amount an amount to withdraw, in DAI
function _withdraw(uint256 amount) internal {
// Get the amount of sDAI to withdraw
uint256 amountInSDAI = sdai.previewWithdraw(amount);
// Approve and withdraw sDAI from TRSRY
TRSRY.increaseWithdrawApproval(address(this), ERC20(address(sdai)), amountInSDAI);
TRSRY.withdrawReserves(address(this), ERC20(address(sdai)), amountInSDAI);
}
/// @notice Helper function to calculate number of price decimals based on the value returned from the price feed.
/// @param price_ The price to calculate the number of decimals for
/// @return The number of decimals
function _getPriceDecimals(uint256 price_) internal view returns (int8) {
int8 decimals;
while (price_ >= 10) {
price_ = price_ / 10;
decimals++;
}
// Subtract the stated decimals from the calculated decimals to get the relative price decimals.
// Required to do it this way vs. normalizing at the beginning since price decimals can be negative.
return decimals - int8(_oracleDecimals);
}
///////////////////////// VIEW /////////////////////////
/// @notice fetch combined sdai balance of clearinghouse and treasury, in DAI
function getReserveBalance() public view override returns (uint256 balance) {
uint256 sBalance = sdai.balanceOf(address(clearinghouse));
sBalance += sdai.balanceOf(address(TRSRY));
balance = sdai.previewRedeem(sBalance);
}
/// @notice compute yield for the next week
function getNextYield() public view override returns (uint256 yield) {
// add sDAI rewards accrued for week
yield +=
((lastReserveBalance * sdai.previewRedeem(1e18)) / lastConversionRate) -
lastReserveBalance;
// add clearinghouse interest accrued for week (0.5% divided by 52 weeks)
yield += (clearinghouse.principalReceivables() * 5) / 1000 / 52;
}
/// @notice compute backing for ohm balance
function getOhmBalanceAndBacking()
public
view
override
returns (uint256 balance, uint256 backing)
{
// balance and backingPerToken are 9 decimals, dai amount is 18 decimals
balance = ohm.balanceOf(address(this));
backing = balance * backingPerToken;
}
}
{
"compilationTarget": {
"src/policies/YieldRepurchaseFacility.sol": "YieldRepurchaseFacility"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 10
},
"remappings": [
":@addresses/=lib/forge-proposal-simulator/addresses/",
":@examples/=lib/forge-proposal-simulator/examples/",
":@openzeppelin/=lib/openzeppelin-contracts/",
":@proposals/=lib/forge-proposal-simulator/proposals/",
":@script/=lib/forge-proposal-simulator/script/",
":@test/=lib/forge-proposal-simulator/test/",
":@utils/=lib/forge-proposal-simulator/utils/",
":Cooler/=lib/Cooler/src/",
":balancer-v2/=lib/balancer-v2/",
":bonds/=lib/bonds/src/",
":clones-with-immutable-args/=lib/clones-with-immutable-args/src/",
":clones/=lib/clones-with-immutable-args/src/",
":comp-governance/=lib/forge-proposal-simulator/lib/compound-governance/contracts/",
":compound-governance/=lib/forge-proposal-simulator/lib/compound-governance/contracts/",
":ds-test/=lib/ds-test/src/",
":erc4626-tests/=lib/forge-proposal-simulator/lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-proposal-simulator/=lib/forge-proposal-simulator/",
":forge-std/=lib/forge-std/src/",
":interfaces/=src/interfaces/",
":layer-zero/=lib/solidity-examples/contracts/",
":libraries/=src/libraries/",
":modules/=src/modules/",
":olympus-v3/=lib/Cooler/lib/olympus-v3/src/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/",
":openzeppelin/=lib/openzeppelin-contracts/contracts/",
":policies/=src/policies/",
":proposal-sim/=lib/forge-proposal-simulator/",
":proposal-sim/proposals/=lib/forge-proposal-simulator/proposals/",
":proposals/=src/proposals/",
":solidity-examples/=lib/solidity-examples/contracts/",
":solmate/=lib/solmate/src/",
":test/=src/test/",
":uniswap-v3-core/=lib/uniswap-v3-core/contracts/",
":uniswap-v3-periphery/=lib/uniswap-v3-periphery/contracts/"
]
}
[{"inputs":[{"internalType":"contract Kernel","name":"kernel_","type":"address"},{"internalType":"address","name":"ohm_","type":"address"},{"internalType":"address","name":"dai_","type":"address"},{"internalType":"address","name":"sdai_","type":"address"},{"internalType":"address","name":"teller_","type":"address"},{"internalType":"address","name":"auctioneer_","type":"address"},{"internalType":"address","name":"clearinghouse_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"caller_","type":"address"}],"name":"KernelAdapter_OnlyKernel","type":"error"},{"inputs":[{"internalType":"Keycode","name":"keycode_","type":"bytes5"}],"name":"Policy_ModuleDoesNotExist","type":"error"},{"inputs":[{"internalType":"bytes","name":"expected_","type":"bytes"}],"name":"Policy_WrongModuleVersion","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"nextYield","type":"uint256"}],"name":"NextYieldSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"marketId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bidAmount","type":"uint256"}],"name":"RepoMarket","type":"event"},{"anonymous":false,"inputs":[],"name":"Shutdown","type":"event"},{"inputs":[],"name":"PRICE","outputs":[{"internalType":"contract PRICEv1","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"RANGE","outputs":[{"internalType":"contract RANGEv2","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ROLES","outputs":[{"internalType":"contract ROLESv1","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TRSRY","outputs":[{"internalType":"contract TRSRYv1","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"newNextYield","type":"uint256"}],"name":"adjustNextYield","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"auctioneer","outputs":[{"internalType":"contract IBondSDA","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"backingPerToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract Kernel","name":"newKernel_","type":"address"}],"name":"changeKernel","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"clearinghouse","outputs":[{"internalType":"contract Clearinghouse","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"configureDependencies","outputs":[{"internalType":"Keycode[]","name":"dependencies","type":"bytes5[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"dai","outputs":[{"internalType":"contract ERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"endEpoch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"epoch","outputs":[{"internalType":"uint48","name":"","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"epochLength","outputs":[{"internalType":"uint48","name":"","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getNextYield","outputs":[{"internalType":"uint256","name":"yield","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getOhmBalanceAndBacking","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"backing","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getReserveBalance","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"initialReserveBalance","type":"uint256"},{"internalType":"uint256","name":"initialConversionRate","type":"uint256"},{"internalType":"uint256","name":"initialYield","type":"uint256"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isShutdown","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"kernel","outputs":[{"internalType":"contract Kernel","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastConversionRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastReserveBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextYield","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ohm","outputs":[{"internalType":"contract ERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"requestPermissions","outputs":[{"components":[{"internalType":"Keycode","name":"keycode","type":"bytes5"},{"internalType":"bytes4","name":"funcSelector","type":"bytes4"}],"internalType":"struct Permissions[]","name":"permissions","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sdai","outputs":[{"internalType":"contract ERC4626","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ERC20[]","name":"tokensToTransfer","type":"address[]"}],"name":"shutdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"teller","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]