Skip to content
Verified contractExactMIT

OhmDotFun

Address0xeb8d929b86de0b96cfd972ef3dba805423abf6cd
Balance

0 ETH

 

Transactions

216

 

Compiler

solc 0.8.34

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,935,172
Creation transaction
0x0a3922a661…25e3bbf99e

ohmfun/OhmDotFun.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {QuoteConsensus} from "./QuoteConsensus.sol";
import {BasketWeights} from "./BasketWeights.sol";
import {RedemptionQueue} from "./RedemptionQueue.sol";
import {AttestationRounds} from "./AttestationRounds.sol";
import {DeviationBand} from "./DeviationBand.sol";

//      /\    /\    /\
//     /  \  /  \  /  \        ohm.fun
//    /    \/    \/    \       stock-backed rebase, ethereum mainnet
//
//         https://ohm.fun

/// @dev QuoteConsensus, BasketWeights, RedemptionQueue, AttestationRounds,
///      and DeviationBand are imported above so this file compiles as
///      one dependency graph with the rest of the ohm.fun contracts,
///      but none of their functions are ever called from here. They
///      are separate, independently deployed contracts with no path
///      back into this token's balances, `_update`, or total supply.
///      Importing them creates no inheritance, no shared storage
///      layout, and no naming collision with anything below.
///
/// @title ohm.fun OHM
/// @notice Flat, non-rebasing, standard ERC-20. The entire 1,000,000
///         supply mints once, to the deployer, in the constructor.
///         There is no mint function anywhere in this contract, no
///         owner, and no admin role, so supply can never change again
///         after deployment under any circumstance.
contract OhmDotFun is ERC20 {
    /// @notice Total supply, fixed forever at deployment.
    uint256 public constant INITIAL_SUPPLY = 1_000_000;

    /// @notice Block timestamp this contract was deployed.
    uint256 public immutable hatchedAt;

    error EmptyLabel();
    error EmptyNote();
    error ZeroValue();
    error OutOfRange();

    constructor() ERC20("ohm.fun", "OHM") {
        hatchedAt = block.timestamp;
        _mint(msg.sender, INITIAL_SUPPLY * 10 ** decimals());
    }

    // -----------------------------------------------------------------
    // Reference-instrument registry. A public log of which tokenized
    // equities the reserve basket described on ohm.fun references.
    // Purely a record-keeping ledger: writing to it does not gate
    // mint/burn, does not affect balances, and is not read by any
    // function above this line.
    // -----------------------------------------------------------------

    struct ReferenceInstrument {
        address instrument;
        string label;
        address submittedBy;
        uint64 submittedAt;
    }

    ReferenceInstrument[] private _referenceInstruments;

    event ReferenceInstrumentRegistered(address indexed instrument, string label, address indexed submittedBy, uint256 index);

    /// @notice Logs `instrument` (e.g. a tokenized-equity token
    ///         address) with a human-readable `label`. Callable by
    ///         anyone; this is a public annotation ledger, not an
    ///         allowlist or oracle feed, and nothing else in this
    ///         contract reads from it.
    function registerReferenceInstrument(address instrument, string calldata label) external returns (uint256 index) {
        if (bytes(label).length == 0) revert EmptyLabel();
        index = _referenceInstruments.length;
        _referenceInstruments.push(
            ReferenceInstrument({instrument: instrument, label: label, submittedBy: msg.sender, submittedAt: uint64(block.timestamp)})
        );
        emit ReferenceInstrumentRegistered(instrument, label, msg.sender, index);
    }

    function referenceInstrumentCount() external view returns (uint256) {
        return _referenceInstruments.length;
    }

    function referenceInstrumentAt(uint256 index) external view returns (ReferenceInstrument memory) {
        if (index >= _referenceInstruments.length) revert OutOfRange();
        return _referenceInstruments[index];
    }

    // -----------------------------------------------------------------
    // Reserve snapshot attestations. A self-reported log of
    // approximate reserve values over time. Not verified, not
    // enforced, and not consulted by mint/burn; a public paper trail
    // only.
    // -----------------------------------------------------------------

    struct ReserveSnapshot {
        uint256 approxValueUsd;
        address submittedBy;
        uint64 submittedAt;
    }

    ReserveSnapshot[] private _reserveSnapshots;

    event ReserveSnapshotAttested(uint256 approxValueUsd, address indexed submittedBy, uint256 index);

    /// @notice Logs a self-reported approximate reserve value, in
    ///         whole USD. Anyone can call this; it has no effect on
    ///         supply, balances, or any other function in this
    ///         contract.
    function attestReserveSnapshot(uint256 approxValueUsd) external returns (uint256 index) {
        if (approxValueUsd == 0) revert ZeroValue();
        index = _reserveSnapshots.length;
        _reserveSnapshots.push(ReserveSnapshot({approxValueUsd: approxValueUsd, submittedBy: msg.sender, submittedAt: uint64(block.timestamp)}));
        emit ReserveSnapshotAttested(approxValueUsd, msg.sender, index);
    }

    function reserveSnapshotCount() external view returns (uint256) {
        return _reserveSnapshots.length;
    }

    function reserveSnapshotAt(uint256 index) external view returns (ReserveSnapshot memory) {
        if (index >= _reserveSnapshots.length) revert OutOfRange();
        return _reserveSnapshots[index];
    }

    function latestReserveSnapshot() external view returns (ReserveSnapshot memory) {
        if (_reserveSnapshots.length == 0) revert OutOfRange();
        return _reserveSnapshots[_reserveSnapshots.length - 1];
    }

    // -----------------------------------------------------------------
    // Revision notes. An append-only public changelog. Anyone can add
    // a note; nothing reads it back except the view functions below.
    // -----------------------------------------------------------------

    struct RevisionNote {
        string note;
        address writtenBy;
        uint64 writtenAt;
    }

    RevisionNote[] private _revisionNotes;

    event RevisionNoteLogged(uint256 indexed index, address indexed writtenBy);

    function logRevisionNote(string calldata note) external returns (uint256 index) {
        if (bytes(note).length == 0) revert EmptyNote();
        index = _revisionNotes.length;
        _revisionNotes.push(RevisionNote({note: note, writtenBy: msg.sender, writtenAt: uint64(block.timestamp)}));
        emit RevisionNoteLogged(index, msg.sender);
    }

    function revisionNoteCount() external view returns (uint256) {
        return _revisionNotes.length;
    }

    function revisionNoteAt(uint256 index) external view returns (RevisionNote memory) {
        if (index >= _revisionNotes.length) revert OutOfRange();
        return _revisionNotes[index];
    }

    // -----------------------------------------------------------------
    // Read-only sugar. None of these participate in transfer/balance
    // accounting; they are convenience views only.
    // -----------------------------------------------------------------

    /// @notice Seconds elapsed since this contract was deployed.
    function secondsSinceHatch() public view returns (uint256) {
        return block.timestamp - hatchedAt;
    }

    /// @notice Total supply expressed in whole tokens (no decimals).
    function pondDepth() public view returns (uint256) {
        return totalSupply() / 10 ** decimals();
    }

    /// @notice `account`'s share of total supply in basis points.
    function shareBps(address account) public view returns (uint256) {
        uint256 supply = totalSupply();
        if (supply == 0) return 0;
        return (balanceOf(account) * 10_000) / supply;
    }
}

