Skip to content
Verified contractExactGPL-2.0-or-later

RewardsExpiry

Address0x8c19bd0381dc7592ba4d5944071a5175ba6e43f2
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.28

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
GPL-2.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,263,479
Creation transaction
0x261a46fc18…ed486c5cfa

src/rewards-expiry/RewardsExpiry.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import {IUniversalRewardsDistributor, PendingRoot} from "src/interfaces/IUniversalRewardsDistributor.sol";
import {IModuleManager} from "@interfaces/safe/IModuleManager.sol";

contract RewardsExpiry {
    struct Row {
        address account;
        uint256 amount;
        uint256 expiredThrough;
    }

    struct Plan {
        uint256 round;
        uint256 index;
        bytes32 parent;
        bytes32[] batches;
    }

    struct Batch {
        uint256 round;
        uint256 index;
        bool last;
        bytes32 ledger;
        bytes32 parent;
        address token;
        uint256 treasuryAmount;
        Row[] rows;
        bytes program;
        bytes32[] nodes;
    }

    IUniversalRewardsDistributor public immutable DISTRIBUTOR;
    address public immutable SAFE;
    address public immutable TREASURY;
    address public immutable PREPARER;
    uint256 public immutable DELAY;
    uint256 public immutable CHAIN_ID;
    bytes32 public proposal;
    uint256 public proposedAt;
    uint256 public round;
    uint256 public nextBatch;
    bool public complete;
    bytes32 public expectedRoot;
    uint256 public firstBatch;
    bytes32[] public batches;
    mapping(bytes32 => bool) public consumed;

    event Prepared(bytes32 indexed digest, uint256 validAt);
    event Reduced(bytes32 indexed digest, address indexed account, address indexed token, uint256 paid, uint256 amount);
    event Activated(bytes32 indexed digest, bytes32 indexed parent, bytes32 indexed root, uint256 recovered);

    constructor(address distributor, address treasury, address preparer) {
        require(block.chainid == 1 || block.chainid == 8453 || block.chainid == 42161, "chain");
        require(
            distributor == 0x000000006feeE0b7a0564Cd5CeB283e10347C4Db
                || (block.chainid == 1 && distributor == 0xD4898A378eA555595c4E7dbDE722B134a3F346D1),
            "distributor"
        );
        CHAIN_ID = block.chainid;
        DISTRIBUTOR = IUniversalRewardsDistributor(distributor);
        require(treasury != address(0) && treasury != address(DISTRIBUTOR), "treasury");
        require(preparer.code.length != 0, "preparer");
        SAFE = DISTRIBUTOR.owner();
        TREASURY = treasury;
        PREPARER = preparer;
        uint256 timelock = DISTRIBUTOR.timelock();
        DELAY = timelock > 3 hours ? timelock : 3 hours;
        require(SAFE.code.length != 0, "owner");
    }

    function digest(Batch calldata batch) public view returns (bytes32) {
        return keccak256(abi.encode(block.chainid, address(this), address(DISTRIBUTOR), SAFE, TREASURY, DELAY, batch));
    }

    function checkRoot(bytes32 parent) external view {
        require(DISTRIBUTOR.root() == parent, "parent");
    }

    function commitment(Batch calldata batch) public pure returns (bytes32) {
        return keccak256(abi.encode(batch.round, batch.index, batch.last, batch.token, batch.rows));
    }

    function planDigest(Plan calldata plan) public view returns (bytes32) {
        return keccak256(abi.encode(block.chainid, address(this), address(DISTRIBUTOR), SAFE, TREASURY, DELAY, plan));
    }

    function prepare(Plan calldata plan) external {
        require(msg.sender == SAFE || msg.sender == PREPARER, "preparer");
        require(plan.round > 0 && plan.round >= round && plan.batches.length > 0, "round");
        if (plan.round == round) require(!complete && plan.index == nextBatch, "batch");
        else require(plan.index == 0, "batch");
        require(DISTRIBUTOR.root() == plan.parent, "parent");
        proposal = planDigest(plan);
        proposedAt = block.timestamp;
        round = plan.round;
        nextBatch = plan.index;
        firstBatch = plan.index;
        complete = false;
        expectedRoot = plan.parent;
        batches = plan.batches;
        uint256 delay = DISTRIBUTOR.timelock();
        emit Prepared(proposal, block.timestamp + (delay > DELAY ? delay : DELAY));
    }

    function activate(Batch calldata batch) external {
        require(msg.sender == SAFE || msg.sender == PREPARER, "preparer");
        require(block.chainid == CHAIN_ID, "chain");
        require(proposedAt != 0 && !complete, "proposal");
        require(batch.round == round && batch.index == nextBatch, "batch");
        require(commitment(batch) == batches[nextBatch - firstBatch], "proposal");
        require(batch.last == (nextBatch - firstBatch + 1 == batches.length), "last");
        bytes32 id = digest(batch);
        uint256 delay = DISTRIBUTOR.timelock();
        require(block.timestamp >= proposedAt + (delay > DELAY ? delay : DELAY), "delay");
        require(DISTRIBUTOR.owner() == SAFE && batch.parent == expectedRoot && DISTRIBUTOR.root() == expectedRoot, "parent");
        PendingRoot memory pending = DISTRIBUTOR.pendingRoot();
        require(pending.validAt == 0, "pending");
        address recipient = DISTRIBUTOR.recipients(TREASURY);
        require(recipient == address(0) || recipient == TREASURY, "recipient");
        require(batch.rows.length > 0 && batch.rows.length <= 64 && batch.program.length <= 4096, "bounds");
        uint256[] memory amounts = new uint256[](batch.rows.length);
        uint256 recovered;
        for (uint256 i; i < batch.rows.length; ++i) {
            Row calldata row = batch.rows[i];
            require(row.account != TREASURY && row.account != address(0) && row.expiredThrough <= row.amount, "row");
            bytes32 key = keccak256(abi.encode(batch.round, row.account, batch.token));
            require(!consumed[key], "consumed");
            consumed[key] = true;
            uint256 paid = DISTRIBUTOR.claimed(row.account, batch.token);
            require(paid <= row.amount, "paid");
            uint256 reduction = row.expiredThrough > paid ? row.expiredThrough - paid : 0;
            amounts[i] = row.amount - reduction;
            recovered += reduction;
            emit Reduced(id, row.account, batch.token, paid, reduction);
        }
        require(DISTRIBUTOR.claimed(TREASURY, batch.token) <= batch.treasuryAmount, "treasury paid");
        (bytes32 oldRoot, bytes32 newRoot) = rebuild(batch, amounts, recovered);
        require(oldRoot == batch.parent, "proof");
        expectedRoot = newRoot;
        nextBatch = batch.index + 1;
        complete = batch.last;
        if (complete) {
            delete proposal;
            delete proposedAt;
        }
        if (newRoot != oldRoot) {
            require(
                IModuleManager(SAFE)
                    .execTransactionFromModule(
                        address(DISTRIBUTOR),
                        0,
                        abi.encodeCall(DISTRIBUTOR.setRoot, (newRoot, id)),
                        IModuleManager.Operation.Call
                    ),
                "safe call"
            );
        }
        emit Activated(id, oldRoot, newRoot, recovered);
    }

    function rebuild(Batch calldata batch, uint256[] memory amounts, uint256 recovered)
        internal
        view
        returns (bytes32, bytes32)
    {
        bytes32[2][] memory stack = new bytes32[2][](batch.program.length);
        uint256 depth;
        uint256 node;
        uint256 row;
        bool treasury;
        for (uint256 i; i < batch.program.length; ++i) {
            uint8 op = uint8(batch.program[i]);
            if (op == 3) {
                require(depth >= 2, "stack");
                stack[depth - 2][0] = pair(stack[depth - 2][0], stack[depth - 1][0]);
                stack[depth - 2][1] = pair(stack[depth - 2][1], stack[depth - 1][1]);
                --depth;
                continue;
            }
            if (op == 0) {
                require(node < batch.nodes.length, "node");
                stack[depth][0] = batch.nodes[node];
                stack[depth][1] = batch.nodes[node++];
            } else if (op == 1) {
                require(row < batch.rows.length, "leaf");
                stack[depth][0] = leaf(batch.rows[row].account, batch.token, batch.rows[row].amount);
                stack[depth][1] = leaf(batch.rows[row].account, batch.token, amounts[row]);
                ++row;
            } else if (op == 2) {
                require(!treasury, "treasury duplicate");
                treasury = true;
                stack[depth][0] = leaf(TREASURY, batch.token, batch.treasuryAmount);
                stack[depth][1] = leaf(TREASURY, batch.token, batch.treasuryAmount + recovered);
            } else {
                revert("opcode");
            }
            ++depth;
        }
        require(depth == 1 && node == batch.nodes.length && row == batch.rows.length && treasury, "frontier");
        return (stack[0][0], stack[0][1]);
    }

    function leaf(address account, address token, uint256 amount) internal pure returns (bytes32) {
        return keccak256(bytes.concat(keccak256(abi.encode(account, token, amount))));
    }

    function pair(bytes32 a, bytes32 b) internal pure returns (bytes32) {
        return a < b ? keccak256(abi.encodePacked(a, b)) : keccak256(abi.encodePacked(b, a));
    }
}

