Skip to content
Verified contractExactMIT

MigcFounderGovernance

Address0xef85b42b295331c462b6d849380e4e4499ef2e8a
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.22

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.22+commit.4fc1097e
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,066,533
Creation transaction
0x9ead3dd6e0…cc840dca9c

contracts/MigcFounderGovernance.sol

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

import "@openzeppelin/contracts/access/IAccessControl.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./MgtWalletRegistry.sol";

interface IMigcGovernedToken {
    function setTreasuryWallet(address wallet, bool allowed) external;
}
interface IMigcUUPS {
    function upgradeToAndCall(address implementation, bytes calldata data) external payable;
}

/// @notice Local review candidate. Two distinct founders approve immutable actions.
/// @dev No arbitrary-call or role-grant escape hatch. Bootstrap authority expires on seal.
contract MigcFounderGovernance is ReentrancyGuard {
    uint64 public constant DELAY = 24 hours;
    address public immutable token;
    address public immutable manager;
    address public immutable bootstrapper;
    address[3] public founders;
    MgtWalletRegistry public registry;
    bool public isSealed;
    uint256 public nonce;
    uint256 public activeMigration;
    enum Kind { Upgrade, Wallets, FounderReplacement, OperationalRole }
    uint256 public founderEpoch;
    mapping(address => uint256) public upgradeRevision;
    mapping(bytes32 => uint256) public operationalRoleRevision;
    struct Proposal {
        Kind kind;
        address target;
        address first;
        address second;
        bytes32 codeHash;
        bytes32 dataHash;
        bytes32 reasonHash;
        bytes32 reconciliationHash;
        uint64 eligibleAt;
        uint8 approvals;
        uint8 cancellations;
        bool done;
        uint256 migrationNonce;
        uint256 epoch;
        uint256 revision;
        bool replacementAccepted;
        bool grantOperationalRole;
    }
    mapping(uint256 => Proposal) private _proposals;
    function proposals(uint256 id) external view returns(Proposal memory) { return _proposals[id]; }
    error Blocked();
    event Proposed(uint256 indexed id, Kind kind, address target, address first, address second, bytes32 dataHash, bytes32 reasonHash, bytes32 reconciliationHash);
    event Approved(uint256 indexed id, address indexed founder, uint64 eligibleAt);
    event FounderReplacementAccepted(uint256 indexed id,address indexed replacement);
    event CancellationApproved(uint256 indexed id, address indexed founder);
    event Cancelled(uint256 indexed id);
    event Executed(uint256 indexed id);
    event Sealed(address registry);

    constructor(address t, address m, address[3] memory f) {
        if(t.code.length == 0 || m.code.length == 0 || t == m) revert Blocked();
        for(uint256 i; i < 3; ++i) {
            if(f[i] == address(0) || f[i] == t || f[i] == m) revert Blocked();
            for(uint256 j; j < i; ++j) if(f[i] == f[j]) revert Blocked();
        }
        token=t; manager=m; founders=f; bootstrapper=msg.sender;
    }
    function _bit() private view returns(uint8) {
        for(uint8 i; i<3; ++i) if(founders[i]==msg.sender) return uint8(1<<i);
        revert Blocked();
    }
    function _quorum(uint8 mask) private pure returns(bool) {
        return mask != 0 && (mask & (mask-1)) != 0;
    }
    /// @dev Deployment must separately verify complete RoleGranted/RoleRevoked history.
    /// AccessControl is not enumerable; this check alone cannot prove exclusive authority.
    function seal(address r) external {
        if(msg.sender!=bootstrapper || isSealed || r.code.length==0) revert Blocked();
        MgtWalletRegistry candidate=MgtWalletRegistry(r);
        if(candidate.owner()!=address(this) || candidate.pendingOwner()!=address(0) ||
           address(candidate.mgt())!=token || address(candidate.payoutManager())!=manager ||
           candidate.migrationDelay()!=DELAY || candidate.migrationPending()) revert Blocked();
        bytes32 upgradeRole=keccak256("UPGRADER_ROLE");
        for(uint256 i; i<2; ++i) {
            IAccessControl c=IAccessControl(i==0?token:manager);
            if(!c.hasRole(bytes32(0),address(this)) || !c.hasRole(upgradeRole,address(this)) ||
               c.hasRole(bytes32(0),bootstrapper) || c.hasRole(upgradeRole,bootstrapper)) revert Blocked();
            for(uint256 j; j<3; ++j)
                if(c.hasRole(bytes32(0),founders[j]) || c.hasRole(upgradeRole,founders[j])) revert Blocked();
        }
        if(!IAccessControl(token).hasRole(keccak256("ADMIN_ROLE"),address(this))) revert Blocked();
        (bool ok,bytes memory value)=manager.staticcall(abi.encodeWithSignature("walletRegistry()"));
        if(!ok || value.length!=32 || abi.decode(value,(address))!=r) revert Blocked();
        registry=candidate; isSealed=true; emit Sealed(r);
    }
    function proposeUpgrade(address target,address implementation,bytes calldata data,bytes32 reason) external returns(uint256 id) {
        _bit();
        if(!isSealed || (target!=token && target!=manager) || implementation.code.length==0 || reason==0) revert Blocked();
        id=++nonce;
        Proposal storage p=_proposals[id];
        p.epoch=founderEpoch; p.revision=upgradeRevision[target];
        p.kind=Kind.Upgrade; p.target=target; p.first=implementation;
        p.codeHash=implementation.codehash; p.dataHash=keccak256(data); p.reasonHash=reason;
        emit Proposed(id,p.kind,target,implementation,address(0),p.dataHash,reason,bytes32(0));
    }
    function proposeWallets(address treasury,address custody,bytes32 reason,bytes32 reconciliation) external returns(uint256 id) {
        _bit();
        if(!isSealed || activeMigration!=0 || treasury==address(0) || custody==address(0) ||
           treasury==custody || treasury==address(this) || custody==address(this) || reason==0 || reconciliation==0) revert Blocked();
        id=++nonce;
        Proposal storage p=_proposals[id];
        p.epoch=founderEpoch; p.revision=registry.migrationNonce(); p.kind=Kind.Wallets; p.target=address(registry); p.first=treasury; p.second=custody;
        p.reasonHash=reason; p.reconciliationHash=reconciliation;
        emit Proposed(id,p.kind,p.target,treasury,custody,bytes32(0),reason,reconciliation);
    }
    /// @notice Signer replacement uses the same threshold/delay; invalidates old proposals.
    function proposeFounderReplacement(address previous,address replacement,bytes32 reason) external returns(uint256 id) {
        _bit();
        if(!isSealed || replacement==address(0) || replacement==address(this) || replacement==token || replacement==manager || replacement==address(registry) || reason==0) revert Blocked();
        bool found;
        for(uint256 i; i<3; ++i) {
            if(founders[i]==previous) found=true;
            if(founders[i]==replacement) revert Blocked();
        }
        if(!found) revert Blocked();
        id=++nonce; Proposal storage p=_proposals[id];
        p.epoch=founderEpoch; p.kind=Kind.FounderReplacement; p.first=previous; p.second=replacement; p.reasonHash=reason;
        emit Proposed(id,p.kind,address(this),previous,replacement,bytes32(0),reason,bytes32(0));
    }
    /// @notice Only operational roles; DEFAULT_ADMIN and UPGRADER cannot be delegated.
    function proposeOperationalRole(address target,bytes32 role,address account,bool grant,bytes32 reason) external returns(uint256 id) {
        _bit();
        bool allowed=target==token ? role==keccak256("ADMIN_ROLE") : target==manager &&
            (role==keccak256("APPROVER_ROLE") || role==keccak256("EXECUTOR_ROLE") || role==keccak256("PAUSER_ROLE"));
        if(!isSealed || !allowed || account==address(0) || account==address(this) || reason==0) revert Blocked();
        id=++nonce; Proposal storage p=_proposals[id];
        p.epoch=founderEpoch; p.kind=Kind.OperationalRole; p.target=target; p.first=account; p.dataHash=role;
        p.grantOperationalRole=grant; p.revision=operationalRoleRevision[keccak256(abi.encode(target,role,account))]; p.reasonHash=reason;
        emit Proposed(id,p.kind,target,account,address(0),role,reason,bytes32(uint256(grant?1:0)));
    }
    function acceptFounderReplacement(uint256 id) external {
        Proposal storage p=_proposals[id];
        if(id==0 || id>nonce || p.done || p.epoch!=founderEpoch || p.kind!=Kind.FounderReplacement || msg.sender!=p.second) revert Blocked();
        p.replacementAccepted=true; emit FounderReplacementAccepted(id,msg.sender);
    }
    function approve(uint256 id) external nonReentrant {
        uint8 bit=_bit(); Proposal storage p=_proposals[id];
        if(id==0 || id>nonce || p.done || p.epoch!=founderEpoch || p.eligibleAt!=0 || (p.approvals & bit)!=0) revert Blocked();
        p.approvals |= bit;
        if(_quorum(p.approvals)) {
            p.eligibleAt=uint64(block.timestamp)+DELAY;
            if(p.kind==Kind.Wallets) {
                if(activeMigration!=0 || p.revision!=registry.migrationNonce()) revert Blocked();
                activeMigration=id;
                registry.proposeWallets(p.first,p.second,p.reasonHash);
                p.migrationNonce=registry.migrationNonce();
            }
        }
        emit Approved(id,msg.sender,p.eligibleAt);
    }
    /// @notice Two founders can abort immediately; cancellation cannot execute a change.
    function approveCancellation(uint256 id) external nonReentrant {
        uint8 bit=_bit(); Proposal storage p=_proposals[id];
        if(id==0 || id>nonce || p.done || (p.cancellations & bit)!=0) revert Blocked();
        p.cancellations |= bit; emit CancellationApproved(id,msg.sender);
        if(_quorum(p.cancellations)) {
            p.done=true;
            if(activeMigration==id) { activeMigration=0; registry.cancelMigration(); }
            emit Cancelled(id);
        }
    }
    /// @notice Permissionless completion after quorum and delay; caller cannot change terms.
    function execute(uint256 id,bytes calldata data) external nonReentrant {
        Proposal storage p=_proposals[id];
        if(id==0 || id>nonce || p.done || p.epoch!=founderEpoch || p.eligibleAt==0 || block.timestamp<p.eligibleAt) revert Blocked();
        p.done=true;
        if(p.kind==Kind.Upgrade) {
            if(activeMigration!=0 || p.revision!=upgradeRevision[p.target] || p.first.codehash!=p.codeHash || keccak256(data)!=p.dataHash) revert Blocked();
            upgradeRevision[p.target]++;
            IMigcUUPS(p.target).upgradeToAndCall(p.first,data);
        } else if(p.kind==Kind.Wallets) {
            if(data.length!=0 || activeMigration!=id) revert Blocked();
            address oldTreasury=registry.treasury();
            registry.finalizeWallets(p.migrationNonce,p.reconciliationHash);
            if(oldTreasury!=p.first) {
                IMigcGovernedToken(token).setTreasuryWallet(oldTreasury,false);
                IMigcGovernedToken(token).setTreasuryWallet(p.first,true);
            }
            activeMigration=0;
        } else if(p.kind==Kind.FounderReplacement) {
            if(data.length!=0 || activeMigration!=0 || !p.replacementAccepted) revert Blocked();
            bool replaced;
            for(uint256 i; i<3; ++i) if(founders[i]==p.first) {founders[i]=p.second; replaced=true; break;}
            if(!replaced) revert Blocked();
            founderEpoch++;
        } else {
            if(data.length!=0 || activeMigration!=0) revert Blocked();
            bytes32 key=keccak256(abi.encode(p.target,p.dataHash,p.first));
            if(p.revision!=operationalRoleRevision[key]) revert Blocked();
            operationalRoleRevision[key]++;
            if(p.grantOperationalRole) IAccessControl(p.target).grantRole(p.dataHash,p.first);
            else IAccessControl(p.target).revokeRole(p.dataHash,p.first);
        }
        emit Executed(id);
    }
}