@openzeppelin/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)

pragma solidity >=0.8.4;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 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 ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
     * 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 ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 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.5.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 ERC-20
 * applications.
 */
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}.
     *
     * Both 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;
    }

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /// @inheritdoc IERC20
    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;
    }

    /// @inheritdoc IERC20
    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}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * 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 sets 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:
     *
     * ```solidity
     * 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.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/contracts/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;
    }
}

ohmfun/AttestationRounds.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

//      /\    /\    /\
//     /  \  /  \  /  \        ohm.fun
//    /    \/    \/    \       stock-backed rebase, ethereum mainnet
//
//         https://ohm.fun

/// @notice Standalone M-of-N attestation tracker. A fixed attestor set
///         is registered once at deployment; anyone in that set can
///         sign off on the current round, and a round is considered
///         confirmed once enough distinct attestors have signed it.
///         No connection to any token's balance or transfer logic.
/// @dev Every public write function here is no-revert. A non-attestor
///      calling `attest`, an attestor signing twice in the same
///      round, or `advanceRound` being called before the current
///      round is confirmed all silently no-op (with a `NoOp` event)
///      instead of reverting.
contract AttestationRounds {
    /// @notice The fixed attestor set, permanent for the life of this
    ///         contract. There is no function anywhere that adds,
    ///         removes, or replaces an attestor after deployment.
    address[] public attestors;
    mapping(address => bool) public isAttestor;

    /// @notice Attestations required for a round to count as
    ///         confirmed, fixed at deployment. Clamped to the
    ///         attestor count if a larger value is supplied, and to 1
    ///         if zero is supplied, so construction itself never
    ///         reverts either.
    uint256 public immutable threshold;

    uint256 public currentRound;
    /// @dev round => attestor => has signed.
    mapping(uint256 => mapping(address => bool)) public hasAttested;
    /// @dev round => count of distinct attestors who have signed.
    mapping(uint256 => uint256) public attestationCount;
    mapping(uint256 => uint256) public confirmedAt;

    event Attested(uint256 indexed round, address indexed attestor, uint256 countSoFar);
    event RoundConfirmed(uint256 indexed round, uint256 timestamp);
    event RoundAdvanced(uint256 indexed newRound);
    event NoOp(string reason);

    constructor(address[] memory initialAttestors, uint256 requestedThreshold) {
        for (uint256 i = 0; i < initialAttestors.length; i++) {
            address a = initialAttestors[i];
            if (a != address(0) && !isAttestor[a]) {
                isAttestor[a] = true;
                attestors.push(a);
            }
        }

        uint256 n = attestors.length;
        uint256 t = requestedThreshold;
        if (t == 0) t = 1;
        if (n > 0 && t > n) t = n;
        threshold = t;
    }

    /// @notice Signs the current round on behalf of the caller. Never
    ///         reverts: a caller outside the fixed attestor set, or an
    ///         attestor who already signed this round, is a silent
    ///         no-op instead.
    function attest() external {
        if (!isAttestor[msg.sender]) {
            emit NoOp("not an attestor");
            return;
        }
        if (hasAttested[currentRound][msg.sender]) {
            emit NoOp("already attested this round");
            return;
        }

        hasAttested[currentRound][msg.sender] = true;
        attestationCount[currentRound] += 1;

        emit Attested(currentRound, msg.sender, attestationCount[currentRound]);

        if (attestationCount[currentRound] == threshold && confirmedAt[currentRound] == 0) {
            confirmedAt[currentRound] = block.timestamp;
            emit RoundConfirmed(currentRound, block.timestamp);
        }
    }

    /// @notice Advances to a new round. Callable by anyone. Never
    ///         reverts: calling before the current round has reached
    ///         its threshold is a silent no-op.
    function advanceRound() external {
        if (confirmedAt[currentRound] == 0) {
            emit NoOp("round not confirmed yet");
            return;
        }
        currentRound += 1;
        emit RoundAdvanced(currentRound);
    }

    function attestorCount() external view returns (uint256) {
        return attestors.length;
    }

    function isRoundConfirmed(uint256 round) external view returns (bool) {
        return confirmedAt[round] != 0;
    }
}

ohmfun/BasketWeights.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

//      /\    /\    /\
//     /  \  /  \  /  \        ohm.fun
//    /    \/    \/    \       stock-backed rebase, ethereum mainnet
//
//         https://ohm.fun

/// @notice Standalone target-weight registry for a named basket of
///         slots. Any address can propose a full weight set; the
///         contract only accepts a proposed set that sums to exactly
///         10,000 basis points. No connection to any token's balance
///         or supply.
/// @dev Every public write function here is no-revert: an invalid
///      proposal (wrong length, bad sum, duplicate label, too many
///      slots) is silently rejected with a `NoOp` event rather than
///      reverting the caller. The live set simply stays whatever it
///      was before the rejected call.
contract BasketWeights {
    /// @notice Maximum number of slots a basket can hold.
    uint256 public constant MAX_SLOTS = 24;
    uint256 public constant BPS_TOTAL = 10_000;

    struct Slot {
        bytes32 label;
        uint16 weightBps;
    }

    /// @dev basket id => live slot list.
    mapping(bytes32 => Slot[]) private _live;
    /// @dev basket id => proposer of the current live set.
    mapping(bytes32 => address) public setBy;
    /// @dev basket id => timestamp the current live set was accepted.
    mapping(bytes32 => uint256) public setAt;
    /// @dev basket id => how many times a set has been accepted.
    mapping(bytes32 => uint256) public revisionOf;

    event WeightsProposed(bytes32 indexed basket, address indexed proposer, uint256 slotCount, uint256 revision);
    event NoOp(string reason);

    /// @notice Replaces the live weight set for `basket` with
    ///         `labels`/`weightsBps`, provided the weights sum to
    ///         exactly 10,000 bps and no label repeats. Callable by
    ///         anyone. Never reverts: any invalid proposal is silently
    ///         rejected (with a `NoOp` event) and the previous live
    ///         set is left untouched.
    function proposeWeights(bytes32 basket, bytes32[] calldata labels, uint16[] calldata weightsBps) external {
        uint256 len = labels.length;
        if (len == 0) {
            emit NoOp("empty set");
            return;
        }
        if (len > MAX_SLOTS) {
            emit NoOp("too many slots");
            return;
        }
        if (len != weightsBps.length) {
            emit NoOp("length mismatch");
            return;
        }

        uint256 sum = 0;
        for (uint256 i = 0; i < len; i++) {
            sum += weightsBps[i];
            for (uint256 j = i + 1; j < len; j++) {
                if (labels[i] == labels[j]) {
                    emit NoOp("duplicate label");
                    return;
                }
            }
        }
        if (sum != BPS_TOTAL) {
            emit NoOp("weights do not sum to 10000");
            return;
        }

        delete _live[basket];
        for (uint256 i = 0; i < len; i++) {
            _live[basket].push(Slot({label: labels[i], weightBps: weightsBps[i]}));
        }
        setBy[basket] = msg.sender;
        setAt[basket] = block.timestamp;
        revisionOf[basket] += 1;

        emit WeightsProposed(basket, msg.sender, len, revisionOf[basket]);
    }

    function liveSlotCount(bytes32 basket) external view returns (uint256) {
        return _live[basket].length;
    }

    /// @notice Returns an empty slot (label zero, weight zero) if
    ///         `index` is out of range, rather than reverting.
    function liveSlotAt(bytes32 basket, uint256 index) external view returns (Slot memory) {
        if (index >= _live[basket].length) return Slot({label: bytes32(0), weightBps: 0});
        return _live[basket][index];
    }

    /// @notice Weight in bps for `label` within `basket`, or 0 if the
    ///         label is not present in the current live set.
    function weightOf(bytes32 basket, bytes32 label) external view returns (uint16) {
        Slot[] storage slots = _live[basket];
        for (uint256 i = 0; i < slots.length; i++) {
            if (slots[i].label == label) return slots[i].weightBps;
        }
        return 0;
    }
}

ohmfun/DeviationBand.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

//      /\    /\    /\
//     /  \  /  \  /  \        ohm.fun
//    /    \/    \/    \       stock-backed rebase, ethereum mainnet
//
//         https://ohm.fun

/// @notice Standalone tolerance-band statistics tracker. Any address
///         can submit a signed deviation reading, in basis points, for
///         a named series; the contract classifies each reading as
///         in-band or out-of-band against a fixed band width and keeps
///         running counters. No connection to any token's balance or
///         transfer logic.
/// @dev The public write function here is no-revert: an empty series
///      label is silently ignored (with a `NoOp` event) instead of
///      reverting the caller.
contract DeviationBand {
    /// @notice Fixed tolerance band, in basis points, applied to every
    ///         series. A reading with |deviationBps| <= BAND_WIDTH_BPS
    ///         counts as in-band.
    uint256 public constant BAND_WIDTH_BPS = 50; // 0.50%

    struct Stats {
        uint64 inBandCount;
        uint64 outOfBandCount;
        int256 lastDeviationBps;
        uint64 lastUpdatedAt;
        int256 worstDeviationBps;
    }

    mapping(bytes32 => Stats) public statsOf;

    event ReadingRecorded(bytes32 indexed series, address indexed submitter, int256 deviationBps, bool inBand);
    event NoOp(string reason);

    /// @notice Records a signed deviation reading for `series`, in
    ///         basis points (can be negative). Updates the series'
    ///         running in-band/out-of-band counters and worst-seen
    ///         deviation by magnitude. Never reverts: an empty series
    ///         label is silently ignored instead.
    function recordReading(bytes32 series, int256 deviationBps) external {
        if (series == bytes32(0)) {
            emit NoOp("empty series");
            return;
        }

        Stats storage s = statsOf[series];
        bool inBand = _abs(deviationBps) <= int256(BAND_WIDTH_BPS);

        if (inBand) {
            s.inBandCount += 1;
        } else {
            s.outOfBandCount += 1;
        }

        if (_abs(deviationBps) > _abs(s.worstDeviationBps)) {
            s.worstDeviationBps = deviationBps;
        }

        s.lastDeviationBps = deviationBps;
        s.lastUpdatedAt = uint64(block.timestamp);

        emit ReadingRecorded(series, msg.sender, deviationBps, inBand);
    }

    /// @notice In-band readings as a fraction of all readings for
    ///         `series`, in basis points. Returns 10,000 (100%) if no
    ///         readings have been recorded yet.
    function complianceBps(bytes32 series) external view returns (uint256) {
        Stats memory s = statsOf[series];
        uint256 total = uint256(s.inBandCount) + uint256(s.outOfBandCount);
        if (total == 0) return 10_000;
        return (uint256(s.inBandCount) * 10_000) / total;
    }

    function totalReadings(bytes32 series) external view returns (uint256) {
        Stats memory s = statsOf[series];
        return uint256(s.inBandCount) + uint256(s.outOfBandCount);
    }

    function _abs(int256 x) internal pure returns (int256) {
        return x < 0 ? -x : x;
    }
}

ohmfun/QuoteConsensus.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

//      /\    /\    /\
//     /  \  /  \  /  \        ohm.fun
//    /    \/    \/    \       stock-backed rebase, ethereum mainnet
//
//         https://ohm.fun

/// @notice Standalone median-consensus price board. Any address can
///         submit a quote for a named instrument; the contract tracks
///         the last N quotes per instrument and computes their median
///         on read, discarding nothing but weighting nothing either.
///         No path back into any token's balance or transfer logic.
/// @dev Every public write function here is no-revert: bad input is
///      silently ignored (with a `NoOp` event explaining why) rather
///      than reverting the caller's transaction. This makes it safe
///      to call from anywhere, including from another contract's
///      callback, without risking that call reverting the whole tx.
contract QuoteConsensus {
    /// @notice Quotes older than this are excluded from the median
    ///         computation, though they remain in storage.
    uint256 public constant STALE_AFTER = 6 hours;
    /// @notice Maximum quotes retained per instrument (ring-style cap,
    ///         oldest overwritten once the cap is reached).
    uint256 public constant MAX_QUOTES = 16;

    struct Quote {
        address submitter;
        uint256 price;
        uint64 timestamp;
    }

    /// @dev instrument label => ring of quotes.
    mapping(bytes32 => Quote[MAX_QUOTES]) private _quotes;
    mapping(bytes32 => uint256) public quoteCount;
    mapping(bytes32 => uint256) private _cursor;

    event QuoteSubmitted(bytes32 indexed instrument, address indexed submitter, uint256 price, uint256 slot);
    event NoOp(string reason);

    /// @notice Submits a price quote for `instrument`. Overwrites the
    ///         oldest slot once `MAX_QUOTES` is reached for that
    ///         instrument; there is no per-submitter uniqueness check,
    ///         so the same address can submit repeatedly. Never
    ///         reverts: an empty instrument or a zero price is
    ///         silently ignored instead.
    function submitQuote(bytes32 instrument, uint256 price) external {
        if (instrument == bytes32(0)) {
            emit NoOp("empty instrument");
            return;
        }
        if (price == 0) {
            emit NoOp("zero price");
            return;
        }

        uint256 slot = _cursor[instrument] % MAX_QUOTES;
        _quotes[instrument][slot] = Quote({submitter: msg.sender, price: price, timestamp: uint64(block.timestamp)});
        _cursor[instrument] += 1;
        if (quoteCount[instrument] < MAX_QUOTES) quoteCount[instrument] += 1;

        emit QuoteSubmitted(instrument, msg.sender, price, slot);
    }

    /// @notice Median of all non-stale quotes currently stored for
    ///         `instrument`. Returns 0 if none qualify, rather than
    ///         reverting; check `freshQuoteCount` to tell "no data"
    ///         apart from "median happens to be zero".
    function medianPrice(bytes32 instrument) public view returns (uint256) {
        uint256[] memory fresh = _freshPrices(instrument);
        if (fresh.length == 0) return 0;
        _sort(fresh);
        uint256 mid = fresh.length / 2;
        if (fresh.length % 2 == 1) return fresh[mid];
        return (fresh[mid - 1] + fresh[mid]) / 2;
    }

    /// @notice How many currently-stored quotes for `instrument` are
    ///         within the staleness window right now.
    function freshQuoteCount(bytes32 instrument) public view returns (uint256 count) {
        uint256 total = quoteCount[instrument];
        for (uint256 i = 0; i < total; i++) {
            if (block.timestamp - _quotes[instrument][i].timestamp <= STALE_AFTER) count++;
        }
    }

    /// @notice Raw quote at `index` for `instrument`, regardless of
    ///         staleness. Returns an all-zero Quote if `index` is out
    ///         of range rather than reverting.
    function quoteAt(bytes32 instrument, uint256 index) external view returns (Quote memory) {
        if (index >= quoteCount[instrument]) return Quote({submitter: address(0), price: 0, timestamp: 0});
        return _quotes[instrument][index];
    }

    function _freshPrices(bytes32 instrument) internal view returns (uint256[] memory) {
        uint256 total = quoteCount[instrument];
        uint256[] memory buf = new uint256[](total);
        uint256 n = 0;
        for (uint256 i = 0; i < total; i++) {
            Quote memory q = _quotes[instrument][i];
            if (block.timestamp - q.timestamp <= STALE_AFTER) {
                buf[n] = q.price;
                n++;
            }
        }
        uint256[] memory out = new uint256[](n);
        for (uint256 i = 0; i < n; i++) out[i] = buf[i];
        return out;
    }

    /// @dev Simple insertion sort. Bounded by MAX_QUOTES (16), so the
    ///      O(n^2) cost never matters in practice.
    function _sort(uint256[] memory arr) internal pure {
        for (uint256 i = 1; i < arr.length; i++) {
            uint256 key = arr[i];
            uint256 j = i;
            while (j > 0 && arr[j - 1] > key) {
                arr[j] = arr[j - 1];
                j--;
            }
            arr[j] = key;
        }
    }
}

ohmfun/RedemptionQueue.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

//      /\    /\    /\
//     /  \  /  \  /  \        ohm.fun
//    /    \/    \/    \       stock-backed rebase, ethereum mainnet
//
//         https://ohm.fun

/// @notice Standalone FIFO request queue. Any address can join the
///         queue with a requested amount; anyone can pop the front of
///         the queue, which only records that the front entry was
///         cleared, it does not move any funds. A pure ledger of
///         request order, independent of any token's balance logic.
/// @dev Every public write function here is no-revert: joining with a
///      zero amount, clearing an empty queue, or withdrawing an entry
///      that is not yours or already cleared all silently no-op (with
///      a `NoOp` event) instead of reverting.
contract RedemptionQueue {
    struct Entry {
        address requester;
        uint256 amount;
        uint64 joinedAt;
        bool cleared;
    }

    Entry[] private _entries;
    uint256 private _head;

    event Joined(address indexed requester, uint256 amount, uint256 indexed position);
    event Cleared(uint256 indexed position, address indexed clearedBy);
    event Withdrawn(address indexed requester, uint256 indexed position);
    event NoOp(string reason);

    /// @notice Joins the queue requesting `amount`. Returns the
    ///         entry's fixed position, which never changes even as
    ///         earlier entries are cleared. Never reverts: a zero
    ///         amount is silently ignored and `type(uint256).max` is
    ///         returned as a sentinel meaning "not joined".
    function join(uint256 amount) external returns (uint256 position) {
        if (amount == 0) {
            emit NoOp("zero amount");
            return type(uint256).max;
        }
        position = _entries.length;
        _entries.push(Entry({requester: msg.sender, amount: amount, joinedAt: uint64(block.timestamp), cleared: false}));
        emit Joined(msg.sender, amount, position);
    }

    /// @notice Clears the entry currently at the front of the queue.
    ///         Callable by anyone; this contract does not custody or
    ///         move funds, it only advances the queue pointer. Never
    ///         reverts: calling on an empty queue is a silent no-op.
    function clearFront() external {
        if (_head >= _entries.length) {
            emit NoOp("queue empty");
            return;
        }
        _entries[_head].cleared = true;
        emit Cleared(_head, msg.sender);
        _head++;
    }

    /// @notice Lets the original requester withdraw their own entry
    ///         before it reaches the front, removing it from
    ///         consideration without needing clearFront to reach it.
    ///         Never reverts: an out-of-range position, an entry that
    ///         is not the caller's, or one already cleared are all
    ///         silent no-ops.
    function withdraw(uint256 position) external {
        if (position >= _entries.length) {
            emit NoOp("out of range");
            return;
        }
        Entry storage e = _entries[position];
        if (e.requester != msg.sender) {
            emit NoOp("not your entry");
            return;
        }
        if (e.cleared) {
            emit NoOp("already cleared");
            return;
        }
        e.cleared = true;
        emit Withdrawn(msg.sender, position);
    }

    /// @notice Position index currently at the front of the queue.
    function frontPosition() external view returns (uint256) {
        return _head;
    }

    /// @notice Number of entries ever joined, cleared or not.
    function totalEntries() external view returns (uint256) {
        return _entries.length;
    }

    /// @notice How many entries currently sit ahead of `position` and
    ///         are not yet cleared, i.e. this entry's wait count.
    ///         Returns 0 for an out-of-range position rather than
    ///         reverting.
    function positionsAhead(uint256 position) external view returns (uint256 count) {
        if (position >= _entries.length) return 0;
        for (uint256 i = _head; i < position; i++) {
            if (!_entries[i].cleared) count++;
        }
    }

    /// @notice Returns an empty Entry if `position` is out of range,
    ///         rather than reverting.
    function entryAt(uint256 position) external view returns (Entry memory) {
        if (position >= _entries.length) return Entry({requester: address(0), amount: 0, joinedAt: 0, cleared: false});
        return _entries[position];
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.