node_modules/@stake-dao/interfaces/src/interfaces/safe/IModuleManager.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/**
 * @title IModuleManager - An interface of contract managing Safe modules
 * @notice Modules are extensions with unlimited access to a Safe that can be added to a Safe by its owners.
 *            ⚠️ WARNING: Modules are a security risk since they can execute arbitrary transactions,
 *            so only trusted and audited modules should be added to a Safe. A malicious module can
 *            completely takeover a Safe.
 * @author @safe-global/safe-protocol
 */
interface IModuleManager {
    enum Operation {
        Call,
        DelegateCall
    }
    event EnabledModule(address indexed module);
    event DisabledModule(address indexed module);
    event ExecutionFromModuleSuccess(address indexed module);
    event ExecutionFromModuleFailure(address indexed module);
    event ChangedModuleGuard(address indexed moduleGuard);

    /**
     * @notice Enables the module `module` for the Safe.
     * @dev This can only be done via a Safe transaction.
     * @param module Module to be whitelisted.
     */
    function enableModule(address module) external;

    /**
     * @notice Disables the module `module` for the Safe.
     * @dev This can only be done via a Safe transaction.
     * @param prevModule Previous module in the modules linked list.
     * @param module Module to be removed.
     */
    function disableModule(address prevModule, address module) external;

