Verified contractExactMIT
ProtoBonds
Address0xba0b60e2f23a84502128d73f1729a3ac78801cd4
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,362,659
- Creation transaction
- 0xc670ce8b10…dba1718374
21 files
- contracts/proto/ProtoBonds.solmain13.67 KB
- @openzeppelin/contracts/access/AccessControl.sol7.05 KB
- @openzeppelin/contracts/access/IAccessControl.sol3.26 KB
- @openzeppelin/contracts/access/Ownable.sol3.1 KB
- @openzeppelin/contracts/interfaces/draft-IERC6093.sol6.53 KB
- @openzeppelin/contracts/token/ERC20/ERC20.sol11.14 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- @openzeppelin/contracts/utils/Address.sol6.26 KB
- @openzeppelin/contracts/utils/Context.sol963 B
- @openzeppelin/contracts/utils/ReentrancyGuard.sol3.24 KB
- @openzeppelin/contracts/utils/introspection/ERC165.sol911 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol869 B
- contracts/IBondOracle.sol2 KB
- contracts/IReserveOracle.sol1.3 KB
- contracts/OlympusToken.sol1.26 KB
- contracts/StakedToken.sol7 KB
- contracts/Staking.sol15.56 KB
- contracts/Treasury.sol52.92 KB
contracts/proto/ProtoBonds.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../Treasury.sol";
import "../IBondOracle.sol";
// ============================================================
// ProtoBonds.sol (13 Oct 2026, Hollow: "that auto-bond discount formula
// which was discussed to be built for keel", saved for Keel on 11 Oct)
//
// Keel's standing bond engine with the discount as a FORMULA instead of
// a dial, and nothing else a key could touch:
//
// discount = BASE_DISCOUNT x LINE / (price / floor)
//
// 8% at the 1.5x line, 4% at 3x, 2% at 6x, 1% at 12x: the hotter the
// market, the thinner the discount, so more of every bond's money goes
// through the split and no key ever picks the number. Below the line
// there are no bonds at all.
//
// discount = max(BASE_DISCOUNT x LINE / (price / floor), MIN_DISCOUNT)
//
// (21 Oct 2026, the founder: "the floor will barely go up if there gets to
// be fomo"): high above the floor the formula's discount shrinks toward
// nothing and bonds go quiet just when the most ETH would come through them.
// MIN_DISCOUNT (fixed at construction, never above BASE, 0 for none) keeps a
// least discount, so in a run-up a bond stays the cheaper way in and its ETH
// goes into the vault: 1.3x the floor for each new token, the rest through
// the split. The 1.3x backing floor on the bond price below still binds.
//
// price the pool's 30-minute average (the hook's TWAP), refused
// while the latest price is more than MAX_DEVIATION off it
// bond price the average less the discount, never under
// 1.3 x floor / (1 - PREMIUM): the Treasury's 1.3x backing
// with a margin, so a bond can never lower the floor
// stock a standing offer of at most STOCK_MAX of supply, refilling
// REFILL of supply a day, up to HEAT_MAX faster the further
// the market runs above the line
// limits MAX_PAYOUT of supply a transaction, WALLET_DAY of supply a
// wallet a day
// delivery the payout, less the Treasury's 1% burn, as a lock owned by
// the buyer at the locks' minimum term (3 days on Hollow, set at the deploy), earning
// the lockers' share while it waits
// in ETH depositEth() wraps the ETH sent when the reserve is WETH
//
// No owner, no brake, no setter: every number is fixed at construction.
// ============================================================
interface ILocksPB {
function lockFor(address to, uint256 amount, uint256 term) external returns (uint256);
function minTerm() external view returns (uint256);
function entryBurnBPS() external view returns (uint256);
}
/// The oracle reads the pool's hook; the hook knows whether its launch fee is still running.
interface IOracleHookPB { function HOOK() external view returns (address); }
interface IHookFeePB { function launchFeeBPS() external view returns (uint256); }
interface IWETHPB { function deposit() external payable; }
contract ProtoBonds is ReentrancyGuard {
using SafeERC20 for IERC20;
IERC20 public immutable TOKEN;
Treasury public immutable TREASURY;
IERC20 public immutable RESERVE;
IBondOracle public immutable ORACLE;
ILocksPB public immutable LOCKS;
bool public immutable NATIVE; // the reserve is WETH: depositEth() is open
uint256 public immutable BASE_DISCOUNT_BPS; // at the line (800 = 8%)
uint256 public immutable LINE_X1E4; // bonds issue at or above this multiple of the floor (15000 = 1.5x)
uint256 public immutable PREMIUM_BPS; // the margin over 1.3x backing at the floor (800)
uint256 public immutable MAX_DEVIATION_BPS; // latest price vs the average (500 = 5%)
uint256 public immutable MAX_PAYOUT_BPS; // of supply, a transaction (300 = 3%)
uint256 public immutable REFILL_BPS_PER_DAY; // of supply, at heat 1x (50 = 0.5%)
uint256 public immutable STOCK_MAX_BPS; // of supply (200 = 2%)
uint256 public immutable HEAT_MAX_X1E4; // the refill's top speed (20000 = 2x)
uint256 public immutable WALLET_DAY_BPS; // of supply, a wallet a day (100 = 1%)
uint256 public immutable MIN_DISCOUNT_BPS; // the least discount above the line (500 = 5%; 0 = none)
uint256 public stock; // tokens the engine may mint right now
uint256 public lastRefill;
mapping(address => mapping(uint256 => uint256)) public boughtOnDay; // wallet => UTC day => tokens
uint256 public totalBonded; // reserve paid in, raw units
uint256 public totalMinted;
struct Terms {
uint256 baseDiscountBPS; uint256 lineX1e4; uint256 premiumBPS; uint256 maxDeviationBPS; uint256 maxPayoutBPS;
uint256 refillBPSPerDay; uint256 stockMaxBPS; uint256 heatMaxX1e4; uint256 walletDayBPS;
uint256 minDiscountBPS; // 21 Oct: the least discount above the line (0 = the formula alone)
}
event Bonded(address indexed buyer, uint256 paid, uint256 payout, uint256 lockId, uint256 discountBPS);
constructor(address token, address treasury, address reserve, address oracle, address locks, bool native, Terms memory t) {
require(token != address(0) && treasury != address(0) && reserve != address(0) && oracle != address(0) && locks != address(0), "Zero address");
require(t.baseDiscountBPS > 0 && t.baseDiscountBPS <= 3000, "Discount 0 to 30%");
require(t.lineX1e4 >= 13000 && t.lineX1e4 <= 50000, "Line 1.3x to 5x");
require(t.premiumBPS >= 600 && t.premiumBPS <= 3000, "Premium 6% to 30%");
require(t.maxDeviationBPS >= 100 && t.maxDeviationBPS <= 2000, "Deviation 1% to 20%");
require(t.maxPayoutBPS > 0 && t.maxPayoutBPS <= 500, "Per transaction up to 5%");
require(t.refillBPSPerDay <= 200 && t.stockMaxBPS <= 500 && t.walletDayBPS <= 100, "Stock limits");
require(t.heatMaxX1e4 >= 10000 && t.heatMaxX1e4 <= 30000, "Heat 1x to 3x");
require(t.minDiscountBPS <= t.baseDiscountBPS, "Least discount up to the base");
TOKEN = IERC20(token); TREASURY = Treasury(treasury); RESERVE = IERC20(reserve);
ORACLE = IBondOracle(oracle); LOCKS = ILocksPB(locks); NATIVE = native;
BASE_DISCOUNT_BPS = t.baseDiscountBPS; LINE_X1E4 = t.lineX1e4; PREMIUM_BPS = t.premiumBPS;
MAX_DEVIATION_BPS = t.maxDeviationBPS; MAX_PAYOUT_BPS = t.maxPayoutBPS; REFILL_BPS_PER_DAY = t.refillBPSPerDay;
STOCK_MAX_BPS = t.stockMaxBPS; HEAT_MAX_X1E4 = t.heatMaxX1e4; WALLET_DAY_BPS = t.walletDayBPS;
MIN_DISCOUNT_BPS = t.minDiscountBPS;
lastRefill = block.timestamp;
}
// ── the price ──
/// The pool's average as a multiple of the floor, x1e4. 0 with no floor or no average.
function multipleX1e4() public view returns (uint256) {
uint256 floor = TREASURY.priceFloor();
if (floor == 0 || !ORACLE.ready()) return 0;
return (ORACLE.consult() * 10000) / floor;
}
/// The formula: BASE x LINE / multiple, never under MIN_DISCOUNT; 0 below the line (no bonds there).
function discountNowBPS() public view returns (uint256) {
uint256 m = multipleX1e4();
if (m < LINE_X1E4) return 0;
uint256 d = (BASE_DISCOUNT_BPS * LINE_X1E4) / m;
return d < MIN_DISCOUNT_BPS ? MIN_DISCOUNT_BPS : d;
}
/// Open: an average with history, a latest price within MAX_DEVIATION of it, and the market at or above the line.
function open() public view returns (bool, string memory) {
if (TREASURY.priceFloor() == 0) return (false, "No floor yet");
// no bonds while the pool's anti-bot launch fee runs: a bond pays none, so it would be the way around it (third review, 13 Oct)
if (launchFeeRunning()) return (false, "Launch fee running");
if (!ORACLE.ready()) return (false, "The average is not ready");
if (ORACLE.deviationBps() > MAX_DEVIATION_BPS) return (false, "The price is off its average: wait");
if (multipleX1e4() < LINE_X1E4) return (false, "Under the line");
return (true, "Open");
}
/// True while the pool's hook still charges its launch fee. An oracle without a hook has none.
function launchFeeRunning() public view returns (bool) {
try IOracleHookPB(address(ORACLE)).HOOK() returns (address hook) {
try IHookFeePB(hook).launchFeeBPS() returns (uint256 bps) { return bps > 0; } catch { return false; }
} catch { return false; }
}
/// What `amount` puts in the buyer's lock: the quote less the Treasury's 1% burn and the locks' entry burn.
function quoteLocked(uint256 amount) public view returns (uint256) {
uint256 p = quote(amount);
uint256 afterBurn = p - (p * TREASURY.BOND_REDEMPTION_BURN_BPS()) / 10000;
return afterBurn - (afterBurn * LOCKS.entryBurnBPS()) / 10000;
}
/// The reserve a token costs, 18 decimals.
function bondPrice() public view returns (uint256) {
uint256 floor = TREASURY.priceFloor();
if (floor == 0) return 0;
uint256 minPrice = (TREASURY.MIN_BACKING_RATIO() * floor * 10000) / (1e18 * (10000 - PREMIUM_BPS));
if (!ORACLE.ready()) return minPrice;
uint256 p = (ORACLE.consult() * (10000 - discountNowBPS())) / 10000;
return p > minPrice ? p : minPrice;
}
/// The tokens `amount` (raw reserve units) buys now, before the 1% burn.
function quote(uint256 amount) public view returns (uint256 payout) {
uint256 floor = TREASURY.priceFloor();
uint256 price = bondPrice();
if (floor == 0 || price == 0) return 0;
uint256 a18 = _to18(amount);
payout = (a18 * 1e18) / price;
// never more than 1.3x backing at the floor allows, less the premium
uint256 ceiling = (((a18 * 1e18) / TREASURY.MIN_BACKING_RATIO()) * 1e18 / floor) * (10000 - PREMIUM_BPS) / 10000;
if (payout > ceiling) payout = ceiling;
}
// ── the stock ──
function _heat() internal view returns (uint256) {
uint256 m = multipleX1e4();
if (m <= LINE_X1E4) return 10000;
uint256 extra = ((m - LINE_X1E4) * 10000) / LINE_X1E4;
uint256 room = HEAT_MAX_X1E4 - 10000;
return 10000 + (extra > room ? room : extra);
}
function stockNow() public view returns (uint256) {
uint256 supply = TOKEN.totalSupply();
uint256 cap = (supply * STOCK_MAX_BPS) / 10000;
uint256 s = stock + (supply * REFILL_BPS_PER_DAY * _heat() * (block.timestamp - lastRefill)) / (10000 * 10000 * 1 days);
return s > cap ? cap : s;
}
function walletRoomToday(address who) public view returns (uint256) {
uint256 cap = (TOKEN.totalSupply() * WALLET_DAY_BPS) / 10000;
uint256 used = boughtOnDay[who][block.timestamp / 1 days];
return used >= cap ? 0 : cap - used;
}
// ── bonding ──
function deposit(uint256 amount, uint256 minPayout) external nonReentrant returns (uint256 lockId) {
RESERVE.safeTransferFrom(msg.sender, address(this), amount);
return _bond(msg.sender, amount, minPayout);
}
/// The same, paid in ETH (the reserve is WETH).
function depositEth(uint256 minPayout) external payable nonReentrant returns (uint256 lockId) {
require(NATIVE, "This engine takes the reserve token");
IWETHPB(address(RESERVE)).deposit{value: msg.value}();
return _bond(msg.sender, msg.value, minPayout);
}
function _bond(address buyer, uint256 amount, uint256 minPayout) internal returns (uint256 lockId) {
require(amount > 0, "Zero");
(bool ok, string memory why) = open();
require(ok, why);
uint256 payout = quote(amount);
require(payout > 0, "Slippage: payout too low");
uint256 supply = TOKEN.totalSupply();
require(payout <= (supply * MAX_PAYOUT_BPS) / 10000, "Over the limit a transaction");
uint256 s = stockNow();
require(payout <= s, "The stock is low: wait for the refill");
stock = s - payout;
lastRefill = block.timestamp;
uint256 day = block.timestamp / 1 days;
require(boughtOnDay[buyer][day] + payout <= (supply * WALLET_DAY_BPS) / 10000, "Over the limit a wallet today");
boughtOnDay[buyer][day] += payout;
uint256 d = discountNowBPS();
RESERVE.forceApprove(address(TREASURY), amount);
TREASURY.bondDeposit(address(RESERVE), amount, payout, 0); // backing first, the rest through the split; mints to here
(, uint256 delivered) = TREASURY.bondRedemptionBurn(payout); // 1% burned
// minPayout is what the lock keeps, after both burns (third review: it was checked before them)
require(delivered - (delivered * LOCKS.entryBurnBPS()) / 10000 >= minPayout, "Slippage: payout too low");
IERC20(address(TOKEN)).forceApprove(address(LOCKS), delivered);
lockId = LOCKS.lockFor(buyer, delivered, LOCKS.minTerm());
totalBonded += amount; totalMinted += payout;
emit Bonded(buyer, amount, delivered, lockId, d);
}
function _to18(uint256 amount) internal view returns (uint256) {
uint8 dec = IERC20Metadata(address(RESERVE)).decimals();
return dec == 18 ? amount : amount * (10 ** (18 - dec));
}
}
@openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contracts/IBondOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// IBondOracle.sol
//
// The price source bonds are quoted against.
//
// IMPLEMENTATION NOTE — read before writing one:
// consult() must return a TIME-WEIGHTED price, never spot. A spot
// price can be moved in a single transaction; a TWAP cannot be,
// without holding the pool away from true price for the whole
// window and paying arbitrageurs the entire time.
//
// Do not hand-roll the tick-to-price conversion. Use Uniswap's
// OracleLibrary.getQuoteAtTick, which is tested against billions
// in TVL. Reimplementing TickMath is how this goes silently wrong:
// the contract compiles, the tests pass against the same wrong
// assumption, and every bond misprices by orders of magnitude.
//
// Minimum window: 30 minutes.
//
// This interface is deliberately small. BondDepository never trusts
// the oracle on its own — it refuses any quote that would price a
// bond below 1.3x the floor, so a corrupted feed cannot mint a
// dilutive bond. The oracle sets the discount; the floor sets the
// boundary.
// ============================================================
interface IBondOracle {
/// Time-weighted price of one $SLM in reserve units, 18 decimals.
/// MUST revert if the pool cannot serve the full window.
function consult() external view returns (uint256 priceX18);
/// Spot price, 18 decimals. For deviation checks only.
function spot() external view returns (uint256 priceX18);
/// Absolute deviation of spot from the TWAP, in basis points.
/// Used to detect a manipulation attempt in progress.
function deviationBps() external view returns (uint256);
/// False if the pool lacks the observation history for the window.
function ready() external view returns (bool);
/// The averaging window in seconds. Must be >= 30 minutes.
function window() external view returns (uint32);
}
contracts/IReserveOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// IReserveOracle.sol
//
// USD price for reserve assets.
//
// The Treasury values every reserve unit at exactly $1.00. That is
// correct while every approved reserve is a sound dollar stablecoin
// and silently wrong the moment one is not: a depegged asset keeps
// counting at face value, the floor reports backing that does not
// exist, and redeemers draw against reserves that are not there.
//
// This is the only path by which redemption can drain the treasury.
// Sell pressure cannot — payout is always reserves/1.3, so 23.1% is
// mathematically unreachable. Reserve QUALITY is the exception.
//
// Implement with Chainlink USDC/USD, DAI/USD and equivalents. Those
// feeds exist and are well maintained; do not hand-roll this.
// ============================================================
interface IReserveOracle {
/// USD price of one whole token, 18 decimals. $1.00 == 1e18.
/// MUST revert on a stale or unset feed rather than returning 0.
function priceUSD(address token) external view returns (uint256);
/// False if the feed is missing, stale, or otherwise untrusted.
function healthy(address token) external view returns (bool);
}
contracts/OlympusToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// OlympusToken.sol v2 — No fixed hard cap
//
// Supply is governed dynamically by the Treasury's backing
// ratio ceiling (1.3x minimum). The Treasury contract enforces
// the ceiling on every mint — this contract simply executes.
// ============================================================
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract OlympusToken is ERC20, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
constructor(
string memory name,
string memory symbol,
uint256 initialSupply
) ERC20(name, symbol) {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
if (initialSupply > 0) _mint(msg.sender, initialSupply);
}
function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
_mint(to, amount);
}
function burn(address from, uint256 amount) external onlyRole(BURNER_ROLE) {
_burn(from, amount);
}
}
contracts/StakedToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// StakedToken.sol v3 — $sSLM
//
// PATCH NOTE (v2 -> v3):
// v2 wrote directly to _rawBalances and only emitted a
// Transfer event. ERC20's internal _balances were never
// touched, and _update() blocked every non-mint/burn move.
// Result: Staking.claim() reverted with "non-transferable"
// and no user could ever receive sSLM.
//
// v3 routes ALL movement through a single overridden
// _update() that operates on raw balances only. super._update
// is never called, so ERC20's _balances are unused by design.
// Transfers are permitted only when the staking contract is
// one of the two parties — sSLM remains non-transferable
// between users, which was the original intent.
// ============================================================
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./OlympusToken.sol";
interface IStakedTokenHook {
/// Called before any sSLM balance moves. Either address may be
/// zero, for a mint or a burn.
function settleOnTransfer(address from, address to) external;
}
contract StakedToken is ERC20, Ownable {
OlympusToken public immutable baseToken;
address public stakingContract;
// ── DIVIDEND SETTLEMENT ─────────────────────────────────
//
// Staking pays a second stream in the reserve asset, accounted
// per RAW balance. That accounting only works if a holder's
// ledger is settled BEFORE their raw balance changes.
//
// Staking settles on its own mints and burns. It cannot settle a
// transfer it never sees - and sSLM does move: BondDepository is
// an operator and hands a vested position straight to the bond
// buyer. Without this hook that buyer's dividend debt stays at
// zero, so they can immediately claim every dividend the protocol
// has ever accrued, pro-rata on a balance they have held for one
// block, out of the pool owed to existing stakers.
//
// So every balance change tells Staking first.
IStakedTokenHook public dividendHook;
/// Contracts permitted to hold and move sSLM. Needed so bond
/// payouts can vest as a staked position rather than sitting
/// idle. sSLM remains non-transferable between ordinary users.
mapping(address => bool) public isOperator;
// Index starts at 1e9 ("1.0") and grows with each rebase.
// Displayed balance = rawBalance * index / 1e9
uint256 public index = 1e9;
mapping(address => uint256) private _rawBalances;
uint256 private _totalRawSupply;
constructor(
address _baseToken,
string memory name,
string memory symbol
) ERC20(name, symbol) Ownable(msg.sender) {
baseToken = OlympusToken(_baseToken);
}
function setStakingContract(address _staking) external onlyOwner {
require(stakingContract == address(0), "Already set");
require(_staking != address(0), "Zero address");
stakingContract = _staking;
}
/// Set once, to the Staking contract. Permanent for the same
/// reason setStakingContract is: a hook that can be repointed is
/// a hook that can be repointed at an attacker's contract, and it
/// is called on every transfer.
function setDividendHook(address h) external onlyOwner {
require(address(dividendHook) == address(0), "Already set");
require(h != address(0), "Zero address");
dividendHook = IStakedTokenHook(h);
emit DividendHookSet(h);
}
function setOperator(address op, bool ok) external onlyOwner {
isOperator[op] = ok;
emit OperatorSet(op, ok);
}
modifier onlyStaking() {
require(msg.sender == stakingContract, "Only staking contract");
_;
}
// ── Mint / burn ─────────────────────────────────────────
// Both route through _mint/_burn -> _update, so raw balance
// accounting happens in exactly one place.
function mint(address to, uint256 amount) external onlyStaking {
_mint(to, amount);
}
function burn(address from, uint256 amount) external onlyStaking {
_burn(from, amount);
}
// ── Rebase ──────────────────────────────────────────────
function rebase(uint256 profit, uint256 totalStaked) external onlyStaking {
if (totalStaked == 0 || profit == 0) return;
index = index + (index * profit) / totalStaked;
emit Rebase(index, profit);
}
// ── Balance views driven by index ───────────────────────
function balanceOf(address account) public view override returns (uint256) {
return (_rawBalances[account] * index) / 1e9;
}
function totalSupply() public view override returns (uint256) {
return (_totalRawSupply * index) / 1e9;
}
function rawBalanceOf(address account) external view returns (uint256) {
return _rawBalances[account];
}
// ── Single accounting path ──────────────────────────────
// Mint: from == address(0)
// Burn: to == address(0)
// Transfer: only if staking contract is sender or receiver
function _update(address from, address to, uint256 value) internal override {
if (from != address(0) && to != address(0)) {
require(
from == stakingContract || to == stakingContract ||
isOperator[msg.sender] || isOperator[from] || isOperator[to],
"sToken: non-transferable"
);
}
// Bank what each side has accrued at the CURRENT balance,
// before that balance changes. Skipped when no hook is set,
// which is how the contract behaves in isolation and in the
// tests that predate dividends.
if (address(dividendHook) != address(0)) {
dividendHook.settleOnTransfer(from, to);
}
uint256 raw = (value * 1e9) / index;
require(raw > 0 || value == 0, "sToken: amount too small");
if (from == address(0)) {
_totalRawSupply += raw;
} else {
require(_rawBalances[from] >= raw, "sToken: insufficient balance");
_rawBalances[from] -= raw;
}
if (to == address(0)) {
_totalRawSupply -= raw;
} else {
_rawBalances[to] += raw;
}
emit Transfer(from, to, value);
}
event Rebase(uint256 newIndex, uint256 profit);
event OperatorSet(address indexed op, bool allowed);
event DividendHookSet(address indexed hook);
}
contracts/Staking.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// Staking.sol - Stake base tokens, receive sTokens + rebases
//
// - Rebases only happen if the treasury can back new tokens
// - Rebase rate is capped (no infinite APY exploit)
// - Warmup period prevents flash-loan attacks
// - Revenue comes from bond profits, not pure inflation
// ============================================================
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./OlympusToken.sol";
import "./StakedToken.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Treasury.sol";
contract Staking is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
OlympusToken public immutable TOKEN;
StakedToken public immutable sTOKEN;
address public treasury;
address public bondDepository;
struct Epoch {
uint256 duration;
uint256 number;
uint256 endTime;
uint256 distribute;
}
Epoch public epoch;
// ── HOW OFTEN, AND HOW MUCH ─────────────────────────────
//
// The cap is PER EPOCH, so it only means something alongside the
// epoch length. At eight-hour epochs, 0.5% each was about 1.5% a
// day. Shorten the epoch without shortening the cap and the same
// figure becomes an absurd rate; lengthen it and the payout
// crawls.
//
// Nothing here mints. Treasury.bondDeposit already minted the
// profit and checked it against the 1.3x ceiling, so this only
// decides how SMOOTHLY an amount that already exists is released.
// A short epoch with a proportionally smaller cap pays out the
// same total, just continuously - which is the point.
//
// MAX_REBASE_RATE is the hard ceiling on what governance may set,
// not the setting itself.
uint256 public constant MAX_REBASE_RATE = 50; // 0.5% per epoch, ever
uint256 public rebaseRateBPS = 50;
uint256 public warmupPeriod = 1;
struct Claim {
uint256 deposit;
uint256 gons;
uint256 expiry;
bool lock;
}
mapping(address => Claim) public warmupInfo;
constructor(
address _token,
address _sToken,
address _treasury,
uint256 _epochDuration,
uint256 _firstEpochTime
) Ownable(msg.sender) {
TOKEN = OlympusToken(_token);
sTOKEN = StakedToken(_sToken);
treasury = _treasury;
epoch = Epoch({
duration: _epochDuration,
number: 0,
endTime: _firstEpochTime,
distribute: 0
});
}
function stake(uint256 amount, address recipient) external nonReentrant {
require(amount > 0, "Cannot stake 0");
rebase();
TOKEN.transferFrom(msg.sender, address(this), amount);
_accountedSLM += amount;
// Store the position in INDEX units, not nominal tokens.
//
// Previously both fields held the nominal amount and claim()
// returned `deposit`. If a rebase landed during warmup, the
// sSLM held here grew but the claimer still received their
// original figure - the difference stranded in the contract,
// attributable to nobody. `gons` existed for this and was
// never used.
uint256 raw = (amount * 1e9) / sTOKEN.index();
Claim memory info = warmupInfo[recipient];
warmupInfo[recipient] = Claim({
deposit: info.deposit + amount,
gons: info.gons + raw,
expiry: epoch.number + warmupPeriod,
lock: false
});
sTOKEN.mint(address(this), amount);
emit Staked(recipient, amount);
}
function claim(address recipient) external nonReentrant {
if (address(dividendToken) != address(0)) _settle(recipient);
Claim memory info = warmupInfo[recipient];
require(info.gons > 0, "Nothing to claim");
require(epoch.number >= info.expiry, "Warmup not complete");
// Convert the index-adjusted position back at the CURRENT
// index, so a rebase during warmup accrues to the staker
// rather than being left behind.
uint256 value = (info.gons * sTOKEN.index()) / 1e9;
delete warmupInfo[recipient];
IERC20(address(sTOKEN)).transfer(recipient, value);
emit Claimed(recipient, value);
}
function unstake(uint256 amount, bool trigger) external nonReentrant {
require(amount > 0, "Cannot unstake 0");
if (address(dividendToken) != address(0)) _settle(msg.sender);
if (trigger) rebase();
sTOKEN.burn(msg.sender, amount);
require(TOKEN.balanceOf(address(this)) >= amount, "Insufficient liquidity");
_accountedSLM = _accountedSLM > amount ? _accountedSLM - amount : 0;
TOKEN.transfer(msg.sender, amount);
emit Unstaked(msg.sender, amount);
}
/// Advance every epoch that has passed, not just one.
///
/// It used to advance a single epoch per call. With eight-hour
/// epochs that was almost invisible; with epochs short enough to
/// feel continuous it would fall permanently behind, because the
/// clock only ever moved forward by one step however long nobody
/// called it.
///
/// Bounded, so a contract left alone for a year cannot be made
/// unusable by the cost of catching up. Anything beyond the bound
/// is caught up by calling again.
uint256 public constant MAX_CATCHUP = 200;
function rebase() public {
for (uint256 i = 0; i < MAX_CATCHUP; i++) {
if (epoch.endTime > block.timestamp) break;
_advance();
}
}
function _advance() internal {
{
epoch.number++;
epoch.endTime = epoch.endTime + epoch.duration;
uint256 totalStaked = sTOKEN.totalSupply();
if (totalStaked > 0 && epoch.distribute > 0) {
uint256 maxDistribute = (totalStaked * rebaseRateBPS) / 10000;
uint256 toDistribute = epoch.distribute > maxDistribute
? maxDistribute
: epoch.distribute;
// NO MINT HERE.
//
// Treasury.bondDeposit already minted `profit` to this
// contract and validated it against the 1.3x ceiling.
// Minting again would create supply with no reserves
// behind it, lower the floor on every rebase, and push
// the protocol through its own backing invariant with
// no check to stop it.
//
// Carry the remainder forward instead of discarding it,
// so a rebase capped at 0.5% pays out over more epochs
// rather than burning the excess.
epoch.distribute -= toDistribute;
sTOKEN.rebase(toDistribute, totalStaked);
emit EpochRebase(epoch.number, toDistribute, totalStaked);
} else {
emit EpochRebase(epoch.number, 0, totalStaked);
}
}
}
function queueDistribution(uint256 amount) external {
require(msg.sender == treasury, "Only treasury");
epoch.distribute += amount;
emit DistributionQueued(amount);
}
/// One-time link to the bond depository.
///
/// DELIBERATELY PERMANENT, like setStaking on the Treasury. A
/// depository that can be repointed is a depository that can be
/// repointed at an attacker's contract, and there is no timelock
/// here to make that visible in advance. The cost is that a
/// broken depository cannot be swapped - it would need a full
/// redeployment. That trade is taken knowingly.
function setBondDepository(address _bd) external onlyOwner {
require(bondDepository == address(0), "Already set");
require(_bd != address(0), "Zero address");
bondDepository = _bd;
}
/// Stake on behalf of a vesting bond position.
///
/// No warmup: the five-day vest is already a longer lock than
/// warmup provides, so the flash-loan protection warmup exists
/// for is redundant here. Caller must have transferred `amount`
/// of SLM to this contract first - checked, not trusted.
function stakeFor(address to, uint256 amount) external {
require(msg.sender == bondDepository, "Only bond depository");
if (address(dividendToken) != address(0)) _settle(to);
require(amount > 0, "Cannot stake 0");
require(
TOKEN.balanceOf(address(this)) >= _accountedSLM + amount,
"SLM not received"
);
_accountedSLM += amount;
rebase();
sTOKEN.mint(to, amount);
emit Staked(to, amount);
}
/// SLM this contract has accepted against sSLM claims. Used to
/// verify a bond payout actually arrived before minting sSLM.
uint256 private _accountedSLM;
// ══ Staker dividends ══════════════════════════════════════
//
// Rebase pays the staker share of each bond mint, so it pays
// nothing when bonds are closed - and bonds close whenever the
// premium is thin. This is the second stream: a slice of fee
// revenue, paid in the reserve asset, independent of bonding.
//
// Accounted per RAW balance rather than per sSLM, because sSLM
// grows on rebase while raw does not. Using sSLM would let a
// rebase silently redistribute unclaimed dividends.
//
// Pull-based: no loop over holders, no gas that scales with
// participation. A position opened today has no claim on
// revenue that arrived yesterday.
Treasury public treasuryC;
IERC20 public dividendToken;
uint256 public accPerRaw; // scaled 1e18
uint256 public totalDividends;
mapping(address => uint256) public divDebt;
mapping(address => uint256) public divOwed;
function setDividends(address _treasury, address _token) external onlyOwner {
require(address(dividendToken) == address(0), "Already set");
treasuryC = Treasury(_treasury);
dividendToken = IERC20(_token);
}
/// Pull the accumulated staker slice and credit it across every
/// raw unit staked. Permissionless - the funds can only ever
/// reach stakers.
function distributeDividends() external nonReentrant returns (uint256 amount) {
require(address(dividendToken) != address(0), "Dividends not wired");
// Warmup positions are held by this contract, not by a
// staker. Counting them would dilute every dividend into a
// balance nobody can ever claim from.
uint256 rawTotal = (sTOKEN.totalSupply() * 1e9) / sTOKEN.index();
uint256 rawHere = _rawOf(address(this));
rawTotal = rawTotal > rawHere ? rawTotal - rawHere : 0;
require(rawTotal > 0, "Nothing staked");
address t = address(dividendToken);
amount = treasuryC.stakerAllocation(t);
require(amount > 0, "Nothing to distribute");
uint256 before = dividendToken.balanceOf(address(this));
treasuryC.claimStakerAllocation(t, amount);
uint256 got = dividendToken.balanceOf(address(this)) - before;
accPerRaw += (got * 1e18) / rawTotal;
totalDividends += got;
emit DividendsDistributed(got, accPerRaw);
}
function _rawOf(address a) internal view returns (uint256) {
return (sTOKEN.balanceOf(a) * 1e9) / sTOKEN.index();
}
/// Move anything newly accrued into the owed ledger. Called
/// before any change to a holder's raw balance.
///
/// Skips this contract's own holdings. sSLM minted into warmup
/// sits here until claim(), and it is not a staker's position -
/// crediting it would move dividends into a balance that has no
/// way to withdraw them.
function _settle(address a) internal {
if (a == address(0) || a == address(this)) return;
uint256 raw = _rawOf(a);
uint256 acc = accPerRaw;
if (raw > 0 && acc > divDebt[a]) {
divOwed[a] += ((acc - divDebt[a]) * raw) / 1e18;
}
divDebt[a] = acc;
}
/// Called by the sSLM contract before any balance moves, so a
/// transfer settles both sides. Without it a holder who RECEIVES
/// sSLM by transfer - which is exactly what a bond redemption is -
/// keeps a dividend debt of zero and can immediately claim the
/// protocol's entire dividend history on a balance they have held
/// for one block.
function settleOnTransfer(address from, address to) external {
require(msg.sender == address(sTOKEN), "Only the staked token");
_settle(from);
_settle(to);
}
function pendingDividends(address a) external view returns (uint256) {
uint256 raw = _rawOf(a);
uint256 extra = (accPerRaw > divDebt[a] && raw > 0)
? ((accPerRaw - divDebt[a]) * raw) / 1e18 : 0;
return divOwed[a] + extra;
}
function claimDividends() external nonReentrant returns (uint256 amount) {
_settle(msg.sender);
amount = divOwed[msg.sender];
require(amount > 0, "Nothing pending");
divOwed[msg.sender] = 0;
dividendToken.safeTransfer(msg.sender, amount);
emit DividendsClaimed(msg.sender, amount);
}
event DividendsDistributed(uint256 amount, uint256 newAccPerRaw);
event DividendsClaimed(address indexed to, uint256 amount);
/// How long an epoch lasts, and how much may be released in each.
///
/// The two move together: halve the duration and the rate should
/// halve too, or the payout doubles. Setting them in one call
/// makes that hard to forget.
function setEpoch(uint256 duration, uint256 rateBPS) external onlyOwner {
require(duration >= 1 minutes && duration <= 7 days, "Duration out of range");
require(rateBPS > 0 && rateBPS <= MAX_REBASE_RATE, "Rate out of range");
rebase(); // settle the old cadence first
epoch.duration = duration;
rebaseRateBPS = rateBPS;
emit EpochSet(duration, rateBPS);
}
/// Epochs that have passed and not yet been applied. Zero means
/// the rebase is up to date.
function pendingEpochs() external view returns (uint256 n) {
if (epoch.endTime > block.timestamp) return 0;
n = ((block.timestamp - epoch.endTime) / epoch.duration) + 1;
if (n > MAX_CATCHUP) n = MAX_CATCHUP;
}
function setWarmupPeriod(uint256 _warmup) external onlyOwner {
require(_warmup <= 5, "Max 5 epochs");
warmupPeriod = _warmup;
}
function setTreasury(address _treasury) external onlyOwner {
require(_treasury != address(0), "Invalid address");
treasury = _treasury;
}
event Staked(address indexed user, uint256 amount);
event Claimed(address indexed user, uint256 amount);
event Unstaked(address indexed user, uint256 amount);
event EpochRebase(uint256 indexed epoch, uint256 distributed, uint256 totalStaked);
event DistributionQueued(uint256 amount);
event EpochSet(uint256 duration, uint256 rateBPS);
}
contracts/Treasury.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// ============================================================
// Treasury.sol v3 - Dynamic supply ceiling + burn mechanisms
//
// PATCH NOTES (v2 -> v3):
// 1. _normalizeDecimals() was a no-op returning its input.
// A 6-decimal USDC deposit of $100,000 registered as
// 0.0000000001 in totalReserves, destroying the backing
// ratio. Now scales any ERC20 to 18 decimals.
// 2. bondRedemptionBurn() burned from address(this) - the
// Treasury holds no SLM, so it always reverted. Now burns
// from the caller (BondDepository), which does hold the
// unvested payout.
// 3. Added burnFromCaller path used by BondDepository so the
// 1% redemption burn is actually reachable.
//
// SUPPLY MODEL (unchanged):
// maxSupply = totalReserves * 1e18 / MIN_BACKING_RATIO (1.3)
// ============================================================
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./OlympusToken.sol";
import "./Staking.sol";
import "./IReserveOracle.sol";
interface IOracleLock { function locked() external view returns (bool); }
contract Treasury is AccessControl, ReentrancyGuard {
using SafeERC20 for IERC20;
bytes32 public constant BOND_DEPOSITOR_ROLE = keccak256("BOND_DEPOSITOR");
bytes32 public constant RESERVE_MANAGER_ROLE = keccak256("RESERVE_MANAGER");
bytes32 public constant BURN_EXECUTOR_ROLE = keccak256("BURN_EXECUTOR");
bytes32 public constant FEE_COLLECTOR_ROLE = keccak256("FEE_COLLECTOR");
OlympusToken public immutable TOKEN;
Staking public staking;
mapping(address => bool) public isReserveToken;
address[] public reserveTokens;
uint256 public totalReserves;
/// Each token's recorded contribution to totalReserves, 18dp.
/// Needed so a delisted asset can be removed without guessing.
mapping(address => uint256) public reserveBalance;
// ── Reserve quality ─────────────────────────────────────
// Redemption cannot drain the treasury; a broken reserve can.
// The oracle is optional: without it every reserve is valued at
// par, which is the behaviour that already shipped.
IReserveOracle public reserveOracle;
uint256 public constant DEPEG_THRESHOLD = 0.95e18;
uint256 public constant MAX_SHORTFALL_BPS = 200;
// ── DELISTING, AND WHY IT IS SLOW ───────────────────────
//
// removeReserveToken is the ONE path exempt from the floor
// ratchet. It has to be: backing that is not worth what it claims
// was never really backing, and pretending otherwise is how a
// depeg becomes an unpayable promise.
//
// But it was instant, and rescueDelisted then sent the whole
// balance to any address the caller named. So with one approved
// reserve - which is what Solum has - a stablecoin dipping to
// $0.949 for a single block let whoever holds the admin key strip
// the recorded value from totalReserves, reset the high-water
// floor, and walk away with tokens still worth 95 cents. The
// protocol's one rule, defeated by a five percent wobble and one
// transaction.
//
// So delisting is now two steps with a day between them, and the
// price must still be broken when the second one lands. Real
// depegs last; the March 2023 USDC break was three days. Wobbles
// do not.
//
// And what comes out goes to an address set in advance, in the
// open, not one chosen at the moment of the call.
// ── WHAT MAY BE A RESERVE ───────────────────────────────
//
// totalReserves is a DOLLAR figure. collectFees and seedReserves
// scale a deposit by its decimals and add it at par - one token,
// one dollar - and redeem() pays out against that same figure.
//
// So an asset that is not worth a dollar cannot be a reserve. Add
// a tokenised stock at $300 and the Treasury records $1 of backing
// per token while redemption hands out one token per dollar
// claimed: the floor becomes fiction and the treasury empties at
// three hundred to one. Add $SLM itself and the backing is
// circular, which is the same thing said faster.
//
// Yield, tokenised equities and anything else that moves belong
// OUTSIDE this figure - earning on the earmarked slices, or in a
// separate vault whose profits arrive here as dollars through
// collectFees, the way RevenueAdapter already works. See
// docs/solum-treasury-strategy.md.
uint256 public constant MIN_RESERVE_PRICE = 0.98e18;
uint256 public constant MAX_RESERVE_PRICE = 1.02e18;
uint256 public constant DELIST_DELAY = 24 hours;
mapping(address => uint256) public depegFlaggedAt;
address public recoveryAddress;
uint256 public constant MIN_BACKING_RATIO = 13e17; // 1.3x
// The least the floor may be, in the reserve per whole token, 18 decimals (16 Oct 2026, Hollow's
// launchpad). 1e18 is the rule as it always was: every token backed by at least 1.3 whole units
// of the reserve. A launchpad token sized in billions sets it lower ONCE, before any supply exists
// (setMinFloor); the 1.3x rule then counts in that unit. Keel and Solum never call it.
uint256 public minFloor = 1e18;
uint256 public swapFeeBurnBPS = 0;
uint256 public constant MAX_BURN_BPS = 5000;
uint256 public constant BOND_REDEMPTION_BURN_BPS = 100; // 1%
uint256 public totalBurned;
uint256 public excessReserves;
// ── Swap fee intake ─────────────────────────────────────
// Fees accrue in a creator-fee wallet on the DEX. A collector
// sweeps them here. A slice is earmarked for agent gas; the
// rest becomes reserves and lifts the floor.
//
// CRITICAL: the agent slice is tracked SEPARATELY and never
// added to totalReserves. Money earmarked to leave must never
// back the floor, or every keeper withdrawal would silently
// lower it.
uint256 public agentAllocationBPS = 300; // 3%, per architecture spec
// 25% rather than 10%. In the engine configuration the "agent" is the
// operator running the bots that produce every dollar of revenue, and
// a slice that keeps them running is worth more than a slice that
// optimises reserves. The combined 40% cap still bounds the total.
uint256 public constant MAX_AGENT_ALLOCATION_BPS = 2500; // 10% ceiling
// ── Node dividend ───────────────────────────────────────
// A slice of fee revenue for Swarm Node holders, segregated on
// arrival exactly like the agent gas allocation.
//
// WHY IT CANNOT COME FROM THE TREASURY:
// The ratchet sets highWaterFloor to the current floor on every
// accretive action, so withdrawableReserves() is permanently
// zero. There is no spendable surplus in this protocol - every
// dollar of reserves is holding the floor up.
//
// So a dividend has to be taken BEFORE fees become reserves.
// Money that never backed the floor cannot lower it by leaving.
//
// THE TRADE IS EXACT AND VISIBLE:
// Floor growth is turnover x fee x premium-multiple. Every
// basis point routed to nodes is a basis point off that. At 10%
// the floor compounds at 6.4%/yr instead of 7.2%.
//
// Worth it only if node holders drive more than 10% additional
// volume - turnover being the other multiplier. That is the
// argument for the mechanism, and it is a bet, not a certainty.
uint256 public nodeAllocationBPS = 0; // off until nodes exist
uint256 public constant MAX_NODE_ALLOCATION_BPS = 2500; // 25% ceiling
address public nodeDistributor;
mapping(address => uint256) public nodeAllocation; // token => raw owed
// ── Staker dividend ─────────────────────────────────────
// Staking's only yield used to be the staker share of each bond
// mint, which meant no bonds paid no yield - and bonds close
// whenever the premium is thin. This gives staking a revenue
// source that does not depend on bond activity.
//
// Segregated on arrival like the others. Money that never backed
// the floor cannot lower it by leaving.
uint256 public stakerAllocationBPS = 0; // off until switched on
// ── Founder allocation ──────────────────────────────────
//
// A slice of fee revenue to the founders, paid in the reserve
// asset. Segregated on arrival like every other slice, so it
// never counts as backing and redemption can never reach it.
//
// Sits inside the same 40% combined cap. Capped on its own at 5%,
// because a founder fee above that is a founder fee that someone
// will reasonably ask about, and the answer should be "no".
uint256 public founderAllocationBPS = 0;
uint256 public constant MAX_FOUNDER_ALLOCATION_BPS = 500;
address public founderRecipient;
mapping(address => uint256) public founderAllocation;
uint256 public constant MAX_STAKER_ALLOCATION_BPS = 2500;
// ── Finalize ────────────────────────────────────────────
// The admin key can, until this is called, re-cut the revenue
// split, move the founder recipient and swap the reserve oracle.
// finalize() ends all six of those, and adding a reserve token,
// permanently. There is no
// function that sets this back; the tests prove the ABI has none.
// What stays adjustable afterwards is listed on the Verify tab:
// redemption fee and cap within their bounds, the burn share, the
// recovery address, and the two one-shot distributor setters.
bool public finalized;
/// After finalize() the admin can no longer hand out the roles that
/// mint (BOND_DEPOSITOR), reduce reserves (BURN_EXECUTOR) or move
/// them (RESERVE_MANAGER). A key that could still grant itself
/// BOND_DEPOSITOR after finalize could mint at exactly 1.3x the
/// floor with no premium (2 Oct review, M4). FEE_COLLECTOR stays
/// grantable: a new collector can only add money.
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
if (finalized) {
require(role != BOND_DEPOSITOR_ROLE && role != BURN_EXECUTOR_ROLE && role != RESERVE_MANAGER_ROLE, "Finalized");
}
_grantRole(role, account);
}
modifier notFinalized() {
require(!finalized, "Finalized");
_;
}
address public stakerDistributor;
mapping(address => uint256) public stakerAllocation;
mapping(address => uint256) public agentAllocation; // token => raw units owed to agent ops
uint256 public totalFeesCollected; // normalised, lifetime, reserves portion only
constructor(address _token) {
TOKEN = OlympusToken(_token);
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// Anyone may push the ratchet up. Permissionless by design -
/// recording that the floor rose must never depend on an admin.
function ratchet() external {
_ratchet();
}
// ── Swap Fee Collection ─────────────────────────────────
// The path by which agent trading revenue reaches the floor.
// Caller must hold FEE_COLLECTOR_ROLE and have approved this
// contract for `amount` of `token`.
function collectFees(address token, uint256 amount)
external onlyRole(FEE_COLLECTOR_ROLE) nonReentrant
{
require(isReserveToken[token], "Not approved reserve");
require(amount > 0, "Nothing to collect");
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
_split(token, amount);
_updateExcessReserves();
_ratchet();
}
/// The split every revenue dollar goes through: the agent, node,
/// staker and founder slices are set aside first, the rest is
/// backing. Shared by collectFees and the premium on a bond. The
/// tokens must already be in this contract.
function _split(address token, uint256 amount) internal {
uint256 toAgents = (amount * agentAllocationBPS) / 10000;
uint256 toNodes = (amount * nodeAllocationBPS) / 10000;
uint256 toStakers = (amount * stakerAllocationBPS) / 10000;
uint256 toFounders = (amount * founderAllocationBPS) / 10000;
uint256 toReserves = amount - toAgents - toNodes - toStakers - toFounders;
if (toAgents > 0) agentAllocation[token] += toAgents;
if (toNodes > 0) nodeAllocation[token] += toNodes;
if (toStakers > 0) stakerAllocation[token] += toStakers;
if (toFounders > 0) founderAllocation[token] += toFounders;
uint256 normalised = _normalizeDecimals(token, toReserves);
totalReserves += normalised;
reserveBalance[token] += normalised;
totalFeesCollected += normalised;
emit FeesCollected(token, amount, toReserves, toAgents, toNodes);
}
/// Keeper pulls the earmarked agent slice to fund gas.
/// Cannot touch reserves - draws only from agentAllocation,
/// so the backing ratio is arithmetically untouched.
/// Once set, the only contract that may draw the agent slice. The
/// RevenueAdapter, which pays it to the operator and nowhere else.
/// Without it any RESERVE_MANAGER could send the slice anywhere,
/// which made finalizeOperator() a promise the Treasury did not keep.
address public agentWithdrawer;
function setAgentWithdrawer(address w) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(agentWithdrawer == address(0), "Already set");
require(w != address(0), "Zero address");
agentWithdrawer = w;
emit AgentWithdrawerSet(w);
}
function withdrawAgentAllocation(address token, address to, uint256 amount)
external onlyRole(RESERVE_MANAGER_ROLE) nonReentrant
{
require(agentWithdrawer == address(0) || msg.sender == agentWithdrawer, "Only the agent withdrawer");
require(to != address(0), "Zero address");
require(amount > 0, "Nothing to withdraw");
require(amount <= agentAllocation[token], "Exceeds agent allocation");
agentAllocation[token] -= amount;
IERC20(token).safeTransfer(to, amount);
emit AgentAllocationWithdrawn(token, to, amount);
}
/// The node distributor pulls the accumulated slice and splits it
/// among holders. Set once; a distributor that can be swapped is
/// a distributor that can be pointed anywhere.
function setNodeDistributor(address d) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(nodeDistributor == address(0), "Already set");
require(d != address(0), "Zero address");
nodeDistributor = d;
emit NodeDistributorSet(d);
}
function setNodeAllocationBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(bps <= MAX_NODE_ALLOCATION_BPS, "Max 25%");
require(agentAllocationBPS + bps <= 3000, "Agent + node above 30%");
require(agentAllocationBPS + bps + stakerAllocationBPS + founderAllocationBPS <= 4000,
"Allocations above 40%");
emit NodeAllocationSet(nodeAllocationBPS, bps);
nodeAllocationBPS = bps;
}
/// Only the distributor may draw it, and only from the segregated
/// slice. Reserves are untouchable through this path, so the floor
/// is arithmetically unaffected.
function claimNodeAllocation(address token, uint256 amount)
external nonReentrant
{
require(msg.sender == nodeDistributor, "Only node distributor");
require(amount > 0, "Nothing to claim");
require(amount <= nodeAllocation[token], "Exceeds node allocation");
nodeAllocation[token] -= amount;
IERC20(token).safeTransfer(nodeDistributor, amount);
emit NodeAllocationClaimed(token, amount);
}
function setStakerDistributor(address d) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(stakerDistributor == address(0), "Already set");
require(d != address(0), "Zero address");
stakerDistributor = d;
emit StakerDistributorSet(d);
}
function setStakerAllocationBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(bps <= MAX_STAKER_ALLOCATION_BPS, "Max 25%");
require(agentAllocationBPS + nodeAllocationBPS + founderAllocationBPS + bps <= 4000,
"Allocations above 40%");
emit StakerAllocationSet(stakerAllocationBPS, bps);
stakerAllocationBPS = bps;
}
function setFounderAllocationBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(bps <= MAX_FOUNDER_ALLOCATION_BPS, "Max 5%");
require(agentAllocationBPS + nodeAllocationBPS + stakerAllocationBPS + bps <= 4000,
"Allocations above 40%");
emit FounderAllocationSet(founderAllocationBPS, bps);
founderAllocationBPS = bps;
}
/// Where the founder slice goes. A FounderSplit contract if there
/// is more than one founder; a wallet if there is one.
function setFounderRecipient(address r) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(r != address(0), "Zero address");
emit FounderRecipientSet(founderRecipient, r);
founderRecipient = r;
}
/// Send the accumulated founder slice to the recipient.
/// Permissionless: nobody gains from calling it except the
/// founders, who are collecting what they are already owed.
function claimFounderAllocation(address token) external nonReentrant {
require(founderRecipient != address(0), "No founder recipient");
uint256 amount = founderAllocation[token];
require(amount > 0, "Nothing to claim");
founderAllocation[token] = 0;
IERC20(token).safeTransfer(founderRecipient, amount);
emit FounderAllocationClaimed(token, founderRecipient, amount);
}
function claimStakerAllocation(address token, uint256 amount)
external nonReentrant
{
require(msg.sender == stakerDistributor, "Only staker distributor");
require(amount > 0, "Nothing to claim");
require(amount <= stakerAllocation[token], "Exceeds staker allocation");
stakerAllocation[token] -= amount;
IERC20(token).safeTransfer(stakerDistributor, amount);
emit StakerAllocationClaimed(token, amount);
}
function setAgentAllocationBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(bps <= MAX_AGENT_ALLOCATION_BPS, "Max 25%");
require(bps + nodeAllocationBPS + stakerAllocationBPS + founderAllocationBPS <= 4000,
"Allocations above 40%");
emit AgentAllocationSet(agentAllocationBPS, bps);
agentAllocationBPS = bps;
}
// ── Bond Deposit ────────────────────────────────────────
// Caller (BondDepository) must hold reserveAmount and have
// approved this contract. See BondDepository.deposit().
//
// Where a bond's dollars go (2 Oct 2026). The part that backs the
// minted tokens at 1.3x the floor as it stood before the bond goes
// straight to reserves, before the mint, so the floor cannot move
// down by construction. Everything above that is the premium, and
// it goes through the same split as every revenue dollar: founders,
// nodes, lockers, and the rest to reserves. A bond that only filled
// the vault would raise the floor and pay lockers nothing; this way
// lockers and the nodes earn from every bond. The depository quotes
// the mint on the whole deposit against the 1.3x ceiling, and the
// ceiling is checked again here on what actually landed.
//
// No floor, no bond (4 Oct 2026 review, H1). Before Keel's genesis
// the floor and its high-water mark are 0, so the backing for a mint
// priced at that floor was $0 and the only limit was the 1.3x
// ceiling: whoever could grant BOND_DEPOSITOR could mint the whole
// ceiling for nothing, brick KeelGenesis and redeem the ticket money
// out. A bond now needs a floor that has been recorded first.
function bondDeposit(
address reserveToken,
uint256 reserveAmount,
uint256 tokensMinted,
uint256 profit
) external onlyRole(BOND_DEPOSITOR_ROLE) nonReentrant reservesSound floorMustHold {
_floorExists();
require(isReserveToken[reserveToken], "Not approved reserve");
require(tokensMinted + profit > 0, "Nothing to do");
IERC20(reserveToken).safeTransferFrom(msg.sender, address(this), reserveAmount);
// backing for the mint, at the floor before this bond
uint256 minted = tokensMinted + profit;
uint256 backing = (minted * priceFloor() / 1e18) * MIN_BACKING_RATIO / 1e18; // 18-dec
uint256 backingRaw = _denormalizeDecimals(reserveToken, backing);
if (backingRaw > reserveAmount) backingRaw = reserveAmount; // all of it, if the quote was that tight
uint256 premiumRaw = reserveAmount - backingRaw;
uint256 _n1 = _normalizeDecimals(reserveToken, backingRaw);
totalReserves += _n1;
reserveBalance[reserveToken] += _n1;
if (premiumRaw > 0) _split(reserveToken, premiumRaw);
uint256 newSupply = TOKEN.totalSupply() + minted;
uint256 maxAllowable = supplyCeiling();
require(newSupply <= maxAllowable, "Would breach 1.3x backing ceiling");
if (tokensMinted > 0) TOKEN.mint(msg.sender, tokensMinted);
if (profit > 0 && address(staking) != address(0)) {
TOKEN.mint(address(staking), profit);
staking.queueDistribution(profit);
}
_updateExcessReserves();
_ratchet();
emit BondDeposit(reserveToken, reserveAmount, tokensMinted, profit);
emit BondPremium(reserveToken, backingRaw, premiumRaw);
}
// ── Burn 1: Swap Fee Buyback & Burn ─────────────────────
function executeSwapFeeBurn(
address reserveToken,
uint256 reserveAmount,
uint256 tokenAmount
) external onlyRole(BURN_EXECUTOR_ROLE) nonReentrant floorMustHold {
_floorExists();
require(swapFeeBurnBPS > 0, "Burn rate not set by governance");
require(tokenAmount > 0, "Nothing to burn");
require(isReserveToken[reserveToken], "Not approved reserve");
TOKEN.burn(msg.sender, tokenAmount);
totalBurned += tokenAmount;
uint256 val = _normalizeDecimals(reserveToken, reserveAmount);
require(val <= totalReserves, "Exceeds reserves");
totalReserves -= val;
reserveBalance[reserveToken] = reserveBalance[reserveToken] > val ? reserveBalance[reserveToken] - val : 0;
_updateExcessReserves();
_ratchet();
emit TokensBurned(tokenAmount, "Swap fee buyback");
}
// ── Burn 2: Bond Redemption 1% Burn ─────────────────────
// PATCHED: burns from msg.sender (BondDepository), which
// holds the unvested payout. v2 burned from address(this).
function bondRedemptionBurn(uint256 payoutAmount)
external
onlyRole(BOND_DEPOSITOR_ROLE)
nonReentrant
returns (uint256 burnAmount, uint256 deliverAmount)
{
burnAmount = (payoutAmount * BOND_REDEMPTION_BURN_BPS) / 10000;
deliverAmount = payoutAmount - burnAmount;
if (burnAmount > 0) {
TOKEN.burn(msg.sender, burnAmount);
totalBurned += burnAmount;
_updateExcessReserves();
emit TokensBurned(burnAmount, "Bond redemption 1%");
}
}
// ── Burn 3: NFT Mint Proceeds Buyback & Burn ────────────
/// Burn supply without touching reserves.
///
/// Permissionless by design. The caller must first approve this
/// contract for the amount, and it burns their own tokens. There
/// is no attack here: destroying supply while reserves stay put
/// can only raise the floor, so anyone willing to pay for it is
/// doing every other holder a favour.
///
/// Used by the inventory escrow when captured supply cannot be
/// sold, and available to anyone else who wants it.
function burnSupply(uint256 amount) external nonReentrant {
require(amount > 0, "Nothing to burn");
IERC20(address(TOKEN)).safeTransferFrom(msg.sender, address(this), amount);
TOKEN.burn(address(this), amount);
totalBurned += amount;
_updateExcessReserves();
_ratchet();
emit TokensBurned(amount, "Supply burn");
}
function nftMintBurn(
address reserveToken,
uint256 reserveAmount,
uint256 tokenAmount
) external onlyRole(BURN_EXECUTOR_ROLE) nonReentrant {
require(tokenAmount > 0, "Nothing to burn");
require(isReserveToken[reserveToken], "Not approved reserve");
TOKEN.burn(msg.sender, tokenAmount);
totalBurned += tokenAmount;
IERC20(reserveToken).safeTransferFrom(msg.sender, address(this), reserveAmount);
uint256 _n2 = _normalizeDecimals(reserveToken, reserveAmount);
totalReserves += _n2;
reserveBalance[reserveToken] += _n2;
_updateExcessReserves();
_ratchet();
emit TokensBurned(tokenAmount, "NFT mint buyback");
}
// Burn 4 (expired bonds) was REMOVED.
//
// It was never reachable: BondDepository has no expiry logic and
// notes stay redeemable indefinitely. Dead privileged code is an
// audit finding whether or not it can be called.
//
// Expiry was not implemented instead, deliberately. A protocol
// whose central claim is that you can always exit should not have
// a mechanism that confiscates unclaimed tokens.
//
// Three burn paths remain: bond redemption, swap fee buyback and
// NFT mint. The documents should say three, not four.
// ── Redemption ──────────────────────────────────────────
// Burn $SLM, receive reserves at the price floor.
//
// WHY THIS EXISTS:
// Without it the floor is an accounting figure, not a price
// anyone is obliged to pay. Nothing stops the market trading
// below it, and the only defence is an agent with finite
// capital. With it, any discount to the floor is a risk-free
// arbitrage and the floor enforces itself.
//
// WHY IT STRENGTHENS THE PROTOCOL:
// Backing per token is reserves/supply. The floor is
// reserves/(supply * 1.3). Redemption therefore pays out LESS
// than the token's share of reserves, and the difference stays
// behind backing fewer tokens. Every redemption raises the
// floor for everyone who stays.
//
// The consequence is that last out wins, not first out. The
// usual bank-run incentive is inverted.
//
// NO PAUSE, BY DESIGN:
// Redemption is deliberately not pausable and not gated by any
// role. A floor that can be switched off during stress is not
// a floor. This is the one function that must work when
// everything else is on fire.
uint256 public redemptionFeeBPS = 50; // 0.5%, retained by treasury
uint256 public constant MAX_REDEMPTION_FEE_BPS = 200;
uint256 public maxRedemptionBPS = 100; // 1% of supply per call
uint256 public redemptionCooldown = 1 hours;
uint256 public totalRedeemed;
mapping(address => uint256) public lastRedemption;
/// Burn `amount` of $SLM and receive `reserveToken` at the floor.
///
/// SPLIT-EXTRACTION DEFENCE: because each burn nudges the floor
/// up, redeeming in many small calls would extract more than one
/// large call. Three limits close that: the whole amount is
/// priced off the floor as it stood at the start of this call,
/// a per-call size cap bounds the advantage to ~0.12%, and the
/// 0.5% fee exceeds it. Splitting loses money.
function redeem(address reserveToken, uint256 amount)
external nonReentrant floorMustHold returns (uint256 payout)
{
require(isReserveToken[reserveToken], "Not approved reserve");
require(amount > 0, "Nothing to redeem");
require(
block.timestamp >= lastRedemption[msg.sender] + redemptionCooldown,
"Redemption cooldown"
);
uint256 supply = TOKEN.totalSupply();
require(supply > 0, "No supply");
require(
amount <= (supply * maxRedemptionBPS) / 10000,
"Exceeds max redemption per call"
);
// Snapshot the floor BEFORE burning. The entire amount prices
// off this one value, so a large call is never worse than
// several small ones.
uint256 floorPrice = priceFloor();
require(floorPrice > 0, "No floor established");
uint256 gross = (amount * floorPrice) / 1e18;
uint256 fee = (gross * redemptionFeeBPS) / 10000;
uint256 net = gross - fee; // fee never leaves - it backs the floor
// Only reserves may be paid out. The agent gas allocation is
// earmarked and must never be reachable through this path.
uint256 raw = _denormalizeDecimals(reserveToken, net);
uint256 available = IERC20(reserveToken).balanceOf(address(this))
- agentAllocation[reserveToken]
- nodeAllocation[reserveToken]
- stakerAllocation[reserveToken]
- founderAllocation[reserveToken];
require(raw <= available, "Insufficient reserve token liquidity");
require(net <= totalReserves, "Insufficient reserves");
lastRedemption[msg.sender] = block.timestamp;
TOKEN.burn(msg.sender, amount);
totalBurned += amount;
totalReserves -= net;
reserveBalance[reserveToken] = reserveBalance[reserveToken] > net ? reserveBalance[reserveToken] - net : 0;
totalRedeemed += amount;
_updateExcessReserves();
_ratchet();
IERC20(reserveToken).safeTransfer(msg.sender, raw);
emit Redeemed(msg.sender, reserveToken, amount, raw, fee, priceFloor());
return raw;
}
/// What a redemption would pay right now, before executing.
function quoteRedemption(address reserveToken, uint256 amount)
external view returns (uint256 payout, uint256 fee)
{
uint256 floorPrice = priceFloor();
uint256 gross = (amount * floorPrice) / 1e18;
fee = (gross * redemptionFeeBPS) / 10000;
payout = _denormalizeDecimals(reserveToken, gross - fee);
}
// KNOWN AND ACCEPTED: SPLIT ADVANTAGE
//
// Redeeming in several small calls pays slightly more than one
// large call, because each burn lifts the floor before the next
// one prices against it. Measured advantage:
//
// 1% of supply -> 0.10% 5% of supply -> 0.54%
// 2% of supply -> 0.12% 10% of supply -> 1.20%
//
// The redemption fee does NOT defend against this. It is charged
// on both paths and cancels out. Only integral pricing -
// reserves * [1 - ((supply-n)/supply)^(1/1.3)]
// is split-invariant, and that needs fractional exponentiation.
// A fixed-point math library inside the one function that can
// never be paused is a worse risk than a 0.12% advantage.
//
// So it is bounded instead: a 2% size cap holds the advantage
// near 0.12%, and the per-address cooldown rate-limits it.
//
// Note this is not a drain. Both paths raise the floor. It is a
// small edge for sophisticated redeemers over naive ones, and
// it is documented rather than hidden.
uint256 public constant MIN_REDEMPTION_FEE_BPS = 50; // 0.5%
uint256 public constant MAX_REDEMPTION_SIZE_BPS = 200; // 2% of supply
function setRedemptionFeeBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(bps >= MIN_REDEMPTION_FEE_BPS, "Below split-extraction floor");
require(bps <= MAX_REDEMPTION_FEE_BPS, "Max 2%");
emit RedemptionFeeSet(redemptionFeeBPS, bps);
redemptionFeeBPS = bps;
}
function setMaxRedemptionBPS(uint256 bps) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(bps >= 10, "Min 0.1% of supply");
require(bps <= MAX_REDEMPTION_SIZE_BPS, "Above split-extraction ceiling");
maxRedemptionBPS = bps;
}
// ── Views ───────────────────────────────────────────────
function supplyCeiling() public view returns (uint256) {
return (totalReserves * 1e36) / (MIN_BACKING_RATIO * minFloor);
}
/// Once, before any supply exists: the floor's least value (see minFloor).
function setMinFloor(uint256 f) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(TOKEN.totalSupply() == 0 && highWaterFloor == 0, "Supply exists");
require(f > 0 && f <= 1e18, "Min floor out of range");
minFloor = f;
emit MinFloorSet(f);
}
function mintableHeadroom() public view returns (uint256) {
uint256 ceiling = supplyCeiling();
uint256 current = TOKEN.totalSupply();
return ceiling > current ? ceiling - current : 0;
}
function backingRatio() public view returns (uint256) {
uint256 supply = TOKEN.totalSupply();
if (supply == 0) return type(uint256).max;
return (totalReserves * 1e18) / supply;
}
/// USD of reserves behind each $SLM. Identical to backingRatio()
/// - kept because protocol_state.py and the technical overview
/// both call it by this name.
function backingPerToken() external view returns (uint256) {
return backingRatio();
}
// Price floor = reserves / (supply * 1.3), 18 decimals.
function priceFloor() public view returns (uint256) {
uint256 supply = TOKEN.totalSupply();
if (supply == 0) return 0;
return (totalReserves * 1e18 * 1e18) / (supply * MIN_BACKING_RATIO);
}
function netSupplyPressure() public view returns (int256) {
uint256 totalEverMinted = TOKEN.totalSupply() + totalBurned;
if (totalBurned >= totalEverMinted) return int256(totalBurned - totalEverMinted);
return -int256(totalEverMinted - totalBurned);
}
// ── Governance ──────────────────────────────────────────
function setSwapFeeBurnBPS(uint256 _bps) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_bps <= MAX_BURN_BPS, "Max 50%");
emit SwapFeeBurnUpdated(swapFeeBurnBPS, _bps);
swapFeeBurnBPS = _bps;
}
// ── Initial Funding ─────────────────────────────────────
// Capitalises the treasury WITHOUT minting any tokens.
function seedReserves(address reserveToken, uint256 amount)
external onlyRole(RESERVE_MANAGER_ROLE) nonReentrant
{
require(isReserveToken[reserveToken], "Not approved reserve");
require(amount > 0, "Nothing to seed");
IERC20(reserveToken).safeTransferFrom(msg.sender, address(this), amount);
uint256 _n3 = _normalizeDecimals(reserveToken, amount);
totalReserves += _n3;
reserveBalance[reserveToken] += _n3;
_updateExcessReserves();
_ratchet();
emit ReservesSeeded(reserveToken, amount);
}
// ── Reserve Management ──────────────────────────────────
// ── The ratchet ─────────────────────────────────────────
//
// highWaterFloor records the highest floor the protocol has ever
// reached. It only ever moves up.
//
// Without it, "the floor cannot fall" was false. excessReserves
// is defined as everything above 1.3x backing - which is exactly
// all accumulated floor growth. A single withdraw() call could
// take it and reset the floor to its opening value, erasing
// months of accretion. Markets could not do this. An admin could.
//
// With it, withdrawal is bounded by arithmetic rather than by
// policy. Reserves above the high-water mark can be deployed;
// reserves holding the floor up cannot be touched by anyone,
// including whoever holds every role.
uint256 public highWaterFloor;
/// Global invariant. Any function that can reduce reserves must
/// carry this. Guarding one function at a time is how the first
/// version left executeSwapFeeBurn able to walk straight past the
/// ratchet: it decremented totalReserves with no transfer and no
/// check, and the floor fell.
modifier floorMustHold() {
_;
require(priceFloor() >= highWaterFloor, "Floor ratchet violated");
}
/// Every path that mints, or takes reserves off the books, needs a
/// recorded floor (4 Oct 2026 review, H1). Before one exists (Keel
/// before genesis: no KEEL, a $0 floor) the ratchet guards nothing,
/// because a $0 floor always holds. Redemption needs a floor too,
/// and checks it itself.
function _floorExists() internal view {
require(highWaterFloor > 0, "No floor yet");
}
/// Called after any operation that can move the floor.
function _ratchet() internal {
uint256 f = priceFloor();
if (f > highWaterFloor) {
highWaterFloor = f;
emit FloorRatcheted(f);
}
}
/// Reserves that may leave without dropping the floor below its
/// all-time high. This is the real withdrawable figure - always
/// less than or equal to excessReserves.
function withdrawableReserves() public view returns (uint256) {
uint256 supply = TOKEN.totalSupply();
// No KEEL yet (Keel's genesis, 4 Oct 2026): every reserve dollar
// is waiting to back the supply created when trading opens, so
// none of it is withdrawable. This used to return all of it.
if (supply == 0) return 0;
// reserves needed to hold highWaterFloor
uint256 needed = (highWaterFloor * supply * MIN_BACKING_RATIO) / 1e36;
return totalReserves > needed ? totalReserves - needed : 0;
}
function withdraw(address reserveToken, uint256 amount)
external onlyRole(RESERVE_MANAGER_ROLE) nonReentrant floorMustHold
{
_floorExists();
require(isReserveToken[reserveToken], "Not a reserve token");
uint256 value = _normalizeDecimals(reserveToken, amount);
require(value <= excessReserves, "Insufficient excess reserves");
require(value <= withdrawableReserves(), "Would lower the floor");
totalReserves -= value;
reserveBalance[reserveToken] = reserveBalance[reserveToken] > value ? reserveBalance[reserveToken] - value : 0;
_updateExcessReserves();
IERC20(reserveToken).safeTransfer(msg.sender, amount);
emit Withdrawal(reserveToken, amount);
}
// ── Admin ───────────────────────────────────────────────
function setStaking(address _staking) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(address(staking) == address(0), "Already set");
staking = Staking(_staking);
}
/// One way. After this, no key can change the revenue split, the
/// founder recipient or the reserve oracle. The event records the
/// split that was frozen so the Record can show it.
function finalize() external onlyRole(DEFAULT_ADMIN_ROLE) {
require(!finalized, "Already finalized");
require(founderAllocationBPS == 0 || founderRecipient != address(0), "Founder recipient unset");
// a wired reserve oracle must be locked first, or its owner could
// still fake a depeg after finalize (3 Oct 2026 audit)
if (address(reserveOracle) != address(0)) {
(bool ok, bytes memory r) = address(reserveOracle).staticcall(abi.encodeWithSelector(IOracleLock.locked.selector));
require(ok && r.length == 32 && abi.decode(r, (bool)), "Lock the reserve oracle first");
}
finalized = true;
emit Finalized(msg.sender, agentAllocationBPS, nodeAllocationBPS,
stakerAllocationBPS, founderAllocationBPS, founderRecipient);
}
/// Wire the reserve price oracle. Optional - without it every
/// reserve is valued at par, which is the behaviour that shipped.
function setReserveOracle(address o) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
reserveOracle = IReserveOracle(o);
emit ReserveOracleSet(o);
}
/// True value of reserves at oracle prices, against what the
/// treasury has recorded. A shortfall means an approved asset has
/// lost its peg and the floor is overstated.
function reserveHealth()
external view
returns (uint256 recorded, uint256 actual, uint256 shortfallBps)
{
recorded = totalReserves;
actual = _actualReserveValue();
if (recorded == 0 || actual >= recorded) return (recorded, actual, 0);
shortfallBps = ((recorded - actual) * 10000) / recorded;
}
function _actualReserveValue() internal view returns (uint256 v) {
if (address(reserveOracle) == address(0)) return totalReserves;
for (uint256 i = 0; i < reserveTokens.length; i++) {
address t = reserveTokens[i];
if (!isReserveToken[t]) continue;
uint256 bal = reserveBalance[t];
if (bal == 0) continue;
if (!reserveOracle.healthy(t)) { v += bal; continue; }
v += (bal * reserveOracle.priceUSD(t)) / 1e18;
}
}
/// Blocks new issuance while reserves are materially impaired.
/// Minting against phantom backing is how a depeg becomes a drain.
modifier reservesSound() {
if (address(reserveOracle) != address(0)) {
uint256 actual = _actualReserveValue();
if (totalReserves > actual) {
require(
((totalReserves - actual) * 10000) / totalReserves <= MAX_SHORTFALL_BPS,
"Reserves impaired"
);
}
}
_;
}
/// Delist an asset that has provably lost its peg.
///
/// Requires the oracle to show it below DEPEG_THRESHOLD. Without
/// that proof this cannot be called at all - otherwise it would
/// be a drain vector, since a delisted token becomes rescuable.
///
/// Removing impaired backing legitimately lowers the floor, so
/// this is the one path deliberately exempt from the ratchet. The
/// high-water mark is reset to the post-removal floor: the floor
/// was never real at the old level.
/// Step one. Records that an approved reserve is trading below the
/// threshold. Changes nothing else, and anyone may call it - a
/// depeg is a public fact and there is no reason to make the
/// protocol wait for an admin to notice.
function flagDepeg(address token) external {
require(isReserveToken[token], "Not a reserve token");
require(address(reserveOracle) != address(0), "No oracle - cannot prove depeg");
require(reserveOracle.healthy(token), "Oracle unhealthy for token");
uint256 p = reserveOracle.priceUSD(token);
require(p < DEPEG_THRESHOLD, "Token is not depegged");
require(depegFlaggedAt[token] == 0, "Already flagged");
depegFlaggedAt[token] = block.timestamp;
emit DepegFlagged(token, p, block.timestamp + DELIST_DELAY);
}
/// Clears the flag once the price has recovered, so a wobble
/// cannot leave a standing licence to delist. Permissionless.
function clearDepeg(address token) external {
require(depegFlaggedAt[token] != 0, "Not flagged");
require(address(reserveOracle) != address(0), "No oracle");
require(reserveOracle.healthy(token), "Oracle unhealthy for token");
require(reserveOracle.priceUSD(token) >= DEPEG_THRESHOLD, "Still depegged");
depegFlaggedAt[token] = 0;
emit DepegCleared(token);
}
function removeReserveToken(address token) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(isReserveToken[token], "Not a reserve token");
require(address(reserveOracle) != address(0), "No oracle - cannot prove depeg");
require(depegFlaggedAt[token] != 0, "Flag the depeg first");
require(block.timestamp >= depegFlaggedAt[token] + DELIST_DELAY,
"Delist delay has not passed");
require(reserveOracle.healthy(token), "Oracle unhealthy for token");
require(reserveOracle.priceUSD(token) < DEPEG_THRESHOLD,
"Token recovered - clearDepeg and start again");
uint256 removed = reserveBalance[token];
isReserveToken[token] = false;
reserveBalance[token] = 0;
depegFlaggedAt[token] = 0;
totalReserves = totalReserves > removed ? totalReserves - removed : 0;
_updateExcessReserves();
highWaterFloor = priceFloor(); // the old mark was never backed
emit ReserveTokenRemoved(token, removed, highWaterFloor);
}
/// Where a delisted asset goes. Set once, in advance, in public.
///
/// It used to be an argument to rescueDelisted, chosen at the
/// moment of the call. Naming it beforehand does not stop a
/// determined admin - nothing in a single-key protocol does - but
/// it does mean the destination is a matter of record before
/// there is anything to take, and it can be a multisig while the
/// admin key is not one yet.
function setRecoveryAddress(address r) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(recoveryAddress == address(0), "Already set");
require(r != address(0), "Zero address");
recoveryAddress = r;
emit RecoveryAddressSet(r);
}
/// Recover a delisted asset so it can be swapped for a sound one.
/// Only reachable after removeReserveToken, which itself requires
/// a flagged depeg that has lasted a day.
///
/// What is owed to nodes, stakers, founders and the agent keeper
/// is NOT reserves and is not the admin's to move. It stays.
function rescueDelisted(address token)
external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant
{
require(!isReserveToken[token], "Still an approved reserve");
require(token != address(TOKEN), "Cannot rescue SLM");
require(recoveryAddress != address(0), "No recovery address set");
uint256 bal = IERC20(token).balanceOf(address(this));
uint256 owed = agentAllocation[token] + nodeAllocation[token]
+ stakerAllocation[token] + founderAllocation[token];
require(bal > owed, "Nothing beyond what is already owed");
uint256 amount = bal - owed;
IERC20(token).safeTransfer(recoveryAddress, amount);
emit DelistedRescued(token, recoveryAddress, amount);
}
function addReserveToken(address token) external onlyRole(DEFAULT_ADMIN_ROLE) notFinalized {
require(!isReserveToken[token], "Already added");
require(token != address(0), "Zero address");
require(token != address(TOKEN), "$SLM cannot back itself");
require(IERC20Metadata(token).decimals() <= 18, "Over 18 decimals");
// Once there is an oracle, prove the thing is a dollar before
// counting it as one. Before there is an oracle this cannot be
// checked, which is the argument for wiring the oracle at
// deploy rather than later.
if (address(reserveOracle) != address(0)) {
require(reserveOracle.healthy(token), "Oracle cannot price this token");
uint256 p = reserveOracle.priceUSD(token);
require(p >= MIN_RESERVE_PRICE && p <= MAX_RESERVE_PRICE,
"Not a dollar asset - reserves are counted at par");
}
isReserveToken[token] = true;
reserveTokens.push(token);
emit ReserveTokenAdded(token);
}
// ── Internal ────────────────────────────────────────────
function _updateExcessReserves() internal {
uint256 needed = (TOKEN.totalSupply() * MIN_BACKING_RATIO * minFloor) / 1e36;
excessReserves = totalReserves > needed ? totalReserves - needed : 0;
}
// PATCHED: scales any reserve token to 18 decimals.
function _normalizeDecimals(address token, uint256 amount)
internal view returns (uint256)
{
uint8 dec = IERC20Metadata(token).decimals();
if (dec == 18) return amount;
return amount * (10 ** (18 - dec));
}
/// Inverse of _normalizeDecimals - converts an 18-decimal
/// internal figure back into the token's own units for transfer.
function _denormalizeDecimals(address token, uint256 amount)
internal view returns (uint256)
{
uint8 dec = IERC20Metadata(token).decimals();
if (dec == 18) return amount;
return amount / (10 ** (18 - dec));
}
event MinFloorSet(uint256 minFloor);
event DepegFlagged(address indexed token, uint256 priceUSD, uint256 delistableAt);
event DepegCleared(address indexed token);
event RecoveryAddressSet(address indexed to);
event BondDeposit(address indexed reserveToken, uint256 amount, uint256 minted, uint256 profit);
event BondPremium(address indexed reserveToken, uint256 backing, uint256 premium);
event ReservesSeeded(address indexed token, uint256 amount);
event Withdrawal(address indexed token, uint256 amount);
event ReserveTokenAdded(address indexed token);
event TokensBurned(uint256 amount, string reason);
event SwapFeeBurnUpdated(uint256 oldBPS, uint256 newBPS);
event FeesCollected(address indexed token, uint256 total, uint256 toReserves, uint256 toAgents, uint256 toNodes);
event AgentAllocationWithdrawn(address indexed token, address indexed to, uint256 amount);
event AgentAllocationSet(uint256 oldBPS, uint256 newBPS);
event NodeAllocationSet(uint256 oldBPS, uint256 newBPS);
event NodeDistributorSet(address indexed distributor);
event NodeAllocationClaimed(address indexed token, uint256 amount);
event StakerAllocationSet(uint256 oldBPS, uint256 newBPS);
event StakerDistributorSet(address indexed distributor);
event StakerAllocationClaimed(address indexed token, uint256 amount);
event FounderAllocationSet(uint256 oldBPS, uint256 newBPS);
event FounderRecipientSet(address indexed from, address indexed to);
event FounderAllocationClaimed(address indexed token, address indexed to, uint256 amount);
event ReserveOracleSet(address indexed oracle);
event AgentWithdrawerSet(address indexed withdrawer);
event Finalized(address indexed by, uint256 agentBPS, uint256 nodeBPS, uint256 stakerBPS, uint256 founderBPS, address founderRecipient);
event ReserveTokenRemoved(address indexed token, uint256 removedValue, uint256 newHighWater);
event DelistedRescued(address indexed token, address indexed to, uint256 amount);
event Redeemed(address indexed holder, address indexed token, uint256 slmBurned, uint256 payout, uint256 fee, uint256 newFloor);
event RedemptionFeeSet(uint256 oldBPS, uint256 newBPS);
event FloorRatcheted(uint256 newHighWaterFloor);
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.