@openzeppelin/contracts/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 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 to signal 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. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    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/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

@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/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.1.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 EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * 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;
    }
}

contracts/MgtWalletRegistry.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IMgtMigrationManager {
    function paused() external view returns (bool);
    function reservedMgt() external view returns (uint256);
    function mgt() external view returns (address);
}
/// @notice Address registry for regular-wallet custody. Does not hold or move tokens.
/// @dev Local review candidate. Delay is selected at deployment, not a finalized production policy.
contract MgtWalletRegistry is Ownable2Step {
    IERC20 public immutable mgt;
    IMgtMigrationManager public immutable payoutManager;
    uint64 public immutable migrationDelay;
    address public treasury;
    address public custody;
    uint256 public migrationNonce;
    struct Migration {
        address treasury;
        address custody;
        uint64 eligibleAt;
        bool treasuryAccepted;
        bool custodyAccepted;
        bytes32 reasonHash;
    }
    Migration public pending;
    error InvalidConfiguration();
    error MigrationBlocked();
    error AcceptanceRequired();
    event MigrationProposed(uint256 indexed nonce,address treasury,address custody,uint64 eligibleAt,bytes32 reasonHash);
    event WalletAccepted(uint256 indexed nonce,address indexed wallet,bool treasuryRole);
    event MigrationCancelled(uint256 indexed nonce);
    event WalletsChanged(uint256 indexed nonce,address oldTreasury,address oldCustody,address treasury,address custody,bytes32 reconciliationHash);

    constructor(address token,address manager,address governance,address initialTreasury,address initialCustody,uint64 delaySeconds)
        Ownable(governance) {
        if(token.code.length==0||manager.code.length==0||delaySeconds==0)revert InvalidConfiguration();
        mgt=IERC20(token);payoutManager=IMgtMigrationManager(manager);migrationDelay=delaySeconds;
        if(payoutManager.mgt()!=token)revert InvalidConfiguration();
        _checkWallets(initialTreasury,initialCustody);
        treasury=initialTreasury;custody=initialCustody;
    }
    function _checkWallets(address t,address c) private view {
        if(t==address(0)||c==address(0)||t==c||t==address(this)||c==address(this)||
           t==address(mgt)||c==address(mgt)||t==address(payoutManager)||c==address(payoutManager))revert InvalidConfiguration();
    }
    function migrationPending() external view returns(bool){return pending.eligibleAt!=0;}
    function proposeWallets(address t,address c,bytes32 reasonHash) external onlyOwner {
        _checkWallets(t,c);
        if(!payoutManager.paused()||pending.eligibleAt!=0||reasonHash==bytes32(0)||(t==treasury&&c==custody))revert MigrationBlocked();
        migrationNonce++;
        uint64 eligible=uint64(block.timestamp)+migrationDelay;
        pending=Migration(t,c,eligible,t==treasury,c==custody,reasonHash);
        emit MigrationProposed(migrationNonce,t,c,eligible,reasonHash);
    }
    function acceptWallet(uint256 nonce,bool treasuryRole) external {
        if(nonce!=migrationNonce||pending.eligibleAt==0)revert MigrationBlocked();
        if(msg.sender!=(treasuryRole?pending.treasury:pending.custody))revert AcceptanceRequired();
        if(treasuryRole)pending.treasuryAccepted=true;else pending.custodyAccepted=true;
        emit WalletAccepted(nonce,msg.sender,treasuryRole);
    }
    function cancelMigration() external onlyOwner {
        if(pending.eligibleAt==0)revert MigrationBlocked();
        delete pending;emit MigrationCancelled(migrationNonce);
    }
    /// @dev Old wallet holders transfer balances themselves while payouts are paused.
    ///      Hash attests off-chain reconciliation; it is not an on-chain proof of ledger liabilities.
    function finalizeWallets(uint256 nonce,bytes32 reconciliationHash) external onlyOwner {
        Migration memory p=pending;
        if(nonce!=migrationNonce||p.eligibleAt==0||block.timestamp<p.eligibleAt||
           !payoutManager.paused()||payoutManager.reservedMgt()!=0||reconciliationHash==bytes32(0))revert MigrationBlocked();
        if(!p.treasuryAccepted||!p.custodyAccepted)revert AcceptanceRequired();
        if((p.treasury!=treasury&&mgt.balanceOf(treasury)!=0)||(p.custody!=custody&&mgt.balanceOf(custody)!=0))revert MigrationBlocked();
        address oldT=treasury;address oldC=custody;
        treasury=p.treasury;custody=p.custody;delete pending;
        emit WalletsChanged(nonce,oldT,oldC,treasury,custody,reconciliationHash);
    }
    function renounceOwnership() public view override onlyOwner {revert MigrationBlocked();}
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.