    /**
     * @notice Execute `operation` (0: Call, 1: DelegateCall) to `to` with `value` (Native Token)
     * @param to Destination address of module transaction.
     * @param value Ether value of module transaction.
     * @param data Data payload of module transaction.
     * @param operation Operation type of module transaction.
     * @return success Boolean flag indicating if the call succeeded.
     */
    function execTransactionFromModule(address to, uint256 value, bytes memory data, Operation operation)
        external
        returns (bool success);

    /**
     * @notice Execute `operation` (0: Call, 1: DelegateCall) to `to` with `value` (Native Token) and return data
     * @param to Destination address of module transaction.
     * @param value Ether value of module transaction.
     * @param data Data payload of module transaction.
     * @param operation Operation type of module transaction.
     * @return success Boolean flag indicating if the call succeeded.
     * @return returnData Data returned by the call.
     */
    function execTransactionFromModuleReturnData(address to, uint256 value, bytes memory data, Operation operation)
        external
        returns (bool success, bytes memory returnData);

    /**
     * @notice Returns if a module is enabled
     * @return True if the module is enabled
     */
    function isModuleEnabled(address module) external view returns (bool);

    /**
     * @notice Returns an array of modules.
     *         If all entries fit into a single page, the next pointer will be 0x1.
     *         If another page is present, next will be the last element of the returned array.
     * @param start Start of the page. Has to be a module or start pointer (0x1 address)
     * @param pageSize Maximum number of modules that should be returned. Has to be > 0
     * @return array Array of modules.
     * @return next Start of the next page.
     */
    function getModulesPaginated(address start, uint256 pageSize)
        external
        view
        returns (address[] memory array, address next);

