Skip to content
Verified contractExactMIT

UptimeOracle

Address0xe89c968311824806b85bc282630f66dda4e5df36
Balance

0 ETH

 

Transactions

3

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,798,212
Creation transaction
0x9899c759ed…9219862e21

src/UptimeOracle.sol

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

import {ERC20} from "./lib/ERC20.sol";
import {Owned} from "./lib/Owned.sol";

/// @title UptimeOracle
/// @notice Uptime has to come from somewhere, and "the provider says so" is not an answer.
///         A staked attester set probes listings and reports downtime per epoch. The
///         finalized value is the median of the reports, and attesters whose report
///         strays too far from that median lose stake — so lying is only profitable if
///         you can buy the median outright.
contract UptimeOracle is Owned {
    event AttesterStaked(address indexed attester, uint256 amount, uint256 total);
    event AttesterUnbondRequested(address indexed attester, uint64 unlockAt);
    event AttesterUnstaked(address indexed attester, uint256 amount);
    event Reported(uint256 indexed listingId, uint256 indexed epoch, address indexed attester, uint32 downSeconds);
    event Finalized(uint256 indexed listingId, uint256 indexed epoch, uint32 downSeconds, uint256 reports);
    event AttesterSlashed(address indexed attester, uint256 amount, uint32 reported, uint32 median);
    event TreasurySet(address treasury);

    error BelowMinStake(uint256 required, uint256 held);
    error NotAnAttester();
    error EpochNotOver();
    error SubmissionClosed();
    error SubmissionOpen();
    error AlreadyReported();
    error AlreadyFinalized();
    error NotFinalized();
    error TooManyReports();
    error DowntimeOutOfRange();
    error QuorumNotMet(uint256 required, uint256 got);
    error UnbondNotStarted();
    error UnbondPending(uint64 unlockAt);
    error StakeLocked();
    error TransferFailed();

    /// @notice Settlement granularity. One hour is short enough that a four-nines
    ///         listing has no free downtime at all, which is the point of the tier.
    uint256 public constant EPOCH = 1 hours;
    /// @notice How long after an epoch ends attesters may report on it.
    uint256 public constant SUBMISSION_WINDOW = 1 hours;
    /// @notice Reports needed before an epoch can be finalized.
    uint256 public constant QUORUM = 3;
    uint256 public constant MAX_REPORTS = 15;
    /// @notice Deviation from the median tolerated before an attester is slashed.
    uint32 public constant DEVIATION_TOLERANCE = 60;
    uint256 public constant DEVIATION_SLASH_BPS = 500; // 5% of stake
    uint256 public constant MIN_STAKE = 10_000e18;
    uint256 public constant ATTESTER_UNBOND_DELAY = 14 days;

    struct Report {
        address attester;
        uint32 downSeconds;
    }

    struct Attester {
        uint128 stake;
        uint64 unbondingAt;
    }

    ERC20 public immutable nine;
    address public treasury;

    mapping(address => Attester) public attesters;
    uint256 public totalAttesterStake;

    mapping(uint256 => mapping(uint256 => Report[])) internal _reports;
    mapping(uint256 => mapping(uint256 => mapping(address => bool))) public hasReported;
    mapping(uint256 => mapping(uint256 => bool)) internal _finalized;
    mapping(uint256 => mapping(uint256 => uint32)) internal _downtime;

    constructor(address _owner, ERC20 _nine, address _treasury) Owned(_owner) {
        nine = _nine;
        treasury = _treasury;
    }

    function setTreasury(address _treasury) external onlyOwner {
        if (_treasury == address(0)) revert ZeroAddress();
        treasury = _treasury;
        emit TreasurySet(_treasury);
    }

    // --- attester set ---

    function stake(uint128 amount) external {
        Attester storage a = attesters[msg.sender];
        a.stake += amount;
        a.unbondingAt = 0;
        totalAttesterStake += amount;
        if (!nine.transferFrom(msg.sender, address(this), amount)) revert TransferFailed();
        emit AttesterStaked(msg.sender, amount, a.stake);
    }

    function requestUnstake() external {
        Attester storage a = attesters[msg.sender];
        if (a.stake == 0) revert NotAnAttester();
        uint64 unlockAt = uint64(block.timestamp + ATTESTER_UNBOND_DELAY);
        a.unbondingAt = unlockAt;
        emit AttesterUnbondRequested(msg.sender, unlockAt);
    }

    function unstake() external returns (uint256 amount) {
        Attester storage a = attesters[msg.sender];
        if (a.unbondingAt == 0) revert UnbondNotStarted();
        if (block.timestamp < a.unbondingAt) revert UnbondPending(a.unbondingAt);
        amount = a.stake;
        a.stake = 0;
        a.unbondingAt = 0;
        totalAttesterStake -= amount;
        if (!nine.transfer(msg.sender, amount)) revert TransferFailed();
        emit AttesterUnstaked(msg.sender, amount);
    }

    /// @notice An attester counts only while fully staked and not on the way out.
    function isActive(address who) public view returns (bool) {
        Attester storage a = attesters[who];
        return a.stake >= MIN_STAKE && a.unbondingAt == 0;
    }

    // --- reporting ---

    function currentEpoch() public view returns (uint256) {
        return block.timestamp / EPOCH;
    }

    function epochStart(uint256 epoch) public pure returns (uint256) {
        return epoch * EPOCH;
    }

    /// @notice Report observed downtime for a listing over one finished epoch.
    function report(uint256 listingId, uint256 epoch, uint32 downSeconds) external {
        if (!isActive(msg.sender)) revert BelowMinStake(MIN_STAKE, attesters[msg.sender].stake);
        uint256 end = epochStart(epoch) + EPOCH;
        if (block.timestamp < end) revert EpochNotOver();
        if (block.timestamp >= end + SUBMISSION_WINDOW) revert SubmissionClosed();
        if (downSeconds > EPOCH) revert DowntimeOutOfRange();
        if (_finalized[listingId][epoch]) revert AlreadyFinalized();
        if (hasReported[listingId][epoch][msg.sender]) revert AlreadyReported();

        Report[] storage rs = _reports[listingId][epoch];
        if (rs.length >= MAX_REPORTS) revert TooManyReports();

        hasReported[listingId][epoch][msg.sender] = true;
        rs.push(Report({attester: msg.sender, downSeconds: downSeconds}));
        emit Reported(listingId, epoch, msg.sender, downSeconds);
    }

    /// @notice Close an epoch. Permissionless: anyone who wants the number settled can pay for it.
    function finalize(uint256 listingId, uint256 epoch) external returns (uint32 median) {
        if (_finalized[listingId][epoch]) revert AlreadyFinalized();
        uint256 end = epochStart(epoch) + EPOCH;
        if (block.timestamp < end + SUBMISSION_WINDOW) revert SubmissionOpen();

        Report[] storage rs = _reports[listingId][epoch];
        uint256 n = rs.length;
        if (n < QUORUM) revert QuorumNotMet(QUORUM, n);

        median = _median(rs);
        _finalized[listingId][epoch] = true;
        _downtime[listingId][epoch] = median;
        emit Finalized(listingId, epoch, median, n);

        _punishOutliers(rs, median);
    }

    function _median(Report[] storage rs) internal view returns (uint32) {
        uint256 n = rs.length;
        uint32[] memory v = new uint32[](n);
        for (uint256 i; i < n; ++i) {
            v[i] = rs[i].downSeconds;
        }
        // Insertion sort: n is capped at MAX_REPORTS, so this is cheap and obvious.
        for (uint256 i = 1; i < n; ++i) {
            uint32 key = v[i];
            uint256 j = i;
            while (j > 0 && v[j - 1] > key) {
                v[j] = v[j - 1];
                --j;
            }
            v[j] = key;
        }
        // Even sets take the lower middle: when the set is split, believe the provider less.
        return n % 2 == 1 ? v[n / 2] : v[n / 2 - 1];
    }

    function _punishOutliers(Report[] storage rs, uint32 median) internal {
        uint256 forfeited;
        uint256 n = rs.length;
        for (uint256 i; i < n; ++i) {
            uint32 reported = rs[i].downSeconds;
            uint32 delta = reported > median ? reported - median : median - reported;
            if (delta <= DEVIATION_TOLERANCE) continue;

            Attester storage a = attesters[rs[i].attester];
            uint256 penalty = (uint256(a.stake) * DEVIATION_SLASH_BPS) / 10_000;
            if (penalty == 0) continue;
            a.stake -= uint128(penalty);
            totalAttesterStake -= penalty;
            forfeited += penalty;
            emit AttesterSlashed(rs[i].attester, penalty, reported, median);
        }
        if (forfeited > 0) {
            if (!nine.transfer(treasury, forfeited)) revert TransferFailed();
        }
    }

    // --- views ---

    function isFinalized(uint256 listingId, uint256 epoch) external view returns (bool) {
        return _finalized[listingId][epoch];
    }

    function downtimeOf(uint256 listingId, uint256 epoch) external view returns (uint256) {
        if (!_finalized[listingId][epoch]) revert NotFinalized();
        return _downtime[listingId][epoch];
    }

    function reportCount(uint256 listingId, uint256 epoch) external view returns (uint256) {
        return _reports[listingId][epoch].length;
    }

    function reportAt(uint256 listingId, uint256 epoch, uint256 i) external view returns (Report memory) {
        return _reports[listingId][epoch][i];
    }
}

