Перейти к содержимому
Проверенный контрактЧастичноеBUSL-1.1

InheritfiV1GRT

Адрес0xfaabbbd1628962c579b3c4e8e2ee5359874380a2
Баланс

0 ETH

 

Транзакций

2

 

Компилятор

solc 0.8.38

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.38+commit.1835d247
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
osaka
Через IR
да
Лицензия
BUSL-1.1
Совпадение
Частичноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 387 893
Транзакция создания
0x48cc0d0417…7f8b9809ec
Библиотеки
src/InheritfiV1GRT.sol:InheritfiV1GovernanceLib0x0601…21935csrc/InheritfiV1GRT.sol:InheritfiV1InheritanceLib0xc94e…d21386

src/InheritfiV1GRT.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 INHERITFI ( https://inheritfi.com / inheritfi.eth ). All rights reserved.
pragma solidity 0.8.38;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./InheritfiV1Base.sol";

/**
 * @title INHERITFI V1 GRT
 * @notice Wraps GRT into iGRT with inheritance and recovery mechanics.
 * @author INHERITFI ( https://inheritfi.com / inheritfi.eth )
 */
contract InheritfiV1GRT is InheritfiV1Base {

    using SafeERC20 for IERC20;

    IERC20 public immutable GRT;

    constructor(address _grt) ERC20("INHERITFI V1 GRT", "iGRT") Ownable(msg.sender) {
        require(_grt != address(0), "Bad GRT addr");
        GRT = IERC20(_grt);
        _initBase();
    }

    // ============ Wrap / Unwrap ============

    function wrap(uint256 amount) external nonReentrant {
        require(amount > 0, "Zero amount");
        GRT.safeTransferFrom(msg.sender, address(this), amount);
        (uint256 tax, uint256 net) = _taxSplit(amount, wrappingTax);
        if (tax > 0) accumulatedTax += tax;
        UserData storage user = userData[msg.sender];
        user.totalReceived    += net;
        _touch();
        if (tax > 0) _mint(address(this), tax);
        _mint(msg.sender, net);
        emit Wrapped(msg.sender, amount, net, tax);
    }

    function unwrap(uint256 amount) external nonReentrant {
        require(amount > 0, "Zero amount");
        require(balanceOf(msg.sender) >= amount, "Insufficient balance");
        bool isTreasury = _isTreasuryWallet(msg.sender);
        uint256 tax;
        uint256 net = amount;
        if (!isTreasury) {
            (tax, net) = _taxSplit(amount, unwrappingTax);
            accumulatedTax += tax;
            if (tax > 0) _transfer(msg.sender, address(this), tax);
        }
        UserData storage user = userData[msg.sender];
        user.totalSent        += amount;
        _touch();
        _burn(msg.sender, net);
        GRT.safeTransfer(msg.sender, net);
        emit Unwrapped(msg.sender, amount, net, tax);
    }

    // ============ Emergency GRT Recovery ============

    function _underlyingAsset() internal view override returns (address) {
        return address(GRT);
    }

    function getRecoverableGRT() public view returns (uint256) {
        uint256 bal = GRT.balanceOf(address(this));
        uint256 sup = totalSupply();
        return bal > sup ? bal - sup : 0;
    }

    function emergencyRecoverGRT(address to, uint256 amount) external onlyOwnerAlive {
        require(to != address(0) && amount > 0, "Bad input");
        require(amount <= getRecoverableGRT(), "Exceeds recoverable");
        GRT.safeTransfer(to, amount);
        emit EmergencyRecovery(address(GRT), to, amount, "GRT-EXCESS");
    }

    function emergencyRecoverERC20(address tokenContract, address to, uint256 amount) external onlyOwnerAlive {
        require(to != address(0) && tokenContract != address(0), "Bad addr");
        require(tokenContract != address(GRT), "Use emergencyRecoverGRT");
        require(amount > 0, "Zero amount");
        if (tokenContract == address(this)) {
            require(amount <= getRecoverableITokens(), "Exceeds recoverable");
            _transfer(address(this), to, amount);
            emit EmergencyRecovery(tokenContract, to, amount, "iGRT-EXCESS");
        } else {
            IERC20 token = IERC20(tokenContract);
            require(token.balanceOf(address(this)) >= amount, "Insufficient balance");
            token.safeTransfer(to, amount);
            emit EmergencyRecovery(tokenContract, to, amount, "ERC20");
        }
    }

    function emergencyRecoverETH(address payable to, uint256 amount) external onlyOwnerAlive {
        require(to != address(0) && amount > 0 && address(this).balance >= amount, "Bad input");
        (bool ok,) = to.call{value: amount}("");
        require(ok, "Transfer failed");
        emit EmergencyRecovery(address(0), to, amount, "ETH");
    }
}

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

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

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

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

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

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

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

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

pragma solidity >=0.4.16;

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

lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
    function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
        bytes4 selector = IERC20Metadata.decimals.selector;
        assembly ("memory-safe") {
            mstore(0x00, selector)
            success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
            success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
            decimals := mul(success, mload(0x00))
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to approve
     * @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

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

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

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

/**
 * @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].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // 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;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/InheritfiV1Base.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 INHERITFI ( https://inheritfi.com / inheritfi.eth ). All rights reserved.
pragma solidity 0.8.38;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

import "./InheritfiV1Types.sol";
import "./InheritfiV1InheritanceLib.sol";
import "./InheritfiV1GovernanceLib.sol";

/**
 * @title INHERITFI V1 Base
 * @notice Abstract base with all shared logic for INHERITFI V1 contracts.
 * @author INHERITFI ( https://inheritfi.com / inheritfi.eth )
 *
 * Heavy logic is extracted into InheritfiV1InheritanceLib and InheritfiV1GovernanceLib (external
 * libraries called via DELEGATECALL) to keep deployed bytecode below the
 * EIP-170 / EIP-3860 limits.
 */
abstract contract InheritfiV1Base is ERC20, Ownable2Step, ReentrancyGuard {

    // ============ Constants ============

    uint256 internal constant BP           = 10_000;
    uint256 internal constant MAX_TAX      = 30;
    uint256 private  constant MIN_P        = 3 days;
    uint256 private  constant MAX_P        = 90 days;
    uint256 private  constant MAX_INAC     = 180 days;
    uint256 private  constant MIN_REC_INAC = 14 days;
    uint256 private  constant MIN_INH_INAC = 21 days;
    uint256 private  constant MIN_REC_P    = 2 days;
    uint256 private  constant MIN_REX_P    = 7 days;
    uint256 private  constant MIN_CREC_P   = 3 days;
    uint256 private  constant MIN_TAX_P    = 3 days;
    uint256 private  constant MIN_RNO_P    = 90 days;
    uint256 private  constant MAX_RNO_P    = 180 days;
    uint256 private  constant MIN_Q_P      = 90 days;
    uint256 private  constant MAX_Q_P      = 180 days;
    uint256 private  constant MIN_QR_P     = 30 days;
    uint256 private  constant MAX_QR_P     = 180 days;
    uint256 private  constant MIN_DI_P     = 7 days;
    uint256 private  constant MAX_DI_P     = 90 days;
    uint256 private  constant MIN_OI_P     = 7 days;
    uint256 private  constant MAX_OI_P     = 90 days;

    // ============ Tax State ============

    uint256 public wrappingTax;
    uint256 public unwrappingTax;
    uint256 public inheritanceTax;
    uint256 public recoveryTax;

    // ============ Time Period State ============

    uint256 public recoveryInactivityPeriod         = 30 days;
    uint256 public inheritInactivityPeriod          = 45 days;
    uint256 public inheritWaitingTime               = 7  days;
    uint256 public inheritRemainingWaitingTime      = 14 days;
    uint256 public recoveryWaitingTime              = 7  days;
    uint256 public recoveryExecutionWindow          = 30 days;
    uint256 public contractRecoveryStartWaitingTime = 30 days;
    uint256 public contractRecoveryWaitingTime      = 30 days;
    uint256 public taxCollectionWaitingTime         = 7  days;
    uint256 public renounceOwnershipWaitingTime     = 90 days;
    uint256 public quorumInactivityPeriod           = 90 days;
    uint256 public quorumRollcallWindow             = 90 days;
    uint256 public delegateInvitationWindow         = 30 days;
    uint256 public ownerInvitationWindow            = 30 days;

    // ============ Limit State ============

    uint256 public maxHeirs         = 30;
    uint256 public maxRecoveryUsers = 15;
    uint256 public maxTreasuries    = 25;
    uint256 public maxDelegates     = 20;

    // ============ Treasury State ============

    Treasury[] public treasuries;
    mapping(address => bool) internal treasuryWallet;
    uint256 public treasuryTimestamp;
    uint256 public accumulatedTax;

    // ============ Delegate / Election State ============

    mapping(address => Delegate) public delegates;
    address[] public delegateList;

    mapping(address => OwnerCandidateRecord) public ownerCandidates;
    address[] public ownerCandidateList;
    mapping(address => bool) public pendingNomination;
    address[] public pendingNominationList;
    bool    public ownerElected;
    address public ownerElect;

    bool    public startContractRecovery;
    uint256 public startContractRecoveryTimestamp;

    bool    public startRenounceOwnership;
    uint256 public startRenounceOwnershipTimestamp;

    uint256 public lastOwnerActivityTimestamp;
    uint256 public ownerInvitationTimestamp;
    uint256 public ownershipEpoch;

    // ============ Owner-Election Lack-of-Quorum State ============
    // Rescue path when too few delegates remain to reach ELEC_THRESH (51).
    // See InheritfiV1GovernanceLib.
    bool    public quorumCallActive;
    uint256 public quorumCallTimestamp;
    address public quorumCallInitiator;
    mapping(address => bool) public presentConfirmed;
    address[] public presentList;

    // ============ User Data ============

    mapping(address => UserData) internal userData;

    // ============ Events ============

    event Wrapped(address indexed user, uint256 inAmt, uint256 outAmt, uint256 tax);
    event Unwrapped(address indexed user, uint256 inAmt, uint256 outAmt, uint256 tax);
    event HeirsUpdated(address indexed testator, uint256 count);
    event RecoveryUsersUpdated(address indexed testator, uint256 count);
    event InheritanceStarted(address indexed testator, address indexed initiator, uint256 ts);
    event InheritanceExecuted(address indexed testator, address indexed heir, uint256 amount, uint256 tax);
    event InheritanceRemainingExecuted(address indexed testator, address indexed heir, uint256 amount, uint256 tax);
    event RecoveryStarted(address indexed testator, address indexed initiator, uint256 ts);
    event RecoveryExecuted(address indexed testator, address indexed ru, uint256 amount, uint256 tax);
    event ActivityChecked(address indexed user, uint256 ts);
    event TaxRateUpdated(string name, uint256 oldRate, uint256 newRate);
    event TreasuryUpdated(uint256 ts);
    event TaxCollected(uint256 amount, uint256 ts);
    event DelegateAdded(address indexed d, uint256 wv, uint256 ts);
    event DelegateRemoved(address indexed d, uint256 ts);
    event DelegateAccepted(address indexed d, uint256 ts);
    event DelegateWeightUpdated(address indexed d, uint256 oldW, uint256 newW);
    event OwnerCandidateNominated(address indexed c, address indexed n, uint256 ts);
    event OwnerCandidateAccepted(address indexed c, uint256 ts);
    event OwnerCandidateVoted(address indexed c, address indexed v, uint256 votes, uint256 total);
    event OwnerCandidateCancelled(address indexed c, address indexed n, uint256 ts);
    event OwnerElectChosen(address indexed elect, uint256 votes, uint256 ts);
    event ContractRecoveryStarted(address indexed initiator, uint256 ts);
    event ContractRecoveryExecuted(address indexed newOwner, uint256 ts);
    event OwnerActivityChecked(uint256 ts);
    event QuorumCallInitiated(address indexed initiator, uint256 ts);
    event PresentConfirmed(address indexed delegate, uint256 ts);
    event QuorumCallCancelled(uint256 ts);
    event OwnerQuorateExecuted(uint256 presentCount, uint256 ts);
    event EmergencySingleOwnerElect(address indexed newOwner, uint256 ts);
    event TreasuryPendingChange(address indexed t, address indexed newW);
    event TreasuryChangeAccepted(address indexed old, address indexed newW);
    event TreasuryChangeCancelled(address indexed t);
    event MaxHeirsUpdated(uint256 old, uint256 nv);
    event MaxRecoveryUsersUpdated(uint256 old, uint256 nv);
    event MaxTreasuriesUpdated(uint256 old, uint256 nv);
    event MaxDelegatesUpdated(uint256 old, uint256 nv);
    event RecoveryInactivityPeriodUpdated(uint256 old, uint256 nv);
    event InheritInactivityPeriodUpdated(uint256 old, uint256 nv);
    event QuorumInactivityPeriodUpdated(uint256 old, uint256 nv);
    event QuorumRollcallWindowUpdated(uint256 old, uint256 nv);
    event DelegateInvitationWindowUpdated(uint256 old, uint256 nv);
    event OwnerInvitationWindowUpdated(uint256 old, uint256 nv);
    event InheritWaitingTimeUpdated(uint256 old, uint256 nv);
    event InheritRemainingWaitingTimeUpdated(uint256 old, uint256 nv);
    event RecoveryWaitingTimeUpdated(uint256 old, uint256 nv);
    event RecoveryExecutionWindowUpdated(uint256 old, uint256 nv);
    event ContractRecoveryStartWaitingTimeUpdated(uint256 old, uint256 nv);
    event ContractRecoveryWaitingTimeUpdated(uint256 old, uint256 nv);
    event TaxCollectionWaitingTimeUpdated(uint256 old, uint256 nv);
    event RenounceOwnershipWaitingTimeUpdated(uint256 old, uint256 nv);
    event RenounceOwnershipStarted(uint256 ts, uint256 executableAt);
    event RenounceOwnershipCancelled(uint256 ts);
    event EmergencyRecovery(address indexed token, address indexed to, uint256 amount, string tokenType);

    // ============ Modifiers ============

    modifier onlyTestator() {
        require(userData[msg.sender].activityTimestamp > 0 || balanceOf(msg.sender) > 0, "Not testator");
        _;
    }

    modifier onlyHeir(address testator) {
        require(userData[testator].heirIndex[msg.sender] > 0, "Not heir");
        _;
    }

    modifier onlyRecoveryUser(address testator) {
        require(userData[testator].isRecoveryUser[msg.sender], "Not recovery user");
        _;
    }

    modifier onlyDelegate() {
        require(delegates[msg.sender].isActive, "Not delegate");
        _;
    }

    modifier onlyTreasuryOrOwner() {
        require(_isTreasuryWallet(msg.sender) || msg.sender == owner(), "Not authorized");
        _;
    }

    /**
     * @notice onlyOwner plus proof of life: records the call as owner
     *         activity and disarms any delegate-initiated process.
     * @dev Replaces onlyOwner on every owner-gated function. See _ownerAlive().
     */
    modifier onlyOwnerAlive() {
        _checkOwner();
        _ownerAlive();
        _;
    }

    // ============ Internal Helpers ============

    function _isTreasuryWallet(address account) internal view returns (bool) {
        return treasuryWallet[account];
    }

    function _initBase() internal {
        wrappingTax    = 30;
        unwrappingTax  = 30;
        inheritanceTax = 30;
        recoveryTax    = 30;
        treasuryTimestamp  = block.timestamp;
        lastOwnerActivityTimestamp = block.timestamp;
    }

    function _taxSplit(uint256 amount, uint256 rate) internal pure returns (uint256 tax, uint256 net) {
        tax = (amount * rate) / BP;
        net = amount - tax;
    }

    /**
     * @dev Proof of life for msg.sender: refreshes the inactivity clock and,
     *      if an inheritance or recovery process is armed, disarms it via
     *      InheritfiV1InheritanceLib.checkActivity (DELEGATECALL keeps
     *      msg.sender). Deliberately parameterless: it can only ever act on
     *      the account that signed the transaction.
     */
    function _touch() internal {
        UserData storage d = userData[msg.sender];
        if (d.startInheritance || d.startRecovery) InheritfiV1InheritanceLib.checkActivity(userData);
        else d.activityTimestamp = block.timestamp;
    }

    // ============ ERC20 Overrides ============

    function transfer(address to, uint256 amount) public override returns (bool) {
        super.transfer(to, amount);
        userData[msg.sender].totalSent         += amount;
        _touch();
        userData[to].totalReceived += amount;
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
        require(amount > 0 || msg.sender == from || allowance(from, msg.sender) > 0, "Not authorized");
        super.transferFrom(from, to, amount);
        userData[from].totalSent         += amount;
        if (msg.sender == from) _touch();
        userData[to].totalReceived += amount;
        return true;
    }

    // ============ Heir Management - delegates to InheritfiV1InheritanceLib ============

    function setHeirs(address[] memory wallets, uint256[] memory percentages) external onlyTestator {
        InheritfiV1InheritanceLib.setHeirs(
            userData,
            wallets,
            percentages,
            maxHeirs
        );
    }

    function getHeirs(address testator) external view returns (address[] memory wallets, uint256[] memory pcts) {
        UserData storage user = userData[testator];
        uint256 n = user.heirs.length;
        wallets = new address[](n);
        pcts    = new uint256[](n);
        for (uint256 i; i < n; i++) {
            wallets[i] = user.heirs[i].wallet;
            pcts[i]    = user.heirs[i].percentage;
        }
    }

    // ============ Recovery User Management - delegates to InheritfiV1InheritanceLib ============

    function setRecoveryUsers(address[] calldata wallets) external onlyTestator {
        InheritfiV1InheritanceLib.setRecoveryUsers(userData, wallets, maxRecoveryUsers);
    }

    function getRecoveryUsers(address testator) external view returns (address[] memory) {
        return userData[testator].recoveryUsers;
    }

    // ============ Inheritance Process - delegates to InheritfiV1InheritanceLib ============

    function startInheritance(address testator) external onlyHeir(testator) {
        InheritfiV1InheritanceLib.startInheritance(
            userData,
            testator,
            msg.sender,
            balanceOf(testator),
            inheritInactivityPeriod,
            recoveryExecutionWindow
        );
        _touch();
    }

    function executeInheritance(address testator) external onlyHeir(testator) nonReentrant {
        (uint256 tax, uint256 net) = InheritfiV1InheritanceLib.executeInheritance(
            userData,
            testator,
            msg.sender,
            balanceOf(testator),
            inheritWaitingTime,
            inheritanceTax
        );
        accumulatedTax += tax;
        if (tax > 0) _transfer(testator, address(this), tax);
        _transfer(testator, msg.sender, net);
        _touch();
    }

    function executeInheritanceRemaining(address testator) external onlyHeir(testator) nonReentrant {
        (
            address[] memory recipients,
            uint256[] memory taxes,
            uint256[] memory nets
        ) = InheritfiV1InheritanceLib.executeInheritanceRemaining(
            userData,
            testator,
            balanceOf(testator),
            inheritWaitingTime,
            inheritRemainingWaitingTime,
            inheritanceTax
        );
        uint256 n = recipients.length;
        for (uint256 i; i < n; i++) {
            if (recipients[i] != address(0) && nets[i] > 0) {
                accumulatedTax += taxes[i];
                if (taxes[i] > 0) _transfer(testator, address(this), taxes[i]);
                _transfer(testator, recipients[i], nets[i]);
            }
        }
        _touch();
    }

    // ============ Recovery Process - delegates to InheritfiV1InheritanceLib ============

    function startRecovery(address testator) external onlyRecoveryUser(testator) {
        InheritfiV1InheritanceLib.startRecovery(
            userData,
            testator,
            msg.sender,
            recoveryInactivityPeriod
        );
        _touch();
    }

    function executeRecovery(address testator) external onlyRecoveryUser(testator) nonReentrant {
        (uint256 tax, uint256 net) = InheritfiV1InheritanceLib.executeRecovery(
            userData,
            testator,
            msg.sender,
            balanceOf(testator),
            recoveryWaitingTime,
            recoveryTax
        );
        accumulatedTax += tax;
        if (tax > 0) _transfer(testator, address(this), tax);
        _transfer(testator, msg.sender, net);
        _touch();
    }

    // ============ Activity Check - delegates to InheritfiV1InheritanceLib ============

    function checkActivity() external onlyTestator {
        InheritfiV1InheritanceLib.checkActivity(userData);
    }

    // ============ View Functions ============

    function getUserInfo(address user) external view returns (
        uint256 totalReceived, uint256 totalSent, uint256 totalRecoveryRelease,
        uint256 totalInheritanceRelease, uint256 totalInheritanceRemainingRelease,
        uint256 activityTimestamp, uint256 heirCount, uint256 recoveryUserCount,
        bool inheritanceStarted, uint256 inheritanceStartTimestamp,
        bool recoveryStarted, uint256 recoveryStartTimestamp,
        bool inheritanceClaimsClosed
    ) {
        UserData storage d = userData[user];
        return (
            d.totalReceived, d.totalSent, d.totalRecoveryRelease,
            d.totalInheritanceRelease, d.totalInheritanceRemainingRelease,
            d.activityTimestamp, d.heirs.length, d.recoveryUsers.length,
            d.startInheritance, d.startInheritanceTimestamp,
            d.startRecovery,    d.startRecoveryTimestamp,
            d.inheritanceClaimsClosed
        );
    }

    function isUserInactive(address testator) external view returns (bool) {
        return block.timestamp >= userData[testator].activityTimestamp + inheritInactivityPeriod;
    }

    function getHeirInheritanceInfo(address testator, address heir) external view returns (
        uint256 percentage, uint256 released, bool hasReceived, uint256 potential, uint256 potentialRemaining
    ) {
        UserData storage user = userData[testator];
        uint256 idx = user.heirIndex[heir];
        require(idx > 0, "Not heir");
        Heir storage h = user.heirs[idx - 1];
        (potential, potentialRemaining) = InheritfiV1InheritanceLib.heirPotentials(
            userData, testator, heir, balanceOf(testator),
            inheritWaitingTime, inheritRemainingWaitingTime, inheritanceTax
        );
        return (
            h.percentage,
            h.inheritanceReleased,
            user.heirReceivedInheritance[heir],
            potential,
            potentialRemaining
        );
    }

    function getRecoveryUserInfo(address testator, address ru) external view returns (
        bool isAuthorized, bool recoveryStarted, uint256 recoveryStartTimestamp,
        bool inactivityElapsed, uint256 currentBalance
    ) {
        UserData storage user = userData[testator];
        return (
            user.isRecoveryUser[ru],
            user.startRecovery,
            user.startRecoveryTimestamp,
            block.timestamp >= user.activityTimestamp + recoveryInactivityPeriod,
            balanceOf(testator)
        );
    }

    // ============ Period & Limit Setters ============

    function setRecoveryInactivityPeriod(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_REC_INAC && p <= MAX_INAC, "Bad period");
        require(p < inheritInactivityPeriod, "Must be < inherit");
        emit RecoveryInactivityPeriodUpdated(recoveryInactivityPeriod, p);
        recoveryInactivityPeriod = p;
    }
    function setInheritInactivityPeriod(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_INH_INAC && p <= MAX_INAC, "Bad period");
        require(p > recoveryInactivityPeriod, "Must be > recovery");
        emit InheritInactivityPeriodUpdated(inheritInactivityPeriod, p);
        inheritInactivityPeriod = p;
    }
    function setInheritWaitingTime(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_P && p <= MAX_P, "Bad period");
        emit InheritWaitingTimeUpdated(inheritWaitingTime, p);
        inheritWaitingTime = p;
    }
    function setInheritRemainingWaitingTime(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_P && p <= MAX_P, "Bad period");
        emit InheritRemainingWaitingTimeUpdated(inheritRemainingWaitingTime, p);
        inheritRemainingWaitingTime = p;
    }
    function setRecoveryWaitingTime(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_REC_P && p <= MAX_P, "Bad period");
        require(p + MIN_P <= recoveryExecutionWindow, "Must be < window");
        emit RecoveryWaitingTimeUpdated(recoveryWaitingTime, p);
        recoveryWaitingTime = p;
    }
    function setRecoveryExecutionWindow(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_REX_P && p <= MAX_P, "Bad period");
        require(p >= recoveryWaitingTime + MIN_P, "Must be > waiting");
        emit RecoveryExecutionWindowUpdated(recoveryExecutionWindow, p);
        recoveryExecutionWindow = p;
    }
    function setContractRecoveryStartWaitingTime(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_CREC_P && p <= MAX_P, "Bad period");
        emit ContractRecoveryStartWaitingTimeUpdated(contractRecoveryStartWaitingTime, p);
        contractRecoveryStartWaitingTime = p;
    }
    function setContractRecoveryWaitingTime(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_CREC_P && p <= MAX_P, "Bad period");
        emit ContractRecoveryWaitingTimeUpdated(contractRecoveryWaitingTime, p);
        contractRecoveryWaitingTime = p;
    }
    function setTaxCollectionWaitingTime(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_TAX_P && p <= MAX_P, "Bad period");
        emit TaxCollectionWaitingTimeUpdated(taxCollectionWaitingTime, p);
        taxCollectionWaitingTime = p;
    }
    function setRenounceOwnershipWaitingTime(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_RNO_P && p <= MAX_RNO_P, "Bad period");
        emit RenounceOwnershipWaitingTimeUpdated(renounceOwnershipWaitingTime, p);
        renounceOwnershipWaitingTime = p;
    }
    function setQuorumInactivityPeriod(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_Q_P && p <= MAX_Q_P, "Bad period");
        emit QuorumInactivityPeriodUpdated(quorumInactivityPeriod, p);
        quorumInactivityPeriod = p;
    }
    function setQuorumRollcallWindow(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_QR_P && p <= MAX_QR_P, "Bad period");
        emit QuorumRollcallWindowUpdated(quorumRollcallWindow, p);
        quorumRollcallWindow = p;
    }
    function setDelegateInvitationWindow(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_DI_P && p <= MAX_DI_P, "Bad period");
        emit DelegateInvitationWindowUpdated(delegateInvitationWindow, p);
        delegateInvitationWindow = p;
    }
    function setOwnerInvitationWindow(uint256 p) external onlyOwnerAlive {
        require(p >= MIN_OI_P && p <= MAX_OI_P, "Bad period");
        emit OwnerInvitationWindowUpdated(ownerInvitationWindow, p);
        ownerInvitationWindow = p;
    }

    function setMaxHeirs(uint256 v) external onlyOwnerAlive {
        require(v > 0 && v <= 40, "Bad value");
        emit MaxHeirsUpdated(maxHeirs, v); maxHeirs = v;
    }
    function setMaxRecoveryUsers(uint256 v) external onlyOwnerAlive {
        require(v > 0 && v <= 50, "Bad value");
        emit MaxRecoveryUsersUpdated(maxRecoveryUsers, v); maxRecoveryUsers = v;
    }
    function setMaxTreasuries(uint256 v) external onlyOwnerAlive {
        require(v > 0 && v <= 40, "Bad value");
        emit MaxTreasuriesUpdated(maxTreasuries, v); maxTreasuries = v;
    }
    function setMaxDelegates(uint256 v) external onlyOwnerAlive {
        require(v > 0 && v <= 50, "Bad value");
        emit MaxDelegatesUpdated(maxDelegates, v); maxDelegates = v;
    }

    // ============ Tax Setters ============

    function setWrappingTax(uint256 r) external onlyOwnerAlive {
        require(r <= MAX_TAX, "Rate too high");
        emit TaxRateUpdated("wrappingTax", wrappingTax, r); wrappingTax = r;
    }
    function setUnwrappingTax(uint256 r) external onlyOwnerAlive {
        require(r <= MAX_TAX, "Rate too high");
        emit TaxRateUpdated("unwrappingTax", unwrappingTax, r); unwrappingTax = r;
    }
    function setInheritanceTax(uint256 r) external onlyOwnerAlive {
        require(r <= MAX_TAX, "Rate too high");
        emit TaxRateUpdated("inheritanceTax", inheritanceTax, r); inheritanceTax = r;
    }
    function setRecoveryTax(uint256 r) external onlyOwnerAlive {
        require(r <= MAX_TAX, "Rate too high");
        emit TaxRateUpdated("recoveryTax", recoveryTax, r); recoveryTax = r;
    }

    // ============ Treasury Management - delegates to InheritfiV1GovernanceLib ============

    function setTreasuries(address[] calldata wallets, uint256[] calldata percentages) external onlyOwnerAlive {
        treasuryTimestamp = InheritfiV1GovernanceLib.setTreasuries(
            treasuries,
            treasuryWallet,
            wallets,
            percentages,
            maxTreasuries
        );
    }

    function getTreasuries() external view returns (address[] memory wallets, uint256[] memory pcts) {
        uint256 n = treasuries.length;
        wallets = new address[](n);
        pcts    = new uint256[](n);
        for (uint256 i; i < n; i++) {
            wallets[i] = treasuries[i].wallet;
            pcts[i]    = treasuries[i].percentage;
        }
    }

    function proposeTreasuryWalletChange(address newWallet) external {
        InheritfiV1GovernanceLib.proposeTreasuryWalletChange(treasuries, treasuryWallet, newWallet);
    }

    function acceptTreasuryWalletChange() external {
        InheritfiV1GovernanceLib.acceptTreasuryWalletChange(treasuries, treasuryWallet, taxCollectionWaitingTime);
    }

    function cancelTreasuryWalletChange() external {
        InheritfiV1GovernanceLib.cancelTreasuryWalletChange(treasuries);
    }

    // ============ Tax Collection ============

    function collectTax() external onlyTreasuryOrOwner nonReentrant {
        require(block.timestamp >= treasuryTimestamp + taxCollectionWaitingTime, "Too soon");
        require(accumulatedTax > 0, "No tax");
        require(treasuries.length > 0, "No treasuries");
        uint256 total = accumulatedTax;
        accumulatedTax = 0;
        uint256 n = treasuries.length;
        uint256 dist;
        for (uint256 i; i < n; i++) {
            uint256 share = (i == n - 1) ? total - dist : (total * treasuries[i].percentage) / BP;
            dist += share;
            if (share > 0) _transfer(address(this), treasuries[i].wallet, share);
        }
        emit TaxCollected(total, block.timestamp);
    }

    /**
     * @notice iTokens held by this contract beyond accumulatedTax (sent to it by mistake).
     *         The owner can recover them with emergencyRecoverERC20(address(this), to, amount).
     */
    function getRecoverableITokens() public view returns (uint256) {
        return balanceOf(address(this)) - accumulatedTax;
    }

    // ============ Delegate Management - delegates to InheritfiV1GovernanceLib ============

    function addDelegate(address d, uint256 wv) external onlyOwnerAlive {
        InheritfiV1GovernanceLib.addDelegate(
            delegates,
            d, wv,
            owner(),
            maxDelegates,
            delegateList.length,
            delegateInvitationWindow,
            ownershipEpoch
        );
    }

    function acceptDelegate() external {
        InheritfiV1GovernanceLib.acceptDelegate(delegates, ownerCandidates, pendingNomination, delegateList, delegateInvitationWindow, maxDelegates, ownershipEpoch);
    }

    function setDelegateWeight(address d, uint256 newW) external onlyOwnerAlive {
        InheritfiV1GovernanceLib.setDelegateWeight(
            delegates,
            ownerCandidates,
            pendingNomination,
            delegateList,
            d, newW
        );
    }

    function removeDelegate(address d) external onlyOwnerAlive {
        InheritfiV1GovernanceLib.removeDelegate(
            delegates,
            ownerCandidates,
            pendingNomination,
            delegateList,
            d
        );
    }

    function getDelegates() external view returns (address[] memory) { return delegateList; }

    // ============ Owner Election - delegates to InheritfiV1GovernanceLib ============

    function nominateOwnerCandidate(address candidate) external onlyDelegate {
        InheritfiV1GovernanceLib.nominateOwnerCandidate(
            delegates,
            ownerCandidates,
            pendingNomination,
            pendingNominationList,
            candidate,
            ownerElected,
            startContractRecovery,
            lastOwnerActivityTimestamp,
            contractRecoveryStartWaitingTime,
            delegateInvitationWindow,
            ownershipEpoch
        );
    }

    function acceptOwnerCandidacy() external {
        InheritfiV1GovernanceLib.acceptOwnerCandidacy(
            delegates,
            ownerCandidates,
            pendingNomination,
            pendingNominationList,
            ownerCandidateList
        );
    }

    function voteForOwnerCandidate(address candidate) external onlyDelegate {
        bool elected = InheritfiV1GovernanceLib.voteForOwnerCandidate(
            delegates,
            ownerCandidates,
            pendingNomination,
            candidate,
            ownerElected
        );
        if (elected) {
            ownerElect   = candidate;
            ownerElected = true;
            _clearCandidates();
        }
    }

    function cancelOwnerCandidacy(address candidate) external onlyDelegate {
        InheritfiV1GovernanceLib.cancelOwnerCandidacy(
            delegates,
            ownerCandidates,
            pendingNomination,
            pendingNominationList,
            ownerCandidateList,
            delegateList,
            candidate
        );
    }

    function getOwnerCandidates() external view returns (address[] memory) { return ownerCandidateList; }

    // ============ Contract Recovery - delegates to InheritfiV1GovernanceLib ============

    function startContractRecoveryProcess() external onlyDelegate {
        startContractRecoveryTimestamp = InheritfiV1GovernanceLib.startContractRecoveryProcess(
            startContractRecovery,
            ownerElected,
            lastOwnerActivityTimestamp,
            contractRecoveryStartWaitingTime
        );
        startContractRecovery = true;
    }

    function executeContractRecovery() external onlyDelegate {
        address newOwner = InheritfiV1GovernanceLib.executeContractRecovery(
            startContractRecovery,
            ownerElected,
            startContractRecoveryTimestamp,
            contractRecoveryWaitingTime,
            ownerElect
        );
        startContractRecovery = false;
        ownerElected          = false;
        ownerElect            = address(0);
        _clearQuorumCall();
        _transferOwnership(newOwner);
        lastOwnerActivityTimestamp = block.timestamp;
    }

    // ============ Owner-Election Lack-of-Quorum - delegates to InheritfiV1GovernanceLib ============

    function quorumCall() external onlyDelegate {
        InheritfiV1GovernanceLib.initiateOwnerQuorumCall(
            delegates,
            presentConfirmed,
            presentList,
            quorumCallActive,
            ownerElected,
            startContractRecovery,
            lastOwnerActivityTimestamp,
            quorumInactivityPeriod,
            msg.sender
        );
        quorumCallActive    = true;
        quorumCallTimestamp = block.timestamp;
        quorumCallInitiator = msg.sender;
    }

    function present() external onlyDelegate {
        bool allPresent = InheritfiV1GovernanceLib.confirmOwnerPresent(
            delegates,
            presentConfirmed,
            presentList,
            quorumCallActive,
            quorumCallTimestamp,
            quorumRollcallWindow,
            delegateList.length,
            msg.sender
        );
        if (allPresent) _clearQuorumCall();
    }

    /**
     * @notice After the roll-call window closes, transfer ownership to the sole
     *         responder, or drop silent delegates and redistribute their
     *         weightedVoting among those who responded.
     * @dev Every candidacy and vote is reset together with the roster change, so
     *      only candidates nominated by present delegates can take part in the
     *      new election and no candidacy of a removed nominator can stall it.
     */
    function quorate() external onlyDelegate nonReentrant {
        // A normal election may have already succeeded while the quorum call
        // was open; if so, the rescue path must not short-circuit it.
        require(!ownerElected, "Already elected");
        require(block.timestamp >= lastOwnerActivityTimestamp + quorumInactivityPeriod, "Owner active");
        // Reset first: no vote then needs retracting or re-tallying while the
        // roster changes, and _settleSoleSurvivorQuorum() still finds the
        // full delegateList.
        _clearCandidates();
        address soloSurvivor = InheritfiV1GovernanceLib.executeOwnerQuorate(
            delegates,
            ownerCandidates,
            pendingNomination,
            delegateList,
            presentConfirmed,
            presentList,
            quorumCallActive,
            quorumCallTimestamp,
            quorumRollcallWindow,
            msg.sender
        );

        if (soloSurvivor != address(0)) {
            _settleSoleSurvivorQuorum();
            startContractRecovery = false;
            ownerElected          = false;
            ownerElect            = address(0);
            _transferOwnership(soloSurvivor);
            lastOwnerActivityTimestamp = block.timestamp;
        } else {
            _clearQuorumCall();
        }
    }

    /**
     * @notice Live state of an open quorum roll-call.
     * @return active          Whether a roll-call is currently open.
     * @return initiator       Delegate that opened it, or address(0).
     * @return startedAt       When the roll-call was opened.
     * @return closesAt        When the roll-call window closes.
     * @return respondedCount  Delegates that have confirmed presence.
     * @return delegateCount   Active delegates on the roster.
     */
    function getQuorumCallInfo() external view returns (
        bool    active,
        address initiator,
        uint256 startedAt,
        uint256 closesAt,
        uint256 respondedCount,
        uint256 delegateCount
    ) {
        return (
            quorumCallActive,
            quorumCallInitiator,
            quorumCallTimestamp,
            quorumCallActive ? quorumCallTimestamp + quorumRollcallWindow : 0,
            presentList.length,
            delegateList.length
        );
    }

    function getPresentDelegates() external view returns (address[] memory) { return presentList; }

    // ============ Owner Activity Check ============

    function ownerCheck() external onlyOwner {
        _ownerAlive();
        startRenounceOwnership = false;
        emit OwnerActivityChecked(block.timestamp);
    }

    function transferOwnership(address newOwner) public override onlyOwnerAlive {
        require(!delegates[newOwner].isActive, "Is delegate");
        super.transferOwnership(newOwner);
        ownerInvitationTimestamp = block.timestamp;
    }

    function acceptOwnership() public override {
        require(block.timestamp <= ownerInvitationTimestamp + ownerInvitationWindow, "Invite expired");
        require(!delegates[msg.sender].isActive, "Is delegate");
        super.acceptOwnership();
        _ownerAlive();
    }

    function _transferOwnership(address newOwner) internal override {
        super._transferOwnership(newOwner);
        startRenounceOwnership          = false;
        startRenounceOwnershipTimestamp = 0;
        ownershipEpoch++;
    }

    // ============ Renounce Ownership ============

    function startRenounceOwnershipProcess() external onlyOwnerAlive {
        startRenounceOwnership          = true;
        startRenounceOwnershipTimestamp = block.timestamp;
        emit RenounceOwnershipStarted(block.timestamp, block.timestamp + renounceOwnershipWaitingTime);
    }

    /**
     * @notice Aborts an in-flight ownership renunciation.
     * @dev Like every owner action (onlyOwnerAlive), it is also a proof of
     *      life and clears any election, roll-call and nomination in progress.
     */
    function cancelRenounceOwnershipProcess() external onlyOwnerAlive {
        require(startRenounceOwnership, "Not started");
        startRenounceOwnership          = false;
        startRenounceOwnershipTimestamp = 0;
        emit RenounceOwnershipCancelled(block.timestamp);
    }

    function renounceOwnership() public override onlyOwner {
        require(startRenounceOwnership, "Not started");
        require(block.timestamp >= startRenounceOwnershipTimestamp + renounceOwnershipWaitingTime, "Too soon");
        super.renounceOwnership();
    }

    // ============ Emergency Recovery ============

    /// @dev Underlying asset of the wrapper (address(0) for native ETH). The ERC-721 and ERC-1155
    ///      recovery paths can never call it, nor this contract itself.
    function _underlyingAsset() internal view virtual returns (address);

    function emergencyRecoverERC721(address nft, address to, uint256 tokenId) external onlyOwnerAlive {
        require(to != address(0) && nft != address(0) && nft.code.length > 0, "Bad addr");
        require(nft != address(this) && nft != _underlyingAsset(), "Protected asset");
        (bool ok,) = nft.call(abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", address(this), to, tokenId));
        require(ok, "NFT transfer failed");
        emit EmergencyRecovery(nft, to, tokenId, "ERC721");
    }

    function emergencyRecoverERC1155(address token, address to, uint256 tokenId, uint256 amount) external onlyOwnerAlive {
        require(to != address(0) && token != address(0) && token.code.length > 0 && amount > 0, "Bad input");
        require(token != address(this) && token != _underlyingAsset(), "Protected asset");
        (bool ok,) = token.call(abi.encodeWithSignature("safeTransferFrom(address,address,uint256,uint256,bytes)", address(this), to, tokenId, amount, ""));
        require(ok, "ERC1155 transfer failed");
        emit EmergencyRecovery(token, to, amount, "ERC1155");
    }

    function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
        return this.onERC721Received.selector;
    }
    function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns (bytes4) {
        return this.onERC1155Received.selector;
    }
    function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata) external pure returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }

    // ============ Private Election Helpers ============

    function _clearCandidates() internal {
        InheritfiV1GovernanceLib.clearCandidates(
            delegates,
            ownerCandidates,
            pendingNomination,
            pendingNominationList,
            ownerCandidateList,
            delegateList
        );
    }

    /// @dev Wipes every delegate and clears roll-call bookkeeping; used only by
    ///      quorate()'s sole-survivor path.
    function _settleSoleSurvivorQuorum() private {
        InheritfiV1GovernanceLib.settleSoloSurvivorQuorum(
            delegates, delegateList, presentConfirmed, presentList
        );
        quorumCallActive    = false;
        quorumCallTimestamp = 0;
        quorumCallInitiator = address(0);
    }

    function _clearQuorumCall() private {
        InheritfiV1GovernanceLib.clearQuorumCall(presentConfirmed, presentList);
        quorumCallActive    = false;
        quorumCallTimestamp = 0;
        quorumCallInitiator = address(0);
    }

    /**
     * @notice Records owner liveness and disarms every governance process
     *         that only exists because the owner appeared to be gone.
     * @dev Called by the onlyOwnerAlive modifier on every owner-gated
     *      function, so any signed owner action is proof of life. A
     *      process can only have been started after a full inactivity
     *      period, so cancelling it here is never accidental.
     */
    function _ownerAlive() internal {
        lastOwnerActivityTimestamp = block.timestamp;
        startContractRecovery = false;
        ownerElected          = false;
        ownerElect            = address(0);
        _clearCandidates();
        _clearQuorumCall();
    }
}