    /**
     * @dev Set a module guard that checks transactions initiated by the module before execution
     *      This can only be done via a Safe transaction.
     *      ⚠️ IMPORTANT: Since a module guard has full power to block Safe transaction execution initiated via a module,
     *        a broken module guard can cause a denial of service for the Safe modules. Make sure to carefully
     *        audit the module guard code and design recovery mechanisms.
     * @notice Set Module Guard `moduleGuard` for the Safe. Make sure you trust the module guard.
     * @param moduleGuard The address of the module guard to be used or the zero address to disable the module guard.
     */
    function setModuleGuard(address moduleGuard) external;
}

src/interfaces/IUniversalRewardsDistributor.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.19;

/// @notice The pending root struct for a merkle tree distribution during the timelock.
struct PendingRoot {
    /// @dev The submitted pending root.
    bytes32 root;
    /// @dev The optional ipfs hash containing metadata about the root (e.g. the merkle tree itself).
    bytes32 ipfsHash;
    /// @dev The timestamp at which the pending root can be accepted.
    uint256 validAt;
}

/// @dev This interface is used for factorizing IUniversalRewardsDistributorStaticTyping and
/// IUniversalRewardsDistributor.
/// @dev Consider using the IUniversalRewardsDistributor interface instead of this one.
interface IUniversalRewardsDistributorBase {
    function root() external view returns (bytes32);

    function owner() external view returns (address);

    function timelock() external view returns (uint256);

    function ipfsHash() external view returns (bytes32);

    function isUpdater(address) external view returns (bool);

    function claimed(address, address) external view returns (uint256);

    function acceptRoot() external;

    function setRoot(bytes32 newRoot, bytes32 newIpfsHash) external;

    function setTimelock(uint256 newTimelock) external;

    function setRootUpdater(address updater, bool active) external;

    function revokePendingRoot() external;

    function setOwner(address newOwner) external;

    function submitRoot(bytes32 newRoot, bytes32 ipfsHash) external;

    function claim(address account, address reward, uint256 claimable, bytes32[] memory proof)
        external
        returns (uint256 amount);

    function recipients(address account) external view returns (address);

    function setRecipient(address account, address recipient) external;
}

/// @dev This interface is inherited by the UniversalRewardsDistributor so that function signatures are checked by the
/// compiler.
/// @dev Consider using the IUniversalRewardsDistributor interface instead of this one.
interface IUniversalRewardsDistributorStaticTyping is IUniversalRewardsDistributorBase {
    function pendingRoot() external view returns (bytes32 root, bytes32 ipfsHash, uint256 validAt);
}

/// @title IUniversalRewardsDistributor
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @dev Use this interface for UniversalRewardsDistributor to have access to all the functions with the appropriate
/// function signatures.
interface IUniversalRewardsDistributor is IUniversalRewardsDistributorBase {
    function pendingRoot() external view returns (PendingRoot memory);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "solady/=node_modules/solady/",
    "solmate/=node_modules/solmate/",
    "forge-std/=node_modules/forge-std/",
    "@address-book/=node_modules/@stake-dao/address-book/",
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "solidity-examples/=node_modules/@layerzerolabs/solidity-examples/contracts/",
    "murky.git/=node_modules/murky.git/",
    "murky/=node_modules/murky.git/src/",
    "weiroll/=node_modules/weiroll/contracts/",
    "@interfaces/=node_modules/@stake-dao/interfaces/src/interfaces/",
    "@shared/=node_modules/@stake-dao/interfaces/src/interfaces/",
    "node_modules/@stake-dao/shared/:src/=node_modules/@stake-dao/shared/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.