Verified contractExactMIT
KeelHookOracle
Address0x31476dc33fc643d97a3596b230a78d0d38e16602
- 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,658
- Creation transaction
- 0x24fb415584…cb50e4d9f1
23 files
- contracts/KeelHookOracle.solmain6.07 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
- @openzeppelin/contracts/utils/math/Math.sol15.12 KB
- contracts/IBondOracle.sol2 KB
- contracts/IReserveOracle.sol1.3 KB
- contracts/KeelHook.sol26.12 KB
- contracts/OlympusToken.sol1.26 KB
- contracts/StakedToken.sol7 KB
- contracts/Staking.sol15.56 KB
- contracts/Treasury.sol52.92 KB
contracts/KeelHookOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// ============================================================
// KeelHookOracle.sol
//
// Wraps KeelHook's TWAP into the IBondOracle interface so the
// escrow, the loans and anything else that prices $KEEL read from
// the same time-weighted source the hook records on every swap.
//
// The spot-only UniV4SpotOracle is not needed on Keel: the hook is
// the oracle.
// ============================================================
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./IBondOracle.sol";
import "./KeelHook.sol";
contract KeelHookOracle is IBondOracle {
KeelHook public immutable HOOK;
bool public immutable KEEL_IS_0;
uint8 public immutable KEEL_DEC;
uint8 public immutable QUOTE_DEC;
uint32 public immutable WINDOW;
constructor(address _hook, bool _keelIs0, uint8 _keelDec, uint8 _quoteDec, uint32 _window) {
require(_hook != address(0), "Zero address");
require(_window >= 30 minutes, "Window too short");
HOOK = KeelHook(_hook);
KEEL_IS_0 = _keelIs0;
KEEL_DEC = _keelDec;
QUOTE_DEC = _quoteDec;
WINDOW = _window;
}
/// Price of one $KEEL in quote, 18 decimals.
///
/// The hook stores ticks. A tick is log_1.0001 of the raw price
/// (currency1 raw per currency0 raw). Convert to a human price by
/// inverting if KEEL is currency1 and correcting for decimals.
function consult() external view override returns (uint256) {
return _priceFromTick(HOOK.consultTick(WINDOW));
}
/// Tick -> price of one KEEL in quote, 18 decimals.
///
/// sqrtP can reach 2^116 at the ticks a mixed-decimals pool sits
/// at, so squaring it needs 512-bit intermediate math. Math.mulDiv
/// does that; the naive product overflowed in testing.
function _priceFromTick(int24 tick) internal view returns (uint256) {
uint160 sqrtP = _sqrtPriceAtTick(tick);
// raw = sqrtP^2 / 2^192, carried at 1e18 precision
uint256 raw = Math.mulDiv(Math.mulDiv(sqrtP, sqrtP, 1 << 96), 1e18, 1 << 96);
if (KEEL_IS_0) {
// raw is quote-raw per KEEL-raw; rescale by decimals
return Math.mulDiv(raw, 10 ** KEEL_DEC, 10 ** QUOTE_DEC);
}
// raw is KEEL-raw per quote-raw; invert, then rescale
if (raw == 0) return 0;
return Math.mulDiv(1e36 / raw, 10 ** KEEL_DEC, 10 ** QUOTE_DEC);
}
function ready() external view override returns (bool) {
return HOOK.ready(WINDOW);
}
function window() external view override returns (uint32) {
return WINDOW;
}
/// How far the latest tick sits from the window's average, in
/// basis points of the average. This is what the depository and
/// the escrow compare against their maxDeviationBPS: a spot pushed
/// away from the 30-minute average in one block is refused until
/// it comes back. Zero before the hook has history (ready() is
/// checked first by every consumer) and zero when the average
/// reads zero.
function deviationBps() external view override returns (uint256) {
if (!HOOK.ready(WINDOW)) return 0;
uint256 twap = _priceFromTick(HOOK.consultTick(WINDOW));
if (twap == 0) return 0;
uint256 sp = _priceFromTick(HOOK.lastTick());
uint256 d = sp > twap ? sp - twap : twap - sp;
return (d * 10000) / twap;
}
/// The hook records the tick after every swap, so "spot" is the
/// latest observation rather than a separate read.
function spot() external view override returns (uint256) {
return _priceFromTick(HOOK.lastTick());
}
// ── V3 TickMath.getSqrtRatioAtTick, vendored ─────────────
function _sqrtPriceAtTick(int24 tick) internal pure returns (uint160) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= 887272, "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
return uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
@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);
}
@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
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/KeelHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// ============================================================
// KeelHook.sol
//
// A Uniswap V4 hook that does three things the token itself never
// has to:
//
// 1. ASYMMETRIC FEES. Buys pay the pool's LP fee only. Sells pay an
// extra slice on top, taken by the hook. The token is a plain
// ERC-20 with no transfer logic - every wallet, aggregator and
// bridge treats it as ordinary, because it is.
//
// 2. FEE ROUTING. The sell slice goes straight to Treasury.collectFees,
// where it splits like every other dollar of revenue and the
// remainder becomes reserves. Leaving raises the floor for whoever
// stays, on the DEX exactly as it does on redemption.
//
// 3. A TWAP. afterSwap records a price observation. The oracle reads
// a time-weighted average from these rather than a single spot
// value, which closes the manipulation window the spot-only V4
// oracle had to leave open.
//
// WHAT IT CANNOT DO
// Touch reserves. Pause the pool. Change the fee above the cap. Take
// anything from a buy. The hook's only power is to skim a bounded
// slice from sells and forward it.
//
// DEPLOYMENT
// V4 encodes hook permissions in the address. This contract needs
// the BEFORE_INITIALIZE, AFTER_SWAP and AFTER_SWAP_RETURNS_DELTA bits
// set (low 14 bits 0x2044), which means mining a CREATE2 salt until
// the address has them. The deploy script does this; see
// scripts/mine-hook-salt.js.
//
// VERIFY BEFORE MAINNET
// The IPoolManager and BalanceDelta interfaces below match v4-core
// at the commit noted. Confirm against the PoolManager actually
// deployed on Robinhood Chain before pointing real liquidity at it.
// ============================================================
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Treasury.sol";
// ── Minimal V4 surface ──────────────────────────────────────
// Only what this hook uses. Pinned to v4-core interfaces; the full
// dependency is heavy and most of it is irrelevant here.
type Currency is address;
type BalanceDelta is int256;
type BeforeSwapDelta is int256;
type PoolId is bytes32;
struct PoolKey {
Currency currency0;
Currency currency1;
uint24 fee;
int24 tickSpacing;
address hooks;
}
struct SwapParams {
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
}
interface IPoolManager {
function take(Currency currency, address to, uint256 amount) external;
function extsload(bytes32 slot) external view returns (bytes32);
}
interface IQuotronBridge {
function notifyReceived(uint256 amount) external;
}
library BalanceDeltaLib {
function amount0(BalanceDelta d) internal pure returns (int128) {
return int128(BalanceDelta.unwrap(d) >> 128);
}
function amount1(BalanceDelta d) internal pure returns (int128) {
return int128(BalanceDelta.unwrap(d));
}
}
contract KeelHook is Ownable {
using SafeERC20 for IERC20;
using BalanceDeltaLib for BalanceDelta;
IPoolManager public immutable POOL_MANAGER;
Treasury public immutable TREASURY;
address public immutable KEEL;
address public immutable RESERVE;
/// Extra fee on sells, in basis points of the stablecoin received.
/// Taken by the hook from the swap output and forwarded to the
/// Treasury. Buys pay nothing here.
uint256 public sellFeeBPS = 300; // 3%
uint256 public constant MAX_SELL_FEE_BPS = 500; // 5%
/// A further slice of sells to the Quotrons ecosystem, via the
/// bridge. Off by default; on once the bridge is deployed. Capped
/// well below the treasury slice - this is a contribution, not a
/// competing claim on the floor.
address public quotronBridge;
uint256 public quotronFeeBPS = 0;
uint256 public constant MAX_QUOTRON_FEE_BPS = 100; // 1%
uint256 public totalToQuotrons;
// ── TWAP ────────────────────────────────────────────────
//
// A ring of (timestamp, tickCumulative) observations, the same
// shape V3 uses. consult(window) integrates over it.
struct Observation { uint32 blockTimestamp; int56 tickCumulative; bool initialized; }
Observation[1024] public observations;
uint16 public observationIndex;
uint16 public observationCardinality = 128;
// The ring keeps one observation per OBSERVATION_GAP seconds at most
// (3 Oct 2026 audit). It used to take one per swap-second, so 129
// swaps inside half an hour, from busy trading or dust swaps every
// 14 seconds, lapped the 30-minute window: the oracle went not-ready
// and bonds closed exactly when the market ran. The running total
// (accCum at accTs) is kept exact on every swap; the ring stores
// snapshots of it, so 128 slots always span at least 2,032 seconds.
uint32 public constant OBSERVATION_GAP = 16;
int56 public accCum;
uint32 public accTs;
int24 public lastTick;
bool public started; // true from the first real swap
uint24 public poolFee; // the one pool, by tier (setPool)
int24 public poolTickSpacing;
bool public poolSet;
uint256 public totalFeesForwarded;
uint256 public sellCount;
// ── The launch, in two phases (2 Oct 2026) ──────────────
//
// Phase one, from `launchStart` for `siteOnlySeconds`: the hook
// accepts a swap only when the PoolManager's caller is Keel's own
// router, so the site is the only door; the router adds the
// fleet-first window and the per-wallet cap. Phase two, from
// `openAt()`: any sender, and a launch fee on top of the standing
// one that opens at `launchStartBPS`, falls in a straight line to
// `launchKneeBPS` at `launchKneeSeconds`, then in a straight line
// to nothing at `launchEndSeconds`. On a sell the fee is the
// reserve asset and goes through Treasury.collectFees like every
// fee dollar; on a buy it is KEEL and is burned through
// Treasury.burnSupply, so a sniper's first-minute buy hands most
// of it to every holder. Set once, before the pool opens; the
// curve can never be raised afterwards. Phase 0 is "no launch set":
// nothing gated, nothing extra taken, which is what every test
// and the fork proof run under.
address public router;
uint64 public launchStart;
uint32 public siteOnlySeconds;
uint16 public launchStartBPS;
uint16 public launchKneeBPS;
uint32 public launchKneeSeconds;
uint32 public launchEndSeconds;
bool public launchSet;
uint256 public constant MAX_LAUNCH_FEE_BPS = 9000; // 90%
uint256 public totalLaunchFees; // reserve asset, through the split
uint256 public totalLaunchBurned; // KEEL burned on launch-day buys
// ── The creator fee ─────────────────────────────────────
//
// A share of every SELL to the founder split, on top of the
// standing fee: 1% at most, only ever lowerable, decaying in a
// straight line to nothing over `creatorSunsetSeconds` from the
// moment the pool opens (or from when it was set, if no launch is
// scheduled). Disclosed on the Verify page and the Record. Never
// scales with the launch curve.
uint16 public creatorFeeBPS;
address public creatorRecipient;
uint32 public creatorSunsetSeconds;
uint64 public creatorFrom;
uint256 public constant MAX_CREATOR_FEE_BPS = 100; // 1%
uint256 public totalToCreator;
/// `_owner` is explicit because this contract is deployed through a
/// CREATE2 factory to land at a salt-mined address. Inside the
/// constructor msg.sender is the FACTORY, and Ownable(msg.sender)
/// made the factory the owner - a contract with no admin path, so
/// setSellFeeBPS and setQuotronBridge were unreachable forever, and
/// the very first call to either in deploy.js reverted with
/// OwnableUnauthorizedAccount. Keel's fork test never noticed
/// because it never set the fee; Solum's did.
constructor(address _pm, address _treasury, address _keel, address _reserve, address _owner)
Ownable(_owner)
{
require(_pm != address(0) && _treasury != address(0)
&& _keel != address(0) && _reserve != address(0), "Zero address");
POOL_MANAGER = IPoolManager(_pm);
TREASURY = Treasury(_treasury);
KEEL = _keel;
RESERVE = _reserve;
// the observation ring starts at the FIRST REAL SWAP (_observe),
// not here: a genesis entry at tick 0 blended into the first
// half hour of trading as a price of one raw unit per raw unit
}
// ── Permissions ─────────────────────────────────────────
//
// V4 reads these bits from the hook ADDRESS, not from this
// function; the function exists so the deploy script can assert
// the mined address matches.
/// Returns (beforeInitialize, afterSwap, afterSwapReturnDelta).
/// Every other V4 permission is false. The deploy script asserts
/// the mined address encodes exactly these three bits: low 14 bits
/// 0x2044 (1<<13 | 1<<6 | 1<<2).
function getHookPermissions() external pure returns (bool, bool, bool) {
return (true, true, true);
}
// ── Who opens the pool (4 Oct 2026) ─────────────────────
/// Called by the PoolManager before any pool naming this hook is
/// initialised. Only the owner may initialise one. Without this,
/// anyone could initialise the empty KEEL pool at a price of their
/// choosing before seed-pool.js runs, and seed-pool.js would then
/// refuse to seed (the pool is not where the launch opens it): the
/// launch frozen by one transaction. With it, the price is set by
/// the same key, in the same run, that sets the launch and seeds.
/// Solum initialises at deploy, as the owner, so it is unaffected.
function beforeInitialize(address sender, PoolKey calldata key, uint160) external view returns (bytes4) {
require(msg.sender == address(POOL_MANAGER), "Only PoolManager");
require(key.hooks == address(this), "Not this hook");
require(sender == owner(), "Only the owner opens the pool");
return this.beforeInitialize.selector;
}
// ── The hook ────────────────────────────────────────────
/// Called by the PoolManager after every swap in this pool.
///
/// Determines direction. If KEEL went in and stablecoin came out,
/// it is a sell: take sellFeeBPS of the stablecoin output, forward
/// it to the Treasury, and return a delta telling the PoolManager
/// the swapper receives that much less.
///
/// Records a price observation either way.
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata
) external returns (bytes4, int128) {
require(msg.sender == address(POOL_MANAGER), "Only PoolManager");
// Only the KEEL pool may write this hook's state. Anyone can
// initialise a pool of any two tokens naming this hook; without
// this check a swap in such a pool would write its tick into the
// TWAP ring (2 Oct review, H1).
require(key.hooks == address(this), "Not this hook");
{
address c0 = Currency.unwrap(key.currency0); address c1 = Currency.unwrap(key.currency1);
require((c0 == KEEL && c1 == RESERVE) || (c0 == RESERVE && c1 == KEEL), "Not the KEEL pool");
if (poolSet) require(key.fee == poolFee && key.tickSpacing == poolTickSpacing, "Not the KEEL pool");
}
// phase one: the site is the only door
if (phase() == 1) require(sender == router && router != address(0), "Phase one: through the site only");
_observe(key);
// A sell is KEEL in, reserve out. zeroForOne means currency0 in.
bool isSell = (Currency.unwrap(key.currency0) == KEEL) ? params.zeroForOne : !params.zeroForOne;
(Currency unspec, uint256 gross) = _unspecified(key, params, delta);
if (gross == 0) return (this.afterSwap.selector, 0);
uint256 total = _charge(unspec, isSell, gross);
return (this.afterSwap.selector, int128(uint128(total)));
}
/// The hook may only adjust the UNSPECIFIED currency: the output of
/// an exact-input swap, the input of an exact-output one. The fee
/// is taken there, in whichever asset that is. The router always
/// swaps exact input, so a sell pays in dollars and a buy pays in
/// KEEL; a direct exact-output swap pays in the other asset, the
/// same value either way.
function _unspecified(PoolKey calldata key, SwapParams calldata params, BalanceDelta delta)
internal pure returns (Currency unspec, uint256 gross)
{
bool unspecIs0 = (params.amountSpecified < 0) ? !params.zeroForOne : params.zeroForOne;
int128 amt = unspecIs0 ? delta.amount0() : delta.amount1();
gross = amt < 0 ? uint256(uint128(-amt)) : uint256(uint128(amt));
unspec = unspecIs0 ? key.currency0 : key.currency1;
}
/// fee, launch fee, creator fee, Quotron fee, on `gross`.
function _fees(bool isSell, uint256 gross) internal view returns (uint256[4] memory f) {
f[0] = isSell ? (gross * sellFeeBPS) / 10000 : 0;
f[1] = (gross * launchFeeBPS()) / 10000;
f[2] = isSell ? (gross * creatorFeeNowBPS()) / 10000 : 0;
f[3] = (isSell && quotronBridge != address(0)) ? (gross * quotronFeeBPS) / 10000 : 0;
}
/// Take the fees out of the PoolManager and send each where it
/// goes. Paid in the reserve asset: the standing and launch fees
/// through the Treasury's split, the creator's slice to the founder
/// split, the Quotron slice to the bridge. Paid in KEEL: everything
/// burns, and the floor rises for every holder.
function _charge(Currency unspec, bool isSell, uint256 gross) internal returns (uint256 total) {
uint256[4] memory f = _fees(isSell, gross);
total = f[0] + f[1] + f[2] + f[3];
if (total == 0) return 0;
require(total < gross, "Fee exceeds the swap");
POOL_MANAGER.take(unspec, address(this), total);
if (Currency.unwrap(unspec) == KEEL) {
IERC20(KEEL).forceApprove(address(TREASURY), total);
TREASURY.burnSupply(total);
totalLaunchBurned += total;
emit LaunchFeeTaken(isSell, total, true);
} else {
if (f[0] + f[1] > 0) {
IERC20(RESERVE).forceApprove(address(TREASURY), f[0] + f[1]);
TREASURY.collectFees(RESERVE, f[0] + f[1]);
totalFeesForwarded += f[0];
totalLaunchFees += f[1];
if (f[1] > 0) emit LaunchFeeTaken(isSell, f[1], false);
}
if (f[2] > 0) {
IERC20(RESERVE).safeTransfer(creatorRecipient, f[2]);
totalToCreator += f[2];
emit CreatorFeeTaken(f[2]);
}
if (f[3] > 0) {
IERC20(RESERVE).safeTransfer(quotronBridge, f[3]);
IQuotronBridge(quotronBridge).notifyReceived(f[3]);
totalToQuotrons += f[3];
emit QuotronContribution(f[3]);
}
}
if (isSell) { sellCount++; emit SellFeeTaken(f[0], TREASURY.priceFloor()); }
}
// ── The launch schedule ─────────────────────────────────
/// 0: no launch set, or not started. 1: site only. 2: open.
/// Once the launch is set, the minutes before launchStart are phase
/// one too (3 Oct 2026 audit): seed-pool.js sets the start a few
/// minutes ahead and then seeds, and phase 0 there let any sender
/// buy the whole pool straight from the PoolManager. The router
/// keeps its own fleet window and cap for that stretch.
function phase() public view returns (uint8) {
if (!launchSet) return 0;
if (block.timestamp < uint256(launchStart) + siteOnlySeconds) return 1;
return 2;
}
function openAt() public view returns (uint256) { return launchSet ? uint256(launchStart) + siteOnlySeconds : 0; }
/// The launch fee right now, in basis points: the curve from the
/// moment the pool opens to everyone.
function launchFeeBPS() public view returns (uint256) {
if (phase() != 2) return 0;
uint256 t = block.timestamp - openAt();
if (t >= launchEndSeconds) return 0;
if (t < launchKneeSeconds) {
return launchStartBPS - ((uint256(launchStartBPS) - launchKneeBPS) * t) / launchKneeSeconds;
}
return launchKneeBPS - (uint256(launchKneeBPS) * (t - launchKneeSeconds)) / (launchEndSeconds - launchKneeSeconds);
}
/// The creator fee right now, in basis points, after its sunset.
function creatorFeeNowBPS() public view returns (uint256) {
if (creatorFeeBPS == 0 || creatorRecipient == address(0)) return 0;
uint256 from = creatorFrom;
if (launchSet) from = openAt();
if (block.timestamp <= from) return creatorFeeBPS;
uint256 t = block.timestamp - from;
if (creatorSunsetSeconds == 0 || t >= creatorSunsetSeconds) return creatorSunsetSeconds == 0 ? creatorFeeBPS : 0;
return creatorFeeBPS - (uint256(creatorFeeBPS) * t) / creatorSunsetSeconds;
}
/// The site's router, set once. Phase one admits nothing else.
function setRouter(address r) external onlyOwner {
require(router == address(0), "Already set");
require(r != address(0), "Zero address");
router = r;
emit RouterSet(r);
}
/// The whole schedule, set once, before the pool opens. Nothing
/// here can be raised, extended or moved afterwards.
function setLaunch(uint64 start, uint32 siteOnly, uint16 startBPS, uint16 kneeBPS, uint32 kneeSeconds, uint32 endSeconds)
external onlyOwner
{
require(!launchSet, "Launch already set");
require(start >= block.timestamp, "Start is in the past");
require(startBPS <= MAX_LAUNCH_FEE_BPS, "Above the 90% cap");
require(kneeBPS <= startBPS, "Knee above the start");
require(kneeSeconds < endSeconds, "Knee after the end");
// bounds (3 Oct 2026 audit): the gate and the fee curve cannot be
// set to freeze the pool for years
require(start <= block.timestamp + 1 days, "Start more than a day out");
require(siteOnly <= 7 days && endSeconds <= 7 days, "Schedule longer than a week");
launchStart = start; siteOnlySeconds = siteOnly;
launchStartBPS = startBPS; launchKneeBPS = kneeBPS; launchKneeSeconds = kneeSeconds; launchEndSeconds = endSeconds;
launchSet = true;
emit LaunchSet(start, uint256(start) + siteOnly, startBPS, kneeBPS, kneeSeconds, endSeconds);
}
/// The creator fee: at most 1%, and once set it can only go down.
/// The recipient and the sunset are fixed with the first set.
function setCreatorFee(uint16 bps, address recipient, uint32 sunsetSeconds) external onlyOwner {
require(bps <= MAX_CREATOR_FEE_BPS, "Above the 1% cap");
if (creatorRecipient != address(0)) {
require(bps <= creatorFeeBPS, "Can only be lowered");
require(recipient == creatorRecipient && sunsetSeconds == creatorSunsetSeconds, "Recipient and sunset are fixed");
} else {
require(recipient != address(0), "Zero recipient");
creatorRecipient = recipient;
creatorSunsetSeconds = sunsetSeconds;
creatorFrom = uint64(block.timestamp);
}
emit CreatorFeeSet(creatorFeeBPS, bps, recipient, sunsetSeconds);
creatorFeeBPS = bps;
}
// ── Observations ────────────────────────────────────────
function _observe(PoolKey calldata key) internal {
int24 tick = _currentTick(key);
uint32 nowTs = uint32(block.timestamp);
if (!started) {
observations[0] = Observation(nowTs, 0, true);
observationIndex = 0;
accCum = 0; accTs = nowTs;
lastTick = tick;
started = true;
return;
}
// the running total, exact: the tick that held since the last
// swap, for as long as it held
if (nowTs > accTs) {
accCum += int56(lastTick) * int56(uint56(nowTs - accTs));
accTs = nowTs;
}
lastTick = tick;
// a snapshot into the ring, at most one per OBSERVATION_GAP
Observation storage last = observations[observationIndex];
if (nowTs - last.blockTimestamp < OBSERVATION_GAP) return;
uint16 next = (observationIndex + 1) % observationCardinality;
observations[next] = Observation(nowTs, accCum, true);
observationIndex = next;
}
/// Reads slot0 of the pool via extsload. The slot layout is
/// v4-core's; confirm against the deployed PoolManager.
function _currentTick(PoolKey calldata key) internal view returns (int24) {
bytes32 poolId = keccak256(abi.encode(key));
bytes32 slot = keccak256(abi.encode(poolId, uint256(6))); // _pools mapping slot
bytes32 packed = POOL_MANAGER.extsload(slot);
// slot0: sqrtPriceX96 (160) | tick (24) | protocolFee (24) | lpFee (24)
return int24(int256(uint256(packed) >> 160));
}
/// Time-weighted average tick over `window` seconds.
function consultTick(uint32 window) public view returns (int24) {
require(window > 0, "Zero window");
Observation storage newest = observations[observationIndex];
require(newest.initialized, "No observations");
uint32 target = uint32(block.timestamp) - window;
// Walk back to the first observation at or before target.
uint16 i = observationIndex;
Observation storage older = newest;
for (uint16 n = 0; n < observationCardinality; n++) {
i = i == 0 ? observationCardinality - 1 : i - 1;
Observation storage o = observations[i];
if (!o.initialized) break;
older = o;
if (o.blockTimestamp <= target) break;
}
require(older.blockTimestamp < newest.blockTimestamp, "Insufficient history");
// the ring must reach back to the target; a short ring would
// otherwise return a shorter average and call it the window
require(older.blockTimestamp <= target, "Window not covered");
// now, from the exact running total rather than the newest snapshot
int56 newestCum = accCum + int56(lastTick) * int56(uint56(uint32(block.timestamp) - accTs));
uint32 span = uint32(block.timestamp) - older.blockTimestamp;
return int24((newestCum - older.tickCumulative) / int56(uint56(span)));
}
/// True once there is enough history to serve `window`.
function ready(uint32 window) external view returns (bool) {
if (!started) return false;
Observation storage newest = observations[observationIndex];
if (!newest.initialized) return false;
uint16 i = observationIndex;
for (uint16 n = 0; n < observationCardinality; n++) {
i = i == 0 ? observationCardinality - 1 : i - 1;
Observation storage o = observations[i];
if (!o.initialized) return false;
if (uint32(block.timestamp) - o.blockTimestamp >= window) return true;
}
return false;
}
// ── Admin ───────────────────────────────────────────────
/// The one pool this hook serves, by fee tier: set once at deploy,
/// so a second KEEL/USDG pool at another tier naming this hook
/// cannot write the ring either.
function setPool(uint24 fee, int24 tickSpacing) external onlyOwner {
require(!poolSet, "Pool already set");
poolFee = fee; poolTickSpacing = tickSpacing; poolSet = true;
emit PoolSet(fee, tickSpacing);
}
function setQuotronBridge(address b, uint256 bps) external onlyOwner {
require(bps <= MAX_QUOTRON_FEE_BPS, "Above cap");
quotronBridge = b;
quotronFeeBPS = b == address(0) ? 0 : bps;
emit QuotronBridgeSet(b, quotronFeeBPS);
}
function setSellFeeBPS(uint256 bps) external onlyOwner {
require(bps <= MAX_SELL_FEE_BPS, "Above cap");
emit SellFeeSet(sellFeeBPS, bps);
sellFeeBPS = bps;
}
event SellFeeTaken(uint256 amount, uint256 newFloor);
event QuotronContribution(uint256 amount);
event QuotronBridgeSet(address indexed bridge, uint256 bps);
event SellFeeSet(uint256 from, uint256 to);
event RouterSet(address indexed router);
event PoolSet(uint24 fee, int24 tickSpacing);
event LaunchSet(uint64 start, uint256 openAt, uint16 startBPS, uint16 kneeBPS, uint32 kneeSeconds, uint32 endSeconds);
event LaunchFeeTaken(bool sell, uint256 amount, bool burned);
event CreatorFeeSet(uint16 from, uint16 to, address indexed recipient, uint32 sunsetSeconds);
event CreatorFeeTaken(uint256 amount);
}
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.