src/lib/ERC20.sol

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

/// @notice Minimal ERC-20 with EIP-2612 permit.
abstract contract ERC20 {
    event Transfer(address indexed from, address indexed to, uint256 amount);
    event Approval(address indexed owner, address indexed spender, uint256 amount);

    error PermitExpired();
    error InvalidSigner();

    string public name;
    string public symbol;
    uint8 public immutable decimals;

    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    uint256 internal immutable INITIAL_CHAIN_ID;
    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
    mapping(address => uint256) public nonces;

    constructor(string memory _name, string memory _symbol, uint8 _decimals) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;
        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = _computeDomainSeparator();
    }

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;
        unchecked {
            balanceOf[to] += amount;
        }
        emit Transfer(msg.sender, to, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender];
        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
        balanceOf[from] -= amount;
        unchecked {
            balanceOf[to] += amount;
        }
        emit Transfer(from, to, amount);
        return true;
    }

    function permit(
        address _owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        if (block.timestamp > deadline) revert PermitExpired();
        address recovered;
        unchecked {
            recovered = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                _owner,
                                spender,
                                value,
                                nonces[_owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );
        }
        if (recovered == address(0) || recovered != _owner) revert InvalidSigner();
        allowance[recovered][spender] = value;
        emit Approval(_owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : _computeDomainSeparator();
    }

    function _computeDomainSeparator() internal view virtual returns (bytes32) {
        return keccak256(
            abi.encode(
                keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                keccak256(bytes(name)),
                keccak256("1"),
                block.chainid,
                address(this)
            )
        );
    }

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;
        unchecked {
            balanceOf[to] += amount;
        }
        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;
        unchecked {
            totalSupply -= amount;
        }
        emit Transfer(from, address(0), amount);
    }
}

src/lib/Owned.sol

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

/// @notice Minimal single-owner authorization.
abstract contract Owned {
    event OwnershipTransferred(address indexed from, address indexed to);

    error NotOwner();
    error ZeroAddress();

    address public owner;

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    constructor(address _owner) {
        if (_owner == address(0)) revert ZeroAddress();
        owner = _owner;
        emit OwnershipTransferred(address(0), _owner);
    }

    function transferOwnership(address to) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        emit OwnershipTransferred(owner, to);
        owner = to;
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.