src/InheritfiV1GovernanceLib.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 INHERITFI ( https://inheritfi.com / inheritfi.eth ). All rights reserved.
pragma solidity 0.8.38;

import "./InheritfiV1Types.sol";

/**
 * @title INHERITFI V1 Governance Lib
 * @notice External library containing delegate management, owner-election, and
 *         treasury management logic extracted from InheritfiV1Base.
 * @author INHERITFI ( https://inheritfi.com / inheritfi.eth )
 *
 * Deployed once; called via DELEGATECALL from InheritfiV1Base, so it operates
 * on the calling contract's storage slots directly.
 */
library InheritfiV1GovernanceLib {

    uint256 internal constant BP           = 10_000;
    uint256 internal constant MAX_WV       = 50;
    uint256 internal constant ELEC_THRESH  = 51;

    // ─── Events ───────────────────────────────────────────────────────────────
    event TreasuryUpdated(uint256 ts);
    event TreasuryPendingChange(address indexed t, address indexed newW);
    event TreasuryChangeAccepted(address indexed old, address indexed newW);
    event TreasuryChangeCancelled(address indexed t);

    event DelegateAdded(address indexed d, uint256 wv, uint256 ts);
    event DelegateRemoved(address indexed d, uint256 ts);
    event DelegateAccepted(address indexed d, uint256 ts);
    event DelegateWeightUpdated(address indexed d, uint256 oldW, uint256 newW);

    event OwnerCandidateNominated(address indexed c, address indexed n, uint256 ts);
    event OwnerCandidateAccepted(address indexed c, uint256 ts);
    event OwnerCandidateVoted(address indexed c, address indexed v, uint256 votes, uint256 total);
    event OwnerCandidateCancelled(address indexed c, address indexed n, uint256 ts);
    event OwnerElectChosen(address indexed elect, uint256 votes, uint256 ts);
    event ContractRecoveryStarted(address indexed initiator, uint256 ts);
    event ContractRecoveryExecuted(address indexed newOwner, uint256 ts);

    event QuorumCallInitiated(address indexed initiator, uint256 ts);
    event PresentConfirmed(address indexed delegate, uint256 ts);
    event QuorumCallCancelled(uint256 ts);
    event OwnerQuorateExecuted(uint256 presentCount, uint256 ts);
    event EmergencySingleOwnerElect(address indexed newOwner, uint256 ts);

    // ─── Treasury ─────────────────────────────────────────────────────────────

    /**
     * @notice Replace the treasury list atomically.
     * @return ts Timestamp of the update.
     */
    function setTreasuries(
        Treasury[] storage treasuries,
        mapping(address => bool) storage treasuryWallet,
        address[] calldata wallets,
        uint256[] calldata percentages,
        uint256 maxTreasuries
    ) external returns (uint256 ts) {
        require(wallets.length == percentages.length && wallets.length > 0, "Bad input");
        require(wallets.length <= maxTreasuries, "Too many");
        uint256 total;
        for (uint256 i; i < wallets.length; i++) {
            require(wallets[i] != address(0) && wallets[i] != address(this), "Bad addr");
            require(percentages[i] > 0 && percentages[i] <= BP, "Bad pct");
            total += percentages[i];
            require(total <= BP, "Overflow");
        }
        require(total == BP, "Total != 100%");
        // `delete` on a storage pointer to a dynamic array is illegal - use pop-loop.
        // Each removed treasury also loses its membership flag.
        uint256 existing = treasuries.length;
        for (uint256 k = existing; k > 0; k--) {
            treasuryWallet[treasuries[k - 1].wallet] = false;
            treasuries.pop();
        }
        for (uint256 i; i < wallets.length; i++) {
            require(!treasuryWallet[wallets[i]], "Dup addr");
            treasuryWallet[wallets[i]] = true;
            treasuries.push(Treasury({
                wallet: wallets[i],
                percentage: percentages[i],
                pendingWallet: address(0),
                pendingSince: 0
            }));
        }
        ts = block.timestamp;
        emit TreasuryUpdated(ts);
    }

    /**
     * @notice Propose a new wallet for the caller's treasury entry.
     */
    function proposeTreasuryWalletChange(Treasury[] storage treasuries, mapping(address => bool) storage treasuryWallet, address newWallet) external {
        require(newWallet != address(0), "Bad addr");
        require(!treasuryWallet[newWallet], "Already treasury");
        for (uint256 i; i < treasuries.length; i++) {
            if (treasuries[i].wallet == msg.sender) {
                treasuries[i].pendingWallet = newWallet;
                treasuries[i].pendingSince  = block.timestamp;
                emit TreasuryPendingChange(msg.sender, newWallet);
                return;
            }
        }
        revert("Not treasury");
    }

    /**
     * @notice Accept a pending treasury wallet change.
     * @dev Only after taxCollectionWaitingTime since the proposal, so the owner
     *      can react to a malicious change before the new wallet receives any
     *      tax. Other treasuries keep collecting meanwhile.
     */
    function acceptTreasuryWalletChange(
        Treasury[] storage treasuries,
        mapping(address => bool) storage treasuryWallet,
        uint256 taxCollectionWaitingTime
    ) external {
        require(!treasuryWallet[msg.sender], "Already treasury");
        for (uint256 i; i < treasuries.length; i++) {
            if (treasuries[i].pendingWallet == msg.sender) {
                require(block.timestamp >= treasuries[i].pendingSince + taxCollectionWaitingTime, "Too soon");
                address old = treasuries[i].wallet;
                treasuryWallet[old]        = false;
                treasuryWallet[msg.sender] = true;
                treasuries[i].wallet        = msg.sender;
                treasuries[i].pendingWallet = address(0);
                treasuries[i].pendingSince  = 0;
                emit TreasuryChangeAccepted(old, msg.sender);
                emit TreasuryUpdated(block.timestamp);
                return;
            }
        }
        revert("No pending change");
    }

    /**
     * @notice Cancel a pending treasury wallet change.
     */
    function cancelTreasuryWalletChange(Treasury[] storage treasuries) external {
        for (uint256 i; i < treasuries.length; i++) {
            if (treasuries[i].wallet == msg.sender && treasuries[i].pendingWallet != address(0)) {
                treasuries[i].pendingWallet = address(0);
                treasuries[i].pendingSince  = 0;
                emit TreasuryChangeCancelled(msg.sender);
                return;
            }
        }
        revert("Nothing to cancel");
    }

    // ─── Delegate Management ──────────────────────────────────────────────────

    /**
     * @notice Offer a delegate role to an address.
     * @dev An invitation can be accepted only within delegateInvitationWindow
     *      and while the owner that issued it (ownershipEpoch) is still the
     *      owner; otherwise it counts as expired everywhere.
     */
    function addDelegate(
        mapping(address => Delegate) storage delegates,
        address d,
        uint256 wv,
        address owner,
        uint256 maxDelegates,
        uint256 delegateListLen,
        uint256 delegateInvitationWindow,
        uint256 ownershipEpoch
    ) external {
        require(d != address(0) && d != owner, "Bad delegate");
        require(!delegates[d].isActive, "Exists");
        require(
            !delegates[d].isPending ||
            block.timestamp > delegates[d].pendingSince + delegateInvitationWindow ||
            delegates[d].inviteEpoch != ownershipEpoch,
            "Invite pending"
        );
        require(delegateListLen < maxDelegates, "Max reached");
        require(wv > 0 && wv <= MAX_WV, "Bad weight");
        delegates[d].isPending      = true;
        delegates[d].pendingSince   = block.timestamp;
        delegates[d].inviteEpoch    = ownershipEpoch;
        delegates[d].weightedVoting = wv;
        emit DelegateAdded(d, wv, block.timestamp);
    }

    /**
     * @notice Accept a pending delegate role and join the active pool.
     *
     * @dev Maintains the invariant that the sum of active delegates'
     *      weightedVoting equals 100 whenever at least two delegates are
     *      active. The rebalance happens here at acceptDelegate(), when a
     *      delegate actually joins the active pool.
     */
    function acceptDelegate(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage delegateList,
        uint256 delegateInvitationWindow,
        uint256 maxDelegates,
        uint256 ownershipEpoch
    ) external {
        require(delegates[msg.sender].isPending, "No pending role");
        require(block.timestamp <= delegates[msg.sender].pendingSince + delegateInvitationWindow, "Invite expired");
        require(delegates[msg.sender].inviteEpoch == ownershipEpoch, "Invite expired");
        require(delegateList.length < maxDelegates, "Max reached");
        uint256 newWv = delegates[msg.sender].weightedVoting;
        if (delegateList.length > 0) {
            // Make room for the newcomer; reverts only on the 1→2 transition
            // when the offered weight isn't exactly 50 (hard math limit).
            _rebalanceExistingToTarget(delegates, ownerCandidates, pendingNomination, delegateList, address(0), 100 - newWv);
        }
        delegates[msg.sender].isPending = false;
        delegates[msg.sender].pendingSince = 0;
        delegates[msg.sender].inviteEpoch = 0;
        delegates[msg.sender].isActive  = true;
        delegateList.push(msg.sender);
        emit DelegateAccepted(msg.sender, block.timestamp);
    }

    /**
     * @notice Update a delegate's voting weight.
     * @dev Only reachable through onlyOwnerAlive, which has already cleared
     *      every candidacy and vote, so no tally needs to follow the change.
     */
    function setDelegateWeight(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage delegateList,
        address d,
        uint256 newW
    ) external {
        require(delegates[d].isActive, "Not active");
        require(newW > 0 && newW <= MAX_WV, "Bad weight");
        uint256 old = delegates[d].weightedVoting;
        if (delegateList.length > 1) {
            // With ≥2 active delegates (this one plus at least one other),
            // every other active delegate absorbs the opposite change,
            // proportionally, so the total stays exactly 100.
            _rebalanceExistingToTarget(delegates, ownerCandidates, pendingNomination, delegateList, d, 100 - newW);
        }
        delegates[d].weightedVoting = newW;
        emit DelegateWeightUpdated(d, old, newW);
    }

    /**
     * @notice Remove a delegate from the roster.
     * @dev Only reachable through onlyOwnerAlive, which has already cleared
     *      every candidacy and vote, so there is no vote to retract.
     */
    function removeDelegate(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage delegateList,
        address d
    ) external {
        require(delegates[d].isActive || delegates[d].isPending, "Not found");
        bool wasActive = delegates[d].isActive;
        delete delegates[d];
        if (wasActive) {
            uint256 n = delegateList.length;
            for (uint256 i; i < n; i++) {
                if (delegateList[i] == d) {
                    delegateList[i] = delegateList[n - 1];
                    delegateList.pop();
                    break;
                }
            }
            if (delegateList.length >= 2) {
                // ≥2 remain: redistribute the removed weight proportionally,
                // capped at MAX_WV. Always feasible (headroom ≥ 100).
                _rebalanceExistingToTarget(delegates, ownerCandidates, pendingNomination, delegateList, address(0), 100);
            }
            // 0 or 1 remain: no total is enforced; any remaining delegate
            // simply keeps whatever weight they already had.
        }
        emit DelegateRemoved(d, block.timestamp);
    }

    // ─── Owner Election ───────────────────────────────────────────────────────

    /**
     * @notice Nominate a candidate for owner election.
     */
    function nominateOwnerCandidate(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage pendingNominationList,
        address candidate,
        bool ownerElected,
        bool startContractRecovery,
        uint256 lastOwnerActivityTimestamp,
        uint256 contractRecoveryStartWaitingTime,
        uint256 delegateInvitationWindow,
        uint256 ownershipEpoch
    ) external {
        require(!ownerElected && !startContractRecovery, "Bad state");
        require(block.timestamp >= lastOwnerActivityTimestamp + contractRecoveryStartWaitingTime, "Owner active");
        require(candidate != address(0), "Bad addr");
        require(
            !delegates[candidate].isActive &&
            (!delegates[candidate].isPending ||
             block.timestamp > delegates[candidate].pendingSince + delegateInvitationWindow ||
             delegates[candidate].inviteEpoch != ownershipEpoch),
            "Is delegate"
        );
        require(!pendingNomination[candidate], "Already nominated");
        require(ownerCandidates[candidate].candidate == address(0), "Active candidate");
        require(delegates[msg.sender].votedFor == address(0), "Already voted");
        pendingNomination[candidate]         = true;
        pendingNominationList.push(candidate);
        delegates[msg.sender].votedFor       = candidate;
        ownerCandidates[candidate].nominator = msg.sender;
        ownerCandidates[candidate].candidate = candidate;
        emit OwnerCandidateNominated(candidate, msg.sender, block.timestamp);
    }

    /**
     * @notice Accept an owner candidacy nomination.
     */
    function acceptOwnerCandidacy(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage pendingNominationList,
        address[] storage ownerCandidateList
    ) external {
        require(pendingNomination[msg.sender], "Not nominated");
        pendingNomination[msg.sender] = false;
        _removePendingNomination(pendingNominationList, msg.sender);
        address nom = ownerCandidates[msg.sender].nominator;
        ownerCandidates[msg.sender].totalVotes = delegates[nom].weightedVoting;
        ownerCandidateList.push(msg.sender);
        emit OwnerCandidateAccepted(msg.sender, block.timestamp);
    }

    /**
     * @notice Vote for an active owner candidate.
     * @return elected  Whether the election threshold was crossed.
     */
    function voteForOwnerCandidate(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address candidate,
        bool ownerElected
    ) external returns (bool elected) {
        require(!ownerElected, "Already elected");
        require(
            ownerCandidates[candidate].candidate == candidate && !pendingNomination[candidate],
            "Not active"
        );
        require(delegates[msg.sender].votedFor == address(0), "Already voted");
        delegates[msg.sender].votedFor          = candidate;
        ownerCandidates[candidate].totalVotes  += delegates[msg.sender].weightedVoting;
        uint256 votes = ownerCandidates[candidate].totalVotes;
        elected = votes >= ELEC_THRESH;
        emit OwnerCandidateVoted(candidate, msg.sender, delegates[msg.sender].weightedVoting, votes);
        if (elected) emit OwnerElectChosen(candidate, votes, block.timestamp);
    }

    /**
     * @notice Cancel an owner candidacy (only the nominator may do so).
     */
    function cancelOwnerCandidacy(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage pendingNominationList,
        address[] storage ownerCandidateList,
        address[] storage delegateList,
        address candidate
    ) external {
        require(ownerCandidates[candidate].nominator == msg.sender, "Not nominator");
        _deleteCandidate(delegates, ownerCandidates, pendingNomination, pendingNominationList, ownerCandidateList, delegateList, candidate);
        emit OwnerCandidateCancelled(candidate, msg.sender, block.timestamp);
    }

    // ─── Contract Recovery ────────────────────────────────────────────────────

    /**
     * @notice Start the contract recovery process.
     * @return ts Timestamp of the start.
     */
    function startContractRecoveryProcess(
        bool startContractRecovery_,
        bool ownerElected,
        uint256 lastOwnerActivityTimestamp,
        uint256 contractRecoveryStartWaitingTime
    ) external returns (uint256 ts) {
        require(!startContractRecovery_ && ownerElected, "Bad state");
        require(block.timestamp >= lastOwnerActivityTimestamp + contractRecoveryStartWaitingTime, "Owner active");
        ts = block.timestamp;
        emit ContractRecoveryStarted(msg.sender, ts);
    }

    /**
     * @notice Execute the contract recovery process.
     * @return newOwner The new owner address.
     */
    function executeContractRecovery(
        bool startContractRecovery_,
        bool ownerElected,
        uint256 startContractRecoveryTimestamp,
        uint256 contractRecoveryWaitingTime,
        address ownerElect
    ) external returns (address newOwner) {
        require(startContractRecovery_ && ownerElected, "Bad state");
        require(block.timestamp >= startContractRecoveryTimestamp + contractRecoveryWaitingTime, "Too soon");
        newOwner = ownerElect;
        emit ContractRecoveryExecuted(newOwner, block.timestamp);
    }

    /**
     * @notice Initiate a quorum call after a period of owner inactivity.
     */
    function initiateOwnerQuorumCall(
        mapping(address => Delegate) storage delegates,
        mapping(address => bool) storage presentConfirmed,
        address[] storage presentList,
        bool quorumCallActive_,
        bool ownerElected,
        bool startContractRecovery_,
        uint256 lastOwnerActivityTimestamp,
        uint256 quorumInactivityPeriod,
        address caller
    ) external {
        require(delegates[caller].isActive, "Not delegate");
        require(!ownerElected && !startContractRecovery_, "Bad state");
        require(!quorumCallActive_, "Already active");
        require(block.timestamp >= lastOwnerActivityTimestamp + quorumInactivityPeriod, "Owner active");
        presentConfirmed[caller] = true;
        presentList.push(caller);
        emit QuorumCallInitiated(caller, block.timestamp);
        emit PresentConfirmed(caller, block.timestamp);
    }

    /**
     * @notice Confirm the caller is still present during a quorum roll-call.
     * @return allPresent  True if every active delegate confirmed → caller
     *                      should cancel the quorum call.
     */
    function confirmOwnerPresent(
        mapping(address => Delegate) storage delegates,
        mapping(address => bool) storage presentConfirmed,
        address[] storage presentList,
        bool quorumCallActive_,
        uint256 quorumCallTimestamp,
        uint256 quorumRollcallWindow,
        uint256 delegateCount,
        address caller
    ) external returns (bool allPresent) {
        require(delegates[caller].isActive, "Not delegate");
        require(quorumCallActive_, "No quorum call");
        require(!presentConfirmed[caller], "Already confirmed");
        require(block.timestamp < quorumCallTimestamp + quorumRollcallWindow, "Roll-call closed");
        presentConfirmed[caller] = true;
        presentList.push(caller);
        emit PresentConfirmed(caller, block.timestamp);
        allPresent = (presentList.length == delegateCount);
        if (allPresent) emit QuorumCallCancelled(block.timestamp);
    }

    /**
     * @notice After the roll-call window closes, resolve the quorum call.
     * @return soloSurvivor  Non-zero only when exactly one delegate responded
     *                        -> caller should transfer ownership to them directly.
     */
    function executeOwnerQuorate(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage delegateList,
        mapping(address => bool) storage presentConfirmed,
        address[] storage presentList,
        bool quorumCallActive_,
        uint256 quorumCallTimestamp,
        uint256 quorumRollcallWindow,
        address caller
    ) external returns (address soloSurvivor) {
        require(delegates[caller].isActive, "Not delegate");
        require(quorumCallActive_, "No quorum call");
        require(block.timestamp >= quorumCallTimestamp + quorumRollcallWindow, "Roll-call still open");
        require(presentConfirmed[caller], "Not present");

        uint256 pCount = presentList.length;

        if (pCount == 1) {
            soloSurvivor = presentList[0];
            emit EmergencySingleOwnerElect(soloSurvivor, block.timestamp);
            return soloSurvivor;
        }

        _redistributeDelegateWV(delegates, ownerCandidates, pendingNomination, delegateList, presentConfirmed);
        emit OwnerQuorateExecuted(pCount, block.timestamp);
    }

    /// @notice Wipe every delegate and clear roll-call bookkeeping.
    /// @dev Used only by the sole-survivor path of quorate()
    function settleSoloSurvivorQuorum(
        mapping(address => Delegate) storage delegates,
        address[] storage delegateList,
        mapping(address => bool) storage presentConfirmed,
        address[] storage presentList
    ) external {
        uint256 n = delegateList.length;
        for (uint256 i; i < n; i++) delete delegates[delegateList[i]];
        for (uint256 i = delegateList.length; i > 0; i--) delegateList.pop();
        uint256 pn = presentList.length;
        for (uint256 i; i < pn; i++) delete presentConfirmed[presentList[i]];
        for (uint256 i = presentList.length; i > 0; i--) presentList.pop();
    }

    /// @notice Clear roll-call bookkeeping after a quorum call ends.
    /// @dev Caller resets the active/timestamp/initiator flags itself since
    ///      those are plain value types.
    function clearQuorumCall(
        mapping(address => bool) storage presentConfirmed,
        address[] storage presentList
    ) external {
        uint256 n = presentList.length;
        for (uint256 i; i < n; i++) delete presentConfirmed[presentList[i]];
        for (uint256 i = presentList.length; i > 0; i--) presentList.pop();
    }

    /**
     * @dev Drops absent delegates and redistributes their weight to the
     *      present ones, capped at MAX_WV. Tolerates leftover (best-effort)
     *      since this runs only in an emergency quorum rescue.
     */
    function _redistributeDelegateWV(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage delegateList,
        mapping(address => bool) storage presentConfirmed
    ) private {
        uint256 absentWV = _removeAbsentDelegates(delegates, delegateList, presentConfirmed);
        _distributeAmong(delegates, ownerCandidates, pendingNomination, delegateList, address(0), absentWV); // leftover tolerated
    }

    /// @dev Sums the WV of every absent delegate and drops it from the roster.
    ///      quorate() clears every candidacy and vote beforehand, so there is
    ///      no vote to retract.
    function _removeAbsentDelegates(
        mapping(address => Delegate) storage delegates,
        address[] storage delegateList,
        mapping(address => bool) storage presentConfirmed
    ) private returns (uint256 absentWV) {
        uint256 dl = delegateList.length;
        for (uint256 i; i < dl; i++) {
            address d = delegateList[i];
            if (!presentConfirmed[d]) {
                absentWV += delegates[d].weightedVoting;
            }
        }
        for (uint256 i; i < delegateList.length; ) {
            if (!presentConfirmed[delegateList[i]]) {
                delete delegates[delegateList[i]];
                delegateList[i] = delegateList[delegateList.length - 1];
                delegateList.pop();
            } else {
                i++;
            }
        }
    }

    /// @dev Grows or shrinks `list` (minus `skip`) to sum exactly `targetTotal`.
    ///      Reverts if growth can't be placed without breaching MAX_WV, or if
    ///      shrinking would leave a delegate below 1 (targetTotal smaller than
    ///      the number of delegates, unreachable while maxDelegates <= 50).
    function _rebalanceExistingToTarget(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage list,
        address skip,
        uint256 targetTotal
    ) private {
        uint256 n = list.length;
        uint256 currentTotal;
        for (uint256 i; i < n; i++) {
            if (list[i] != skip) currentTotal += delegates[list[i]].weightedVoting;
        }
        if (targetTotal >= currentTotal) {
            uint256 leftover = _distributeAmong(delegates, ownerCandidates, pendingNomination, list, skip, targetTotal - currentTotal);
            require(leftover == 0, "Cannot balance to 100");
        } else {
            _scaleDown(delegates, ownerCandidates, pendingNomination, list, skip, targetTotal);
        }
    }

    /// @dev Proportionally scales `list` (minus `skip`) DOWN to `targetTotal`.
    ///      Removes (currentTotal - targetTotal) in proportion to each delegate's
    ///      weight above 1, so every delegate keeps at least 1 and no delegate
    ///      ever grows (so none can exceed MAX_WV). Rounding leftovers are taken
    ///      one unit at a time from delegates that can still give one.
    ///      Keeps each delegate's live vote (if any) in sync with the change.
    function _scaleDown(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage list,
        address skip,
        uint256 targetTotal
    ) private {
        uint256 n = list.length;
        uint256 currentTotal;
        uint256 reducible;
        for (uint256 i; i < n; i++) {
            if (list[i] == skip) continue;
            uint256 w = delegates[list[i]].weightedVoting;
            currentTotal += w;
            reducible += w - 1;
        }
        uint256 toRemove = currentTotal - targetTotal;
        require(toRemove <= reducible, "Cannot balance to 100");

        uint256[] memory newW = new uint256[](n);
        uint256 removed;
        for (uint256 i; i < n; i++) {
            if (list[i] == skip) continue;
            uint256 w = delegates[list[i]].weightedVoting;
            uint256 cut = (toRemove * (w - 1)) / reducible;
            newW[i] = w - cut;
            removed += cut;
        }
        // Rounding leftover: take one unit from each delegate that can still give one.
        for (uint256 i; i < n && removed < toRemove; i++) {
            if (list[i] == skip || newW[i] <= 1) continue;
            newW[i] -= 1;
            removed += 1;
        }
        require(removed == toRemove, "Cannot balance to 100");

        for (uint256 i; i < n; i++) {
            address d = list[i];
            if (d == skip) continue;
            uint256 w = delegates[d].weightedVoting;
            if (newW[i] != w) {
                delegates[d].weightedVoting = newW[i];
                address vf = delegates[d].votedFor;
                if (_isLiveVote(ownerCandidates, pendingNomination, vf)) {
                    ownerCandidates[vf].totalVotes = ownerCandidates[vf].totalVotes - w + newW[i];
                }
            }
        }
    }

    /// @dev Proportionally grows `list` (minus `skip`) by `amount`, never
    ///      pushing anyone past MAX_WV; excludes anyone already at MAX_WV
    ///      from every round. Returns whatever could not be placed (0 when
    ///      the caller's aggregate headroom was sufficient).
    function _distributeAmong(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage list,
        address skip,
        uint256 amount
    ) private returns (uint256 remaining) {
        uint256 n = list.length;
        remaining = amount;
        for (uint256 round; remaining > 0 && round < n; round++) {
            uint256 distributedThisRound = _distributeDelegateRound(delegates, ownerCandidates, pendingNomination, list, skip, n, remaining);
            if (distributedThisRound == 0) break;
            remaining -= distributedThisRound;
        }
    }

    /// @dev One growth round: shares `remaining` among `list` (minus `skip`)
    ///      that are below MAX_WV, proportional to current weight, clamped to
    ///      headroom, keeping any live vote's totalVotes in sync.
    function _distributeDelegateRound(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage list,
        address skip,
        uint256 n,
        uint256 remaining
    ) private returns (uint256 distributedThisRound) {
        uint256 eligibleWV;
        uint256 lastEligibleIdx = type(uint256).max;
        for (uint256 i; i < n; i++) {
            address d = list[i];
            if (d == skip) continue;
            uint256 w = delegates[d].weightedVoting;
            if (w < MAX_WV) { eligibleWV += w; lastEligibleIdx = i; }
        }
        if (eligibleWV == 0) return 0;

        for (uint256 i; i < n; i++) {
            address d = list[i];
            if (d == skip) continue;
            uint256 w = delegates[d].weightedVoting;
            if (w >= MAX_WV) continue;
            uint256 headroom = MAX_WV - w;
            uint256 share = (i == lastEligibleIdx)
                ? remaining - distributedThisRound
                : (remaining * w) / eligibleWV;
            if (share > headroom) share = headroom;
            if (share > 0) {
                delegates[d].weightedVoting = w + share;
                address vf = delegates[d].votedFor;
                if (_isLiveVote(ownerCandidates, pendingNomination, vf)) {
                    ownerCandidates[vf].totalVotes += share;
                }
                distributedThisRound += share;
            }
        }
    }

    // ─── Internal helpers ─────────────────────────────────────────────────────

    /// @dev True when `vf` is an accepted candidate whose tally must follow weight
    ///      changes. Pending nominations are excluded: their totalVotes is set when
    ///      the nominee accepts (acceptOwnerCandidacy).
    function _isLiveVote(
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address vf
    ) private view returns (bool) {
        return vf != address(0) && ownerCandidates[vf].candidate == vf && !pendingNomination[vf];
    }

    /**
     * @dev Removes `candidate` from the pending-nomination list, if present.
     *      Swap-and-pop; order is not significant.
     */
    function _removePendingNomination(
        address[] storage pendingNominationList,
        address candidate
    ) internal {
        uint256 n = pendingNominationList.length;
        for (uint256 i; i < n; i++) {
            if (pendingNominationList[i] == candidate) {
                pendingNominationList[i] = pendingNominationList[n - 1];
                pendingNominationList.pop();
                break;
            }
        }
    }

    /// @dev Removes a candidate and clears every delegate's vote for it.
    function _deleteCandidate(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage pendingNominationList,
        address[] storage ownerCandidateList,
        address[] storage delegateList,
        address candidate
    ) internal {
        uint256 n = delegateList.length;
        for (uint256 i; i < n; i++) {
            if (delegates[delegateList[i]].votedFor == candidate) {
                delegates[delegateList[i]].votedFor = address(0);
            }
        }
        uint256 m = ownerCandidateList.length;
        for (uint256 i; i < m; i++) {
            if (ownerCandidateList[i] == candidate) {
                ownerCandidateList[i] = ownerCandidateList[m - 1];
                ownerCandidateList.pop();
                break;
            }
        }
        delete ownerCandidates[candidate];
        delete pendingNomination[candidate];
        _removePendingNomination(pendingNominationList, candidate);
    }

    /**
     * @notice Clear all owner candidates and reset every delegate's vote.
     */
    function clearCandidates(
        mapping(address => Delegate) storage delegates,
        mapping(address => OwnerCandidateRecord) storage ownerCandidates,
        mapping(address => bool) storage pendingNomination,
        address[] storage pendingNominationList,
        address[] storage ownerCandidateList,
        address[] storage delegateList
    ) external {
        uint256 n = delegateList.length;
        for (uint256 i; i < n; i++) delegates[delegateList[i]].votedFor = address(0);
        uint256 m = ownerCandidateList.length;
        for (uint256 i; i < m; i++) {
            address c = ownerCandidateList[i];
            delete ownerCandidates[c];
            delete pendingNomination[c];
        }
        uint256 q = pendingNominationList.length;
        for (uint256 i; i < q; i++) {
            address pc = pendingNominationList[i];
            delete ownerCandidates[pc];
            delete pendingNomination[pc];
        }
        for (uint256 i = q; i > 0; i--) pendingNominationList.pop();
        // `delete` on a storage pointer to a dynamic array is illegal - use pop-loop.
        uint256 p = ownerCandidateList.length;
        for (uint256 i = p; i > 0; i--) ownerCandidateList.pop();
    }
}

src/InheritfiV1InheritanceLib.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 INHERITFI ( https://inheritfi.com / inheritfi.eth ). All rights reserved.
pragma solidity 0.8.38;

import "./InheritfiV1Types.sol";

/**
 * @title INHERITFI V1 Inheritance Lib
 * @notice External library containing the heavy inheritance and recovery logic
 *         extracted from InheritfiV1Base to reduce deployed contract bytecode size.
 * @author INHERITFI ( https://inheritfi.com / inheritfi.eth )
 *
 * External library functions are deployed once and called via DELEGATECALL,
 * reducing the consuming contract's bytecode below EIP-170 / EIP-3860 limits.
 */
library InheritfiV1InheritanceLib {

    // ─── Shared constants (must mirror InheritfiV1Base) ───────────────────────
    uint256 internal constant BP = 10_000;

    // ─── Events (must match InheritfiV1Base exactly) ──────────────────────────
    event HeirsUpdated(address indexed testator, uint256 count);
    event RecoveryUsersUpdated(address indexed testator, uint256 count);
    event InheritanceStarted(address indexed testator, address indexed initiator, uint256 ts);
    event InheritanceExecuted(address indexed testator, address indexed heir, uint256 amount, uint256 tax);
    event InheritanceRemainingExecuted(address indexed testator, address indexed heir, uint256 amount, uint256 tax);
    event RecoveryStarted(address indexed testator, address indexed initiator, uint256 ts);
    event RecoveryExecuted(address indexed testator, address indexed ru, uint256 amount, uint256 tax);
    event ActivityChecked(address indexed user, uint256 ts);

    // ─── Heir Management ──────────────────────────────────────────────────────

    /**
     * @notice Replace a testator's heir list atomically.
     * @dev Called via DELEGATECALL so `userData` lives in the calling contract's
     *      storage; `msg.sender` is the testator.
     */
    function setHeirs(
        mapping(address => UserData) storage userData,
        address[] memory wallets,
        uint256[] memory percentages,
        uint256 maxHeirs
    ) external {
        require(wallets.length == percentages.length && wallets.length > 0, "Bad input");
        require(wallets.length <= maxHeirs, "Too many heirs");
        UserData storage user = userData[msg.sender];
        require(!user.startInheritance && !user.startRecovery, "Process active");

        // Clear old heirs
        uint256 n = user.heirs.length;
        for (uint256 i; i < n; i++) delete user.heirIndex[user.heirs[i].wallet];
        delete user.heirs;

        uint256 total;
        for (uint256 i; i < wallets.length; i++) {
            address w = wallets[i];
            uint256 p = percentages[i];
            require(w != address(0) && w != msg.sender, "Bad heir");
            require(p > 0 && p <= BP, "Bad pct");
            require(user.heirIndex[w] == 0, "Dup heir");
            total += p;
            require(total <= BP, "Overflow");
            user.heirs.push();
            uint256 idx = user.heirs.length - 1;
            user.heirs[idx].wallet     = w;
            user.heirs[idx].percentage = p;
            user.heirIndex[w]          = idx + 1;
        }
        require(total == BP, "Total != 100%");
        user.activityTimestamp = block.timestamp;
        emit HeirsUpdated(msg.sender, wallets.length);
    }

    // ─── Recovery User Management ─────────────────────────────────────────────

    /**
     * @notice Replace a testator's recovery user list atomically.
     */
    function setRecoveryUsers(
        mapping(address => UserData) storage userData,
        address[] calldata wallets,
        uint256 maxRecoveryUsers
    ) external {
        require(wallets.length > 0 && wallets.length <= maxRecoveryUsers, "Bad count");
        UserData storage user = userData[msg.sender];
        require(!user.startInheritance && !user.startRecovery, "Process active");

        uint256 n = user.recoveryUsers.length;
        for (uint256 i; i < n; i++) delete user.isRecoveryUser[user.recoveryUsers[i]];
        delete user.recoveryUsers;

        for (uint256 i; i < wallets.length; i++) {
            address w = wallets[i];
            require(w != address(0) && w != msg.sender, "Bad addr");
            require(!user.isRecoveryUser[w], "Dup");
            user.recoveryUsers.push(w);
            user.isRecoveryUser[w] = true;
        }
        user.activityTimestamp = block.timestamp;
        emit RecoveryUsersUpdated(msg.sender, wallets.length);
    }

    // ─── Inheritance Process ──────────────────────────────────────────────────

    /**
     * @notice Start the inheritance process for a testator after inactivity.
     */
    function startInheritance(
        mapping(address => UserData) storage userData,
        address testator,
        address initiator,
        uint256 balance,
        uint256 inheritInactivityPeriod,
        uint256 recoveryExecutionWindow
    ) external {
        UserData storage user = userData[testator];
        require(!user.startInheritance, "Process active");
        if (user.startRecovery) {
            require(
                block.timestamp >= user.startRecoveryTimestamp + recoveryExecutionWindow,
                "Process active"
            );
            user.startRecovery          = false;
            user.startRecoveryTimestamp = 0;
        }
        require(block.timestamp >= user.activityTimestamp + inheritInactivityPeriod, "Too soon");
        require(balance > 0, "No balance");
        user.startInheritance          = true;
        user.startInheritanceTimestamp = block.timestamp;
        emit InheritanceStarted(testator, initiator, block.timestamp);
    }

    /**
     * @notice Compute an heir's share and update inheritance state.
     * @return tax   Amount to move to the treasury.
     * @return net   Amount to transfer to the heir.
     *
     * @dev Pays from the current balance: share = balance * pct / pct of heirs
     *      still unclaimed (this heir included). The last heir gets the whole
     *      balance. A zero share is paid and still marks the heir as claimed.
     */
    function executeInheritance(
        mapping(address => UserData) storage userData,
        address testator,
        address heir,
        uint256 testatorBalance,
        uint256 inheritWaitingTime,
        uint256 inheritanceTax
    ) external returns (uint256 tax, uint256 net) {
        UserData storage user = userData[testator];
        require(user.startInheritance, "Not started");
        require(!user.heirReceivedInheritance[heir], "Already claimed");
        require(!user.inheritanceClaimsClosed, "Claims closed");
        require(block.timestamp >= user.startInheritanceTimestamp + inheritWaitingTime, "Too soon");

        Heir storage h = user.heirs[user.heirIndex[heir] - 1];
        // Pro rata over the current balance among heirs who haven't claimed yet
        // (this heir included); the last one gets the whole balance.
        uint256 share = (testatorBalance * h.percentage) / (BP - user.inheritanceClaimedPct);

        tax = (share * inheritanceTax) / BP;
        net = share - tax;

        h.inheritanceReleased              += share;
        user.totalInheritanceRelease       += share;
        user.inheritanceClaimedPct         += h.percentage;
        user.heirReceivedInheritance[heir]  = true;
        user.heirsWhoReceived.push(heir);

        emit InheritanceExecuted(testator, heir, net, tax);
    }

    /**
     * @notice Distribute leftover balance to heirs who already claimed.
     * @dev Returns parallel arrays (recipient, tax, net) for the caller to
     *      execute transfers. Per-heir logic is in _processRemainingShare to
     *      avoid "Stack too deep".
     */
    function executeInheritanceRemaining(
        mapping(address => UserData) storage userData,
        address testator,
        uint256 testatorBalance,
        uint256 inheritWaitingTime,
        uint256 inheritRemainingWaitingTime,
        uint256 inheritanceTax
    ) external returns (
        address[] memory recipients,
        uint256[] memory taxes,
        uint256[] memory nets
    ) {
        UserData storage user = userData[testator];
        require(user.heirReceivedInheritance[msg.sender], "Not claimed yet");
        require(user.startInheritance, "Not started");
        require(
            block.timestamp >= user.startInheritanceTimestamp + inheritWaitingTime + inheritRemainingWaitingTime,
            "Too soon"
        );

        uint256 claimCount = user.heirsWhoReceived.length;
        require(testatorBalance > 0, "No balance");
        user.inheritanceClaimsClosed = true;

        uint256 totalPct;
        for (uint256 i; i < claimCount; i++) {
            totalPct += user.heirs[user.heirIndex[user.heirsWhoReceived[i]] - 1].percentage;
        }

        recipients = new address[](claimCount);
        taxes      = new uint256[](claimCount);
        nets       = new uint256[](claimCount);

        // Delegate per-heir body to avoid "Stack too deep". Same rule as collectTax:
        // shares are proportional and rounded down, and the last heir who claimed also
        // takes the rounding residue, so the testator's balance is fully distributed (B-05).
        uint256 distributed;
        for (uint256 i; i < claimCount; i++) {
            uint256 share = i == claimCount - 1
                ? testatorBalance - distributed
                : (testatorBalance * user.heirs[user.heirIndex[user.heirsWhoReceived[i]] - 1].percentage) / totalPct;
            distributed += share;
            _processRemainingShare(
                user,
                testator,
                i,
                share,
                inheritanceTax,
                recipients,
                taxes,
                nets
            );
        }
    }

    /**
     * @dev Processes one heir's remaining-inheritance share (avoids stack too deep).
     *
     * @param user          Storage pointer to the testator's UserData.
     * @param testator      Address of the testator (used only for the event).
     * @param i             Current loop index.
     * @param share         Gross share computed by the caller (see executeInheritanceRemaining).
     * @param inheritanceTax Tax rate in basis points.
     * @param recipients    Output array: heir addresses.
     * @param taxes         Output array: tax amounts per heir.
     * @param nets          Output array: net amounts per heir.
     *
     * @dev The caller gives the last heir who claimed the rounding residue (B-05),
     *      so the testator's whole balance is distributed and never exceeded.
     */
    function _processRemainingShare(
        UserData storage user,
        address testator,
        uint256 i,
        uint256 share,
        uint256 inheritanceTax,
        address[] memory recipients,
        uint256[] memory taxes,
        uint256[] memory nets
    ) private {
        address ha     = user.heirsWhoReceived[i];
        Heir storage h = user.heirs[user.heirIndex[ha] - 1];

        if (share > 0) {
            uint256 t  = (share * inheritanceTax) / BP;
            uint256 n_ = share - t;
            h.inheritanceReleased                 += share;
            user.totalInheritanceRemainingRelease += share;
            recipients[i] = ha;
            taxes[i]      = t;
            nets[i]       = n_;
            emit InheritanceRemainingExecuted(testator, ha, n_, t);
        }
    }

    /**
     * @notice Net amounts an heir would receive, mirroring the payout logic.
     * @return potential          executeInheritance share, net of tax, computed
     *                            from the current balance exactly as executeInheritance
     *                            does. 0 if already claimed or
     *                            if claims are closed. With no inheritance process
     *                            active, it is the share the heir would get if one
     *                            started now with the current balance.
     * @return potentialRemaining executeInheritanceRemaining share, net of tax.
     *                            0 unless the heir already claimed and the
     *                            remaining window is open.
     */
    function heirPotentials(
        mapping(address => UserData) storage userData,
        address testator,
        address heir,
        uint256 testatorBalance,
        uint256 inheritWaitingTime,
        uint256 inheritRemainingWaitingTime,
        uint256 inheritanceTax
    ) external view returns (uint256 potential, uint256 potentialRemaining) {
        UserData storage user = userData[testator];
        Heir storage h = user.heirs[user.heirIndex[heir] - 1];
        bool received = user.heirReceivedInheritance[heir];

        uint256 gross;
        if (!received && !user.inheritanceClaimsClosed) {
            gross = (testatorBalance * h.percentage) / (BP - user.inheritanceClaimedPct);
        }
        potential = gross - (gross * inheritanceTax) / BP;

        if (
            user.startInheritance && received &&
            block.timestamp >= user.startInheritanceTimestamp + inheritWaitingTime + inheritRemainingWaitingTime
        ) {
            uint256 totalPct;
            uint256 n = user.heirsWhoReceived.length;
            for (uint256 i; i < n; i++) {
                totalPct += user.heirs[user.heirIndex[user.heirsWhoReceived[i]] - 1].percentage;
            }
            uint256 distributed;
            for (uint256 i; i < n; i++) {
                address a = user.heirsWhoReceived[i];
                uint256 s = i == n - 1
                    ? testatorBalance - distributed
                    : (testatorBalance * user.heirs[user.heirIndex[a] - 1].percentage) / totalPct;
                if (a == heir) {
                    potentialRemaining = s - (s * inheritanceTax) / BP;
                    break;
                }
                distributed += s;
            }
        }
    }

    // ─── Recovery Process ─────────────────────────────────────────────────────

    /**
     * @notice Start the recovery process for a testator after inactivity.
     */
    function startRecovery(
        mapping(address => UserData) storage userData,
        address testator,
        address initiator,
        uint256 recoveryInactivityPeriod
    ) external {
        UserData storage user = userData[testator];
        require(!user.startRecovery, "Already started");
        require(block.timestamp >= user.activityTimestamp + recoveryInactivityPeriod, "Too soon");
        // Disarm the inheritance but keep its claim marks: if this recovery is
        // abandoned and the heirs resume it (AUD2-03), heirs who already claimed
        // cannot claim again and the split continues where it stopped.
        user.startInheritance          = false;
        user.startInheritanceTimestamp = 0;
        user.startRecovery          = true;
        user.startRecoveryTimestamp = block.timestamp;
        emit RecoveryStarted(testator, initiator, block.timestamp);
    }

    /**
     * @notice Validate recovery conditions and update state.
     * @return tax  Amount to collect.
     * @return net  Amount to transfer to recovery user.
     */
    function executeRecovery(
        mapping(address => UserData) storage userData,
        address testator,
        address recoveryUser,
        uint256 balance,
        uint256 recoveryWaitingTime,
        uint256 recoveryTax
    ) external returns (uint256 tax, uint256 net) {
        UserData storage user = userData[testator];
        require(user.startRecovery, "Not started");
        require(block.timestamp >= user.startRecoveryTimestamp + recoveryWaitingTime, "Too soon");
        require(balance > 0, "No balance");

        tax = (balance * recoveryTax) / BP;
        net = balance - tax;

        user.totalRecoveryRelease            += balance;
        userData[recoveryUser].totalReceived += net;
        user.startRecovery          = false;
        user.startRecoveryTimestamp = 0;
        // The whole balance left with the recovery: a later inheritance starts afresh.
        _clearInheritance(user);

        emit RecoveryExecuted(testator, recoveryUser, net, tax);
    }

    // ─── Activity Check ───────────────────────────────────────────────────────

    /**
     * @notice Update the caller's activity timestamp and clear any active processes.
     */
    function checkActivity(mapping(address => UserData) storage userData) external {
        UserData storage user = userData[msg.sender];
        user.activityTimestamp = block.timestamp;
        // Claim marks may also survive in a recovery armed over a cancelled inheritance.
        if (user.startInheritance || user.startRecovery) _clearInheritance(user);
        if (user.startRecovery) {
            user.startRecovery          = false;
            user.startRecoveryTimestamp = 0;
        }
        emit ActivityChecked(msg.sender, block.timestamp);
    }

    // ─── Private helpers ──────────────────────────────────────────────────────

    /// @dev Resets all inheritance state for a user.
    function _clearInheritance(UserData storage user) private {
        user.startInheritance          = false;
        user.startInheritanceTimestamp = 0;
        user.inheritanceClaimedPct     = 0;
        user.inheritanceClaimsClosed   = false;
        uint256 n = user.heirsWhoReceived.length;
        for (uint256 i; i < n; i++) delete user.heirReceivedInheritance[user.heirsWhoReceived[i]];
        delete user.heirsWhoReceived;
    }
}

src/InheritfiV1Types.sol

// SPDX-License-Identifier: BUSL-1.1
// Copyright (c) 2026 INHERITFI ( https://inheritfi.com / inheritfi.eth ). All rights reserved.
pragma solidity 0.8.38;

/**
 * @title INHERITFI V1 Types
 * @notice Storage structs shared by InheritfiV1Base, InheritfiV1InheritanceLib and
 *         InheritfiV1GovernanceLib. Defined once so that the contract and the libraries
 *         always agree on the storage layout (audit finding M-12).
 * @author INHERITFI ( https://inheritfi.com / inheritfi.eth )
 */

struct Heir {
    address wallet;
    uint256 percentage;
    uint256 inheritanceReleased;
}

struct UserData {
    uint256 totalReceived;
    uint256 totalSent;
    uint256 totalRecoveryRelease;
    uint256 totalInheritanceRelease;
    uint256 totalInheritanceRemainingRelease;
    uint256 inheritanceClaimedPct;
    uint256 activityTimestamp;
    Heir[]  heirs;
    mapping(address => uint256) heirIndex;
    address[] recoveryUsers;
    mapping(address => bool) isRecoveryUser;
    bool    startInheritance;
    uint256 startInheritanceTimestamp;
    mapping(address => bool) heirReceivedInheritance;
    address[] heirsWhoReceived;
    bool    inheritanceClaimsClosed;
    bool    startRecovery;
    uint256 startRecoveryTimestamp;
}

struct Treasury {
    address wallet;
    uint256 percentage;
    address pendingWallet;
    uint256 pendingSince;
}

struct Delegate {
    bool    isActive;
    bool    isPending;
    uint256 weightedVoting;
    address votedFor;
    uint256 pendingSince;
    uint256 inviteEpoch;
}

struct OwnerCandidateRecord {
    address candidate;
    uint256 totalVotes;
    address nominator;
}
Настройки компилятораПоказать
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {
    "src/InheritfiV1GRT.sol": {
      "InheritfiV1GovernanceLib": "0x0601a3fd01b747edea0d493913b1242bc521935c",
      "InheritfiV1InheritanceLib": "0xc94e2f80fb08b0736972fe7ea224fadea2d21386"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    ":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    ":forge-std/=lib/forge-std/src/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.