Skip to content
Verified contractExactUNLICENSED

TransferEOALegacy

Address0x3f34c84bc6101e4abd0f8cbf65efe9b8956b3a42
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.20

 

Same code

20 more contracts

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,625,416
Creation transaction
0xfb7519f578…d67a886634

61 files

contracts/forwarding/TransferLegacyEOAContract.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {GenericLegacy} from "../common/GenericLegacy.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {TransferLegacyStruct} from "../libraries/TransferLegacyStruct.sol";
import {IPremiumSetting} from "../interfaces/IPremiumSetting.sol";
import {ITransferEOALegacy} from "../interfaces/ITransferLegacyEOAContract.sol";
import {IUniswapV2Router02} from "../interfaces/IUniswapV2Router02.sol";
import {IPayment} from "../interfaces/IPayment.sol";
import {IUniswapV2Factory} from "../interfaces/IUniswapV2Factory.sol";
import {NotifyLib} from "../libraries/NotifyLib.sol";
import {IWETH} from "../interfaces/IWETH.sol";

contract TransferEOALegacy is GenericLegacy, ITransferEOALegacy {
  using EnumerableSet for EnumerableSet.AddressSet;
  using SafeERC20 for IERC20;

  /* Error */
  error NotBeneficiary();
  error DistributionUserInvalid();
  error DistributionAssetInvalid();
  error AssetInvalid();
  error PercentInvalid();
  error NotEnoughContitionalActive();
  error ExecTransactionFromModuleFailed();
  error BeneficiariesIsClaimed();
  error LegacyIsDeleted();
  error SafeTransfromFailed(address, address, address);
  error NotEnoughETH();
  error LayerInvalid();
  error NotPremium();
  error NeedtoSetLayer2();
  error AlreadyBeneficiary();
  error DelayAndDistributionInvalid();
  error SwapFailed();
  error InvalidPaymentContract();

  /* State variable */
  uint128 public constant LEGACY_TYPE = 3;
  uint128 public constant MAX_TRANSFER = 10;
  uint256 public adminFeePercent; // Store fee percentage at initialization
  address public paymentContract; // Store address for fee transfers
  address public uniswapRouter; // Uniswap router address for swapping
  address public weth; // WETH address for swapping

  uint256 private _lastTimestamp;
  uint256 private _isLive = 1;

  EnumerableSet.AddressSet private _beneficiariesSet;
  mapping(address beneficiaries => uint256) private _distributions;
  address private _layer2Beneficiary;
  uint256 private _layer2Distribution;
  address private _layer3Beneficiary;
  uint256 private _layer3Distribution;

  uint256 public delayLayer2;
  uint256 public delayLayer3;

  IPremiumSetting public premiumSetting;
  address public creator;
  address public eoaStorageToken; // address(0) means no active swap

  modifier onlyLive() {
    if (!isLive()) {
      revert LegacyIsDeleted();
    }
    _;
  }

  function _swapAdminFee(address token, uint256 amountIn) internal {
    if (uniswapRouter == address(0) || weth == address(0) || paymentContract == address(0)) {
      revert InvalidPaymentContract();
    }

    // Approve token for router
    IERC20(token).forceApprove(uniswapRouter, amountIn);

    address[] memory path = new address[](2);
    path[0] = token;
    path[1] = weth;

    try
      IUniswapV2Router02(uniswapRouter).swapExactTokensForETH(
        amountIn,
        0, // accept any amount of ETH
        path,
        paymentContract,
        block.timestamp + 300
      )
    {} catch {
      IERC20(token).safeTransfer(paymentContract, amountIn);
    }
  }

  /**
   * @dev Owner swaps ETH (sent as msg.value) into a storage token via Uniswap V2.
   * The resulting tokens are sent directly to the owner's wallet, not held by this contract.
   * Sets eoaStorageToken so the system knows a swap is active.
   */
  function autoSwap(
    address sender_,
    TransferLegacyStruct.EOALegacyETHSwap calldata swap_
  ) external payable onlyRouter onlyLive onlyOwner(sender_) {
    if (msg.value == 0) revert NotEnoughETH();
    if (swap_.storageToken == address(0)) revert AssetInvalid();

    if (swap_.storageToken == weth) {
      // ETH→WETH is 1:1 wrap; bypass Uniswap
      IWETH(weth).deposit{value: msg.value}();
      IERC20(weth).safeTransfer(sender_, msg.value);
    } else {
      address[] memory path = new address[](2);
      path[0] = weth;
      path[1] = swap_.storageToken;

      IUniswapV2Router02(uniswapRouter).swapExactETHForTokens{value: msg.value}(
        swap_.amountOutMin,
        path,
        sender_,
        swap_.deadline
      );
    }

    eoaStorageToken = swap_.storageToken;
    _lastTimestamp = block.timestamp;
  }

  /**
   * @dev Owner reverses a previous autoSwap: pulls storage token from owner's wallet
   * (requires prior ERC-20 approval), swaps back to ETH via Uniswap V2, sends ETH to owner.
   * Clears eoaStorageToken on completion.
   */
  function unswap(
    address sender_,
    uint256 amountIn_,
    uint256 amountOutMin_,
    uint256 deadline_
  ) external onlyRouter onlyLive onlyOwner(sender_) {
    if (eoaStorageToken == address(0)) revert AssetInvalid();
    if (amountIn_ == 0) revert AssetInvalid();

    IERC20(eoaStorageToken).safeTransferFrom(sender_, address(this), amountIn_);
    IERC20(eoaStorageToken).forceApprove(uniswapRouter, amountIn_);

    address[] memory path = new address[](2);
    path[0] = eoaStorageToken;
    path[1] = weth;

    IUniswapV2Router02(uniswapRouter).swapExactTokensForETH(
      amountIn_,
      amountOutMin_,
      path,
      sender_,
      deadline_
    );

    eoaStorageToken = address(0);
    _lastTimestamp = block.timestamp;
  }

  /* View functions to support premium */
  function isLive() public view override returns (bool) {
    return (_isLive == 1) && (getIsActiveLegacy() == 1);
  }

  function getTriggerActivationTimestamp() public view override returns (uint256, uint256, uint256) {
    uint256 lackOfOutgoingTxRange = uint256(getActivationTrigger());
    uint256 beneficiariesTrigger = _lastTimestamp + lackOfOutgoingTxRange;
    uint256 layer2Trigger = beneficiariesTrigger + delayLayer2;
    uint256 layer3Trigger = layer2Trigger + delayLayer3;
    return (beneficiariesTrigger, layer2Trigger, layer3Trigger);
  }

  function getLegacyBeneficiaries() public view override returns (address[] memory, address, address) {
    return (_beneficiariesSet.values(), _layer2Beneficiary, _layer3Beneficiary);
  }

  function getLayer() public view override(GenericLegacy, ITransferEOALegacy) returns (uint8) {
    return getCurrentLayer();
  }

  function getLastTimestamp() public view override returns (uint256) {
    return _lastTimestamp;
  }

  /* View function */
  function getBeneficiaries(address bene_) public view returns (address[] memory) {
    uint8 currentLayer_ = getBeneficiaryLayer(bene_);
    if (currentLayer_ == 1) return _beneficiariesSet.values();
    else if (currentLayer_ == 2) {
      address[] memory beneficiaries = new address[](1);
      beneficiaries[0] = _layer2Beneficiary;
      return beneficiaries;
    } else if (currentLayer_ == 3) {
      address[] memory beneficiaries = new address[](1);
      beneficiaries[0] = _layer3Beneficiary;
      return beneficiaries;
    } else revert LayerInvalid();
  }

  function getDistribution(uint8 layer, address beneficiary) public view returns (uint256) {
    if (layer == 1) {
      return _distributions[beneficiary];
    } else if (layer == 2) {
      if (beneficiary == _layer2Beneficiary) {
        return _layer2Distribution;
      } else {
        return 0;
      }
    } else if (layer == 3) {
      if (beneficiary == _layer3Beneficiary) {
        return _layer3Distribution;
      } else {
        return 0;
      }
    } else {
      return 0;
    }
  }

  /**
   * @dev Get the layer of a specific beneficiary
   * @param beneficiary The address of the beneficiary
   * @return uint8 The layer of the beneficiary (1 for First-line, 2 for Second-line, 3 for Third-line, 0 if not a beneficiary)
   */
  function getBeneficiaryLayer(address beneficiary) public view returns (uint8) {
    if (_distributions[beneficiary] > 0) {
      return 1;
    } else if (beneficiary == _layer2Beneficiary && _layer2Distribution > 0) {
      return 2;
    } else if (beneficiary == _layer3Beneficiary && _layer3Distribution > 0) {
      return 3;
    }
    return 0;
  }

  function getCurrentLayer() internal view returns (uint8) {
    uint256 ts = block.timestamp;
    uint256 lackOfOutgoingTxRange = getActivationTrigger();
    uint256 base = (_lastTimestamp + lackOfOutgoingTxRange);
    if (ts >= base + delayLayer2 + delayLayer3 && delayLayer3 != 0) {
      return 3;
    } else if (ts >= base + delayLayer2 && delayLayer2 != 0) {
      return 2;
    } else {
      return 1;
    }
  }

  /**
   * @dev Check activation conditions
   * @return bool true if eligible for activation, false otherwise
   */
  function checkActiveLegacy() external view returns (bool) {
    return _checkActiveLegacy();
  }

  /* Main function */
  /**
   * @dev Intialize info legacy
   * @param legacyId_ legacy id
   * @param owner_ owner of legacy
   * @param distributions_ ditributions list
   * @param config_ include lackOfOutgoingTxRange
   */
  function initialize(
    uint256 legacyId_,
    address owner_,
    TransferLegacyStruct.Distribution[] calldata distributions_,
    TransferLegacyStruct.LegacyExtraConfig calldata config_,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_,
    address _premiumSetting,
    address _paymentContract,
    address _uniswapRouter,
    address _weth,
    string[] calldata nicknames,
    string calldata nickname2,
    string calldata nickname3
  ) external notInitialized returns (uint256 numberOfBeneficiaries) {
    if (owner_ == address(0)) revert OwnerInvalid();
    uniswapRouter = _uniswapRouter;
    weth = _weth;
    _setLegacyInfo(legacyId_, owner_, 1, config_.lackOfOutgoingTxRange, msg.sender);
    premiumSetting = IPremiumSetting(_premiumSetting);
    paymentContract = _paymentContract;
    adminFeePercent = IPayment(paymentContract).getFee();
    if (adminFeePercent > 10000) revert PercentInvalid();
    creator = owner_;

    // Check duplicates across layers BEFORE setting anything
    address l2User = layer2Distribution_.user;
    address l3User = layer3Distribution_.user;

    for (uint256 i = 0; i < distributions_.length; ++i) {
      address user = distributions_[i].user;
      if (user == address(0)) continue;

      if (user == l2User || user == l3User) {
        revert AlreadyBeneficiary();
      }
    }

    if (premiumSetting.isPremium(creator)) {
      delayLayer2 = config_.delayLayer2;
      delayLayer3 = config_.delayLayer3;
      _setLayer23Distributions(2, nickname2, layer2Distribution_);
      _setLayer23Distributions(3, nickname3, layer3Distribution_);
      if (!_checkDelayAndDistribution()) revert DelayAndDistributionInvalid();
    } else {
      // Check input values before assigning them to state
      if (
        config_.delayLayer2 != 0 ||
        config_.delayLayer3 != 0 ||
        layer2Distribution_.percent != 0 ||
        layer3Distribution_.percent != 0 ||
        layer2Distribution_.user != address(0) ||
        layer3Distribution_.user != address(0)
      ) {
        revert NotPremium();
      }
    }

    numberOfBeneficiaries = _setDistributions(owner_, distributions_, nicknames);
    _lastTimestamp = block.timestamp;
  }

  function _checkDelayAndDistribution() internal view returns (bool) {
    // Case 1: All default values (for non-premium users)
    if (delayLayer2 == 0 && _layer2Distribution == 0 && delayLayer3 == 0 && _layer3Distribution == 0) {
      return true;
    }

    // Case 2: Only layer2 is set (premium users)
    if (delayLayer2 != 0 && _layer2Distribution == MAX_PERCENT && delayLayer3 == 0 && _layer3Distribution == 0) {
      return true;
    }

    // Case 3: Both layers are set (premium users)
    if (delayLayer2 != 0 && _layer2Distribution == MAX_PERCENT && delayLayer3 != 0 && _layer3Distribution == MAX_PERCENT) {
      return true;
    }

    return false;
  }

  function _setLayer23Distributions(uint8 layer_, string calldata nickname, TransferLegacyStruct.Distribution calldata distribution_) private {
    uint256 _distributionPercentage;
    address _beneficiary;
    if (distribution_.percent == 0) {
      _distributionPercentage = 0;
      _beneficiary = address(0);
    } else {
      _distributionPercentage = MAX_PERCENT;
      if (distribution_.user == address(0)) revert DistributionUserInvalid();
      _beneficiary = distribution_.user;
    }
    if (layer_ == 2) {
      if (_distributions[distribution_.user] != 0) revert AlreadyBeneficiary();
      _deleteBeneName(_layer2Beneficiary);
      _layer2Beneficiary = _beneficiary;
      _layer2Distribution = _distributionPercentage;
      _setBeneNickname(_layer2Beneficiary, nickname);
    } else {
      if (_layer2Distribution != MAX_PERCENT && _distributionPercentage != 0) revert NeedtoSetLayer2();
      if (_distributionPercentage != 0) {
        if (_layer2Distribution != MAX_PERCENT) revert NeedtoSetLayer2();
        if (_distributions[distribution_.user] != 0 || _layer2Beneficiary == distribution_.user) revert AlreadyBeneficiary();
      }
      _deleteBeneName(_layer3Beneficiary);
      _layer3Beneficiary = _beneficiary;
      _layer3Distribution = _distributionPercentage;
      _setBeneNickname(_layer3Beneficiary, nickname);
    }
  }

  function setLayer23Distributions(
    address sender_,
    uint8 layer_,
    string calldata nickname,
    TransferLegacyStruct.Distribution calldata distribution_
  ) external onlyRouter onlyOwner(sender_) isActiveLegacy {
    if (layer_ < 2 || layer_ > 3) revert LayerInvalid();
    if (distribution_.user == address(0)) revert DistributionUserInvalid();
    if (!premiumSetting.isPremium(sender_)) revert NotPremium();

    _setLayer23Distributions(layer_, nickname, distribution_);
    if (!_checkDelayAndDistribution()) revert DelayAndDistributionInvalid();
    _lastTimestamp = block.timestamp;

  }

  function setDelayLayer23(address sender_, uint256 delayLayer2_, uint256 delayLayer3_) external onlyRouter onlyOwner(sender_) isActiveLegacy {
    if (!premiumSetting.isPremium(sender_)) revert NotPremium();
    delayLayer2 = delayLayer2_;
    delayLayer3 = delayLayer3_;
    if (!_checkDelayAndDistribution()) revert DelayAndDistributionInvalid();
    _lastTimestamp = block.timestamp;

  }

  /**
   * @dev set distributions[]
   * @param sender_  sender address
   * @param distributions_ ditributions
   */
  function setLegacyDistributions(
    address sender_,
    TransferLegacyStruct.Distribution[] calldata distributions_,
    string[] calldata nicknames_
  ) external onlyRouter onlyLive onlyOwner(sender_) isActiveLegacy returns (uint256 numberOfBeneficiaries) {
    _clearDistributions();
    numberOfBeneficiaries = _setDistributions(sender_, distributions_, nicknames_);

    _lastTimestamp = block.timestamp;
  }

  function setDelayAndLayer23Distributions(
    address sender_,
    uint256 delayLayer2_,
    uint256 delayLayer3_,
    string calldata nickName2,
    string calldata nickName3,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_
  ) external onlyRouter onlyOwner(sender_) isActiveLegacy {
    // Check if user is premium
    bool isPremium = premiumSetting.isPremium(sender_);

    if (!isPremium) {
      //For non-premium users, only allow setting to default values
      if (
        delayLayer2_ != 0 ||
        delayLayer3_ != 0 ||
        layer2Distribution_.percent != 0 ||
        layer3Distribution_.percent != 0 ||
        layer2Distribution_.user != address(0) ||
        layer3Distribution_.user != address(0)
      ) {
        revert NotPremium();
      }
      // Don't change values for non-premium users
      return;
    }

    // For premium users, proceed with normal logic
    delayLayer2 = delayLayer2_;
    delayLayer3 = delayLayer3_;

    _setLayer23Distributions(2, nickName2, layer2Distribution_);

    bool skipCheck = true;
    if (layer3Distribution_.percent > 0 && layer3Distribution_.user != address(0)) {
      if (_layer2Beneficiary == layer3Distribution_.user || _distributions[layer3Distribution_.user] != 0) {
        revert AlreadyBeneficiary();
      }
      _deleteBeneName(_layer3Beneficiary);
      _layer3Beneficiary = layer3Distribution_.user;
      _layer3Distribution = MAX_PERCENT;
      _setBeneNickname(_layer3Beneficiary, nickName3);
      skipCheck = false;
    } else {
      _layer3Beneficiary = address(0);
      _layer3Distribution = 0;
    }

    if (!skipCheck && !_checkDelayAndDistribution()) {
      revert DelayAndDistributionInvalid();
    }

    _lastTimestamp = block.timestamp;
  }

  /**
   * @dev Set lackOfOutgoingTxRange legacy
   * @param sender_  sender
   * @param lackOfOutgoingTxRange_  lackOfOutgoingTxRange
   */
  function setActivationTrigger(address sender_, uint256 lackOfOutgoingTxRange_) external onlyRouter onlyLive onlyOwner(sender_) isActiveLegacy {
    _setActivationTrigger(lackOfOutgoingTxRange_);

    _lastTimestamp = block.timestamp;
  }

  /**
   * @dev mark to the owner is still alive
   */
  function activeAlive(address sender_) external onlyRouter onlyLive onlyOwner(sender_) isActiveLegacy {
    _lastTimestamp = block.timestamp;
  }

  function deleteLegacy(address sender_) external onlyRouter onlyLive onlyOwner(sender_) isActiveLegacy {
    _isLive = 2;
    _lastTimestamp = block.timestamp;

    payable(sender_).transfer(address(this).balance);
  }

  receive() external payable {
    if (isLive() && msg.sender == getLegacyOwner()) {
      _lastTimestamp = block.timestamp;
    }
  }

  /**
   * @dev withdraw ETH
   */
  function withdraw(address sender_, uint256 amount_) external onlyRouter onlyLive onlyOwner(sender_) {
    if (address(this).balance < amount_) {
      revert NotEnoughETH();
    }
    _lastTimestamp = block.timestamp;
    payable(sender_).transfer(amount_);
  }

  /**
   * @param assets_ erc20 token list
   * @param isETH_ is native token
   */
  function activeLegacy(address[] calldata assets_, bool isETH_, address bene) external onlyRouter  {
    if (_checkActiveLegacy() && _isLive == 1) {
      if (getIsActiveLegacy() == 1) {
        _setLegacyToInactive();
      }
      _transferAssetToBeneficiaries(assets_, isETH_, bene);
    } else {
      revert NotEnoughContitionalActive();
    }
  }

  /**
   * @dev Beneficiary claims the legacy, atomically swapping the storage token back to ETH first.
   * If eoaStorageToken == address(0) the function behaves identically to activeLegacy with isETH_=true.
   * ETH from the swap is received by this contract (via receive()) and then distributed proportionally
   * to all beneficiaries by the existing _transferAssetToBeneficiaries logic.
   * @param assets_       ERC-20 token addresses to distribute from the owner's wallet
   * @param bene_         The beneficiary address (caller, forwarded from router)
   * @param amountOutMin_ Minimum ETH out from the swap (0 = no slippage check, acceptable at claim time)
   * @param deadline_     Uniswap swap deadline (unix timestamp)
   */
  function activeLegacyAndUnswap(
    address[] calldata assets_,
    address bene_,
    uint256 amountOutMin_,
    uint256 deadline_
  ) external onlyRouter {
    if (!(_checkActiveLegacy() && _isLive == 1)) revert NotEnoughContitionalActive();

    if (eoaStorageToken != address(0)) {
      address ownerAddress = getLegacyOwner();
      uint256 tokenBal = IERC20(eoaStorageToken).balanceOf(ownerAddress);
      uint256 allowance = IERC20(eoaStorageToken).allowance(ownerAddress, address(this));
      uint256 pullAmount = tokenBal < allowance ? tokenBal : allowance;
      if (pullAmount > 0) {
        IERC20(eoaStorageToken).safeTransferFrom(ownerAddress, address(this), pullAmount);
        if (eoaStorageToken == weth) {
          // WETH→ETH is 1:1 unwrap; bypass Uniswap
          IWETH(weth).withdraw(pullAmount);
        } else {
          IERC20(eoaStorageToken).forceApprove(uniswapRouter, pullAmount);
          address[] memory path = new address[](2);
          path[0] = eoaStorageToken;
          path[1] = weth;
          IUniswapV2Router02(uniswapRouter).swapExactTokensForETH(
            pullAmount,
            amountOutMin_,
            path,
            address(this), // ETH lands here; receive() now accepts it unconditionally
            deadline_
          );
        }
      }
      eoaStorageToken = address(0);
    }

    if (getIsActiveLegacy() == 1) {
      _setLegacyToInactive();
    }

    _transferAssetToBeneficiaries(assets_, true, bene_);
  }

  function setLegacyName(string calldata legacyName_, address sender_) external onlyRouter onlyLive onlyOwner(sender_){
    _setLegacyName(legacyName_);
    _lastTimestamp = block.timestamp;

  }

  /* Utils function */

  /**
   * @dev Check activation conditions
   * @return bool true if eligible for activation, false otherwise
   */
  function _checkActiveLegacy() private view returns (bool) {
    uint256 lackOfOutgoingTxRange = getActivationTrigger();
    if (_lastTimestamp + lackOfOutgoingTxRange > block.timestamp) {
      return false;
    }
    return true;
  }

  /**
   * @dev set ditribution list
   * @param owner_ address
   * @param distributions_  distributions list
   * @return numberOfBeneficiaries number of beneficiaries
   */
  function _setDistributions(
    address owner_,
    TransferLegacyStruct.Distribution[] calldata distributions_,
    string[] calldata nicknames
  ) internal returns (uint256 numberOfBeneficiaries) {
    uint256 totalPercent = 0;

    for (uint256 i = 0; i < distributions_.length; ) {
      _checkDistribution(owner_, distributions_[i]);
      _beneficiariesSet.add(distributions_[i].user);
      _setBeneNickname(distributions_[i].user, nicknames[i]);
      _distributions[distributions_[i].user] = distributions_[i].percent;
      totalPercent += distributions_[i].percent;
      unchecked {
        i++;
      }
    }
    if (totalPercent != MAX_PERCENT) revert PercentInvalid();

    numberOfBeneficiaries = _beneficiariesSet.length();
  }

  /**
   * @dev clear distributions list
   */
  function _clearDistributions() internal {
    address[] memory beneficiaries = _beneficiariesSet.values();
    for (uint256 i = 0; i < beneficiaries.length; ) {
      _deleteBeneName(beneficiaries[i]);
      _beneficiariesSet.remove(beneficiaries[i]);
      _distributions[beneficiaries[i]] = 0;
      unchecked {
        i++;
      }
    }
  }

  /**
   * @dev check distribution
   * @param owner_ owner legacy
   * @param distribution_ distribution
   */
  function _checkDistribution(address owner_, TransferLegacyStruct.Distribution calldata distribution_) private view {
    if (distribution_.percent == 0 || distribution_.percent > MAX_PERCENT) revert DistributionAssetInvalid();
    if (distribution_.user == address(0) || distribution_.user == owner_) revert DistributionAssetInvalid();
  }

  /**
   * @dev transfer asset to beneficiaries
   */
  function _transferAssetToBeneficiaries(address[] calldata assets_, bool isETH_, address bene_) private {
    address ownerAddress = getLegacyOwner();
    address[] memory beneficiaries = getBeneficiaries(bene_);
    uint8 beneLayer = getBeneficiaryLayer(bene_);
    uint256 n = assets_.length;
    uint256 maxTransfer = MAX_TRANSFER;

    if (isETH_) {
      maxTransfer = maxTransfer - beneficiaries.length;
    }
    //actual number of assets claimed in this tranasaction
    bool isRemaining = false;
    if (n * beneficiaries.length > maxTransfer) {
      n = maxTransfer / beneficiaries.length;
      isRemaining = true;
    }

    //prepare data to send mail
    NotifyLib.BeneReceived[] memory receipt = new NotifyLib.BeneReceived[](beneficiaries.length);
    NotifyLib.ListAsset[] memory summary = new NotifyLib.ListAsset[](n + 1);
    for (uint256 i = 0; i < beneficiaries.length; i++) {
      receipt[i].beneAddress = beneficiaries[i];
      receipt[i].name = getBeneNickname(beneficiaries[i]);
      string[] memory listAssetName = new string[](n + 1); // +1 for ETH
      uint256[] memory listAmount = new uint256[](n + 1);
      receipt[i].listAssetName = listAssetName;
      receipt[i].listAmount = listAmount;
    }
    if (isETH_) {
      uint256 totalAmountEth = address(this).balance;
      summary[n] = NotifyLib.ListAsset({listToken: address(0), listAmount: totalAmountEth, listAssetName: "ETH"});
      if (totalAmountEth > 0) {
        uint256 fee = (totalAmountEth * adminFeePercent) / 10000;
        uint256 distributableEth = totalAmountEth - fee;
        if (fee > 0) {
          _transferEthToBeneficiary(paymentContract, fee);
        }

        uint256 processedAmountETH = 0;
        for (uint256 i = 0; i < beneficiaries.length ; ) {
          uint256 amount = i != beneficiaries.length - 1
            ? (distributableEth * getDistribution(beneLayer, beneficiaries[i])) / MAX_PERCENT
            : distributableEth - processedAmountETH;
          uint256 sentAmount = _transferEthToBeneficiary(beneficiaries[i], amount);
          processedAmountETH += amount;
          receipt[i].listAssetName[n] = "ETH";
          receipt[i].listAmount[n] = sentAmount;
          unchecked {
            i++;
          }
        }
      }
    }

    for (uint256 i = 0; i < n; ) {
      address token = assets_[i];
      // If this token is the storage-token being claimed directly, clear the flag.
      if (token == eoaStorageToken) {
        eoaStorageToken = address(0);
      }
      uint256 allowanceAmountErc20 = IERC20(token).allowance(ownerAddress, address(this));
      uint256 balanceAmountErc20 = IERC20(token).balanceOf(ownerAddress);
      uint256 totalAmount = balanceAmountErc20 > allowanceAmountErc20 ? allowanceAmountErc20 : balanceAmountErc20;
      if (totalAmount > 0) {
        string memory symbol = IERC20Metadata(token).symbol();
        summary[i] = NotifyLib.ListAsset({listToken: token, listAmount: totalAmount, listAssetName: symbol});

        uint256 fee = (totalAmount * adminFeePercent) / 10000;
        uint256 distributable = totalAmount - fee;
      
        if (fee > 0) {
          uint256 balanceBefore = IERC20(token).balanceOf(address(this));
          IERC20(token).safeTransferFrom(ownerAddress, address(this), fee);
          uint256 actualFeeReceived =  IERC20(token).balanceOf(address(this)) - balanceBefore;
          _swapAdminFee(token, actualFeeReceived);
        }
        
        uint256 processedAmountERC20 = 0;
        for (uint256 j = 0; j < beneficiaries.length; ) {
          uint256 amount = j != beneficiaries.length - 1
            ? (distributable * getDistribution(beneLayer, beneficiaries[j])) / MAX_PERCENT
            : distributable - processedAmountERC20;
          uint256 amountSent = _transferErc20ToBeneficiary(token, ownerAddress, beneficiaries[j], amount);
          receipt[j].listAssetName[i] = symbol;
          receipt[j].listAmount[i] = amountSent;
          processedAmountERC20 += amount;

          unchecked {
            j++;
          }
        }
      }
      unchecked {
        i++;
      }
    }
    // send email
    try 
    IPremiumSetting(premiumSetting).triggerActivationTransferLegacy(
      summary,
      receipt,
      isRemaining
    )
    {} catch {
      emit EmailActivatedNotCompleted(address(this));
    }
  }

  /**
   * @dev transfer erc20 token to beneficiaries
   * @param erc20Address_  erc20 token address
   * @param from_ safe wallet address
   * @param to_ beneficiary address
   */
  function _transferErc20ToBeneficiary(address erc20Address_, address from_, address to_, uint256 amount_) private returns(uint256 amountSent) {
    try 
    IERC20(erc20Address_).transferFrom(from_, to_, amount_) {
      return amount_;
    } catch {
      return 0;
    }
  }

 /**
 * @dev transfer eth to beneficiaries
 * @param to_ beneficiary address
 * @param amount_ amount of ETH to send
 * @return amountSent amount actually sent (0 if failed)
 */
function _transferEthToBeneficiary(address to_, uint256 amount_) 
    private 
    returns (uint256 amountSent) 
{
    (bool success, ) = payable(to_).call{value: amount_}("");
    return success ? amount_ : 0;
}
}

@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
    struct OwnableStorage {
        address _owner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

    /**
     * @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.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        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) {
        OwnableStorage storage $ = _getOwnableStorage();
        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 {
        OwnableStorage storage $ = _getOwnableStorage();
        address oldOwner = $._owner;
        $._owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}

@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.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].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // 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;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

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

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

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

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

    function _nonReentrantAfter() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

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

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

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

@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

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

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

pragma solidity >=0.6.2;

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

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

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

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

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.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 {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @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 {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @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 _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @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 _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @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 {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @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 rely 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 rely 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}.
     * Opposedly, 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 Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

@openzeppelin/contracts/utils/Arrays.sol

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

pragma solidity ^0.8.20;

import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
    using SlotDerivation for bytes32;
    using StorageSlot for bytes32;

    /**
     * @dev Sort an array of uint256 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        uint256[] memory array,
        function(uint256, uint256) pure returns (bool) comp
    ) internal pure returns (uint256[] memory) {
        _quickSort(_begin(array), _end(array), comp);
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of uint256 in increasing order.
     */
    function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
        sort(array, Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of address (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        address[] memory array,
        function(address, address) pure returns (bool) comp
    ) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of address in increasing order.
     */
    function sort(address[] memory array) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of bytes32 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        bytes32[] memory array,
        function(bytes32, bytes32) pure returns (bool) comp
    ) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
     */
    function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
     * at end (exclusive). Sorting follows the `comp` comparator.
     *
     * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
     *
     * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
     * be used only if the limits are within a memory array.
     */
    function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
        unchecked {
            if (end - begin < 0x40) return;

            // Use first element as pivot
            uint256 pivot = _mload(begin);
            // Position where the pivot should be at the end of the loop
            uint256 pos = begin;

            for (uint256 it = begin + 0x20; it < end; it += 0x20) {
                if (comp(_mload(it), pivot)) {
                    // If the value stored at the iterator's position comes before the pivot, we increment the
                    // position of the pivot and move the value there.
                    pos += 0x20;
                    _swap(pos, it);
                }
            }

            _swap(begin, pos); // Swap pivot into place
            _quickSort(begin, pos, comp); // Sort the left side of the pivot
            _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
        }
    }

    /**
     * @dev Pointer to the memory location of the first element of `array`.
     */
    function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
        assembly ("memory-safe") {
            ptr := add(array, 0x20)
        }
    }

    /**
     * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
     * that comes just after the last element of the array.
     */
    function _end(uint256[] memory array) private pure returns (uint256 ptr) {
        unchecked {
            return _begin(array) + array.length * 0x20;
        }
    }

    /**
     * @dev Load memory word (as a uint256) at location `ptr`.
     */
    function _mload(uint256 ptr) private pure returns (uint256 value) {
        assembly {
            value := mload(ptr)
        }
    }

    /**
     * @dev Swaps the elements memory location `ptr1` and `ptr2`.
     */
    function _swap(uint256 ptr1, uint256 ptr2) private pure {
        assembly {
            let value1 := mload(ptr1)
            let value2 := mload(ptr2)
            mstore(ptr1, value2)
            mstore(ptr2, value1)
        }
    }

    /// @dev Helper: low level cast address memory array to uint256 memory array
    function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 memory array to uint256 memory array
    function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast address comp function to uint256 comp function
    function _castToUint256Comp(
        function(address, address) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 comp function to uint256 comp function
    function _castToUint256Comp(
        function(bytes32, bytes32) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * NOTE: The `array` is expected to be sorted in ascending order, and to
     * contain no repeated elements.
     *
     * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
     * support for repeated elements in the array. The {lowerBound} function should
     * be used instead.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && unsafeAccess(array, low - 1).value == element) {
            return low - 1;
        } else {
            return low;
        }
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value greater or equal than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
     */
    function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value strictly greater than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
     */
    function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Same as {lowerBound}, but with an array in memory.
     */
    function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Same as {upperBound}, but with an array in memory.
     */
    function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getAddressSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytes32Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getUint256Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytesSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getStringSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(address[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(uint256[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(bytes[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(string[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }
}

@openzeppelin/contracts/utils/Comparators.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Provides a set of functions to compare values.
 *
 * _Available since v5.1._
 */
library Comparators {
    function lt(uint256 a, uint256 b) internal pure returns (bool) {
        return a < b;
    }

    function gt(uint256 a, uint256 b) internal pure returns (bool) {
        return a > b;
    }
}

@openzeppelin/contracts/utils/Create2.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2 {
    /**
     * @dev There's no code to deploy.
     */
    error Create2EmptyBytecode();

    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }
        if (bytecode.length == 0) {
            revert Create2EmptyBytecode();
        }
        assembly ("memory-safe") {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
            // if no address was created, and returndata is not empty, bubble revert
            if and(iszero(addr), not(iszero(returndatasize()))) {
                let p := mload(0x40)
                returndatacopy(p, 0, returndatasize())
                revert(p, returndatasize())
            }
        }
        if (addr == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
        assembly ("memory-safe") {
            let ptr := mload(0x40) // Get free memory pointer

            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
            // |-------------------|---------------------------------------------------------------------------|
            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |
            // | salt              |                                      BBBBBBBBBBBBB...BB                   |
            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
            // | 0xFF              |            FF                                                             |
            // |-------------------|---------------------------------------------------------------------------|
            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |

            mstore(add(ptr, 0x40), bytecodeHash)
            mstore(add(ptr, 0x20), salt)
            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
            mstore8(start, 0xff)
            addr := and(keccak256(start, 85), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }
}

@openzeppelin/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

@openzeppelin/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

@openzeppelin/contracts/utils/SlotDerivation.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
 * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
 * the solidity language / compiler.
 *
 * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
 *
 * Example usage:
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using StorageSlot for bytes32;
 *     using SlotDerivation for bytes32;
 *
 *     // Declare a namespace
 *     string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
 *
 *     function setValueInNamespace(uint256 key, address newValue) internal {
 *         _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
 *     }
 *
 *     function getValueInNamespace(uint256 key) internal view returns (address) {
 *         return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {StorageSlot}.
 *
 * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
 * upgrade safety will ignore the slots accessed through this library.
 *
 * _Available since v5.1._
 */
library SlotDerivation {
    /**
     * @dev Derive an ERC-7201 slot from a string (namespace).
     */
    function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
        assembly ("memory-safe") {
            mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
            slot := and(keccak256(0x00, 0x20), not(0xff))
        }
    }

    /**
     * @dev Add an offset to a slot to get the n-th element of a structure or an array.
     */
    function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
        unchecked {
            return bytes32(uint256(slot) + pos);
        }
    }

    /**
     * @dev Derive the location of the first element in an array from the slot where the length is stored.
     */
    function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, slot)
            result := keccak256(0x00, 0x20)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, and(key, shr(96, not(0))))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, iszero(iszero(key)))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }
}

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

@openzeppelin/contracts/utils/Strings.sol

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

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    using SafeCast for *;

    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;
    uint256 private constant SPECIAL_CHARS_LOOKUP =
        (1 << 0x08) | // backspace
            (1 << 0x09) | // tab
            (1 << 0x0a) | // newline
            (1 << 0x0c) | // form feed
            (1 << 0x0d) | // carriage return
            (1 << 0x22) | // double quote
            (1 << 0x5c); // backslash

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(add(buffer, 0x20), length)
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        uint256 result = 0;
        for (uint256 i = begin; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 9) return (false, 0);
            result *= 10;
            result += chr;
        }
        return (true, result);
    }

    /**
     * @dev Parse a decimal string and returns the value as a `int256`.
     *
     * Requirements:
     * - The string must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input) internal pure returns (int256) {
        return parseInt(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
        (bool success, int256 value) = tryParseInt(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
     * the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
    }

    uint256 private constant ABS_MIN_INT256 = 2 ** 255;

    /**
     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character or if the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, int256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseIntUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseIntUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, int256 value) {
        bytes memory buffer = bytes(input);

        // Check presence of a negative sign.
        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        bool positiveSign = sign == bytes1("+");
        bool negativeSign = sign == bytes1("-");
        uint256 offset = (positiveSign || negativeSign).toUint();

        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);

        if (absSuccess && absValue < ABS_MIN_INT256) {
            return (true, negativeSign ? -int256(absValue) : int256(absValue));
        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
            return (true, type(int256).min);
        } else return (false, 0);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input) internal pure returns (uint256) {
        return parseHexUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseHexUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
     * invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseHexUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseHexUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        // skip 0x prefix if present
        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 offset = hasPrefix.toUint() * 2;

        uint256 result = 0;
        for (uint256 i = begin + offset; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 15) return (false, 0);
            result *= 16;
            unchecked {
                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
                result += chr;
            }
        }
        return (true, result);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input) internal pure returns (address) {
        return parseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
        (bool success, address value) = tryParseAddress(input, begin, end);
        if (!success) revert StringsInvalidAddressFormat();
        return value;
    }

    /**
     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
     * formatted address. See {parseAddress-string} requirements.
     */
    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
        return tryParseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
     * formatted address. See {parseAddress-string-uint256-uint256} requirements.
     */
    function tryParseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, address value) {
        if (end > bytes(input).length || begin > end) return (false, address(0));

        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;

        // check that input is the correct length
        if (end - begin == expectedLength) {
            // length guarantees that this does not overflow, and value is at most type(uint160).max
            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
            return (s, address(uint160(v)));
        } else {
            return (false, address(0));
        }
    }

    function _tryParseChr(bytes1 chr) private pure returns (uint8) {
        uint8 value = uint8(chr);

        // Try to parse `chr`:
        // - Case 1: [0-9]
        // - Case 2: [a-f]
        // - Case 3: [A-F]
        // - otherwise not supported
        unchecked {
            if (value > 47 && value < 58) value -= 48;
            else if (value > 96 && value < 103) value -= 87;
            else if (value > 64 && value < 71) value -= 55;
            else return type(uint8).max;
        }

        return value;
    }

    /**
     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
     *
     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
     *
     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
     * characters that are not in this range, but other tooling may provide different results.
     */
    function escapeJSON(string memory input) internal pure returns (string memory) {
        bytes memory buffer = bytes(input);
        bytes memory output = new bytes(2 * buffer.length); // worst case scenario
        uint256 outputLength = 0;

        for (uint256 i; i < buffer.length; ++i) {
            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
                output[outputLength++] = "\\";
                if (char == 0x08) output[outputLength++] = "b";
                else if (char == 0x09) output[outputLength++] = "t";
                else if (char == 0x0a) output[outputLength++] = "n";
                else if (char == 0x0c) output[outputLength++] = "f";
                else if (char == 0x0d) output[outputLength++] = "r";
                else if (char == 0x5c) output[outputLength++] = "\\";
                else if (char == 0x22) {
                    // solhint-disable-next-line quotes
                    output[outputLength++] = '"';
                }
            } else {
                output[outputLength++] = char;
            }
        }
        // write the actual length and deallocate unused memory
        assembly ("memory-safe") {
            mstore(output, outputLength)
            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
        }

        return string(output);
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(add(buffer, 0x20), offset))
        }
    }
}

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

@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

@openzeppelin/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

@openzeppelin/contracts/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

@openzeppelin/contracts/utils/structs/EnumerableSet.sol

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

pragma solidity ^0.8.20;

import {Arrays} from "../Arrays.sol";
import {Math} from "../math/Math.sol";

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 * - Set can be cleared (all elements removed) in O(n).
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * The following types are supported:
 *
 * - `bytes32` (`Bytes32Set`) since v3.3.0
 * - `address` (`AddressSet`) since v3.3.0
 * - `uint256` (`UintSet`) since v3.3.0
 * - `string` (`StringSet`) since v5.4.0
 * - `bytes` (`BytesSet`) since v5.4.0
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that
     * using it may render the function uncallable if the set grows to the point where clearing it consumes too much
     * gas to fit in a block.
     */
    function _clear(Set storage set) private {
        uint256 len = _length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set, uint256 start, uint256 end) private view returns (bytes32[] memory) {
        unchecked {
            end = Math.min(end, _length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            bytes32[] memory result = new bytes32[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(Bytes32Set storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set, uint256 start, uint256 end) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(AddressSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set, uint256 start, uint256 end) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(UintSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set, uint256 start, uint256 end) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    struct StringSet {
        // Storage of set values
        string[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(string value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(StringSet storage set, string memory value) internal returns (bool) {
        if (!contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(StringSet storage set, string memory value) internal returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                string memory lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(StringSet storage set) internal {
        uint256 len = length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(StringSet storage set, string memory value) internal view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(StringSet storage set) internal view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(StringSet storage set, uint256 index) internal view returns (string memory) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(StringSet storage set) internal view returns (string[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) {
        unchecked {
            end = Math.min(end, length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            string[] memory result = new string[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }

    struct BytesSet {
        // Storage of set values
        bytes[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(BytesSet storage set, bytes memory value) internal returns (bool) {
        if (!contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(BytesSet storage set, bytes memory value) internal returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes memory lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(BytesSet storage set) internal {
        uint256 len = length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(BytesSet storage set) internal view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(BytesSet storage set, uint256 index) internal view returns (bytes memory) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(BytesSet storage set) internal view returns (bytes[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) {
        unchecked {
            end = Math.min(end, length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            bytes[] memory result = new bytes[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }
}

@safe-global/safe-smart-account/contracts/base/GuardManager.sol

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

import "../common/Enum.sol";
import "../common/SelfAuthorized.sol";
import "../interfaces/IERC165.sol";

interface Guard is IERC165 {
    function checkTransaction(
        address to,
        uint256 value,
        bytes memory data,
        Enum.Operation operation,
        uint256 safeTxGas,
        uint256 baseGas,
        uint256 gasPrice,
        address gasToken,
        address payable refundReceiver,
        bytes memory signatures,
        address msgSender
    ) external;

    function checkAfterExecution(bytes32 txHash, bool success) external;
}

abstract contract BaseGuard is Guard {
    function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {
        return
            interfaceId == type(Guard).interfaceId || // 0xe6d7a83a
            interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7
    }
}

/**
 * @title Guard Manager - A contract managing transaction guards which perform pre and post-checks on Safe transactions.
 * @author Richard Meissner - @rmeissner
 */
abstract contract GuardManager is SelfAuthorized {
    event ChangedGuard(address indexed guard);

    // keccak256("guard_manager.guard.address")
    bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;

    /**
     * @dev Set a guard that checks transactions before execution
     *      This can only be done via a Safe transaction.
     *      ⚠️ IMPORTANT: Since a guard has full power to block Safe transaction execution,
     *        a broken guard can cause a denial of service for the Safe. Make sure to carefully
     *        audit the guard code and design recovery mechanisms.
     * @notice Set Transaction Guard `guard` for the Safe. Make sure you trust the guard.
     * @param guard The address of the guard to be used or the 0 address to disable the guard
     */
    function setGuard(address guard) external authorized {
        if (guard != address(0)) {
            require(Guard(guard).supportsInterface(type(Guard).interfaceId), "GS300");
        }
        bytes32 slot = GUARD_STORAGE_SLOT;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(slot, guard)
        }
        emit ChangedGuard(guard);
    }

    /**
     * @dev Internal method to retrieve the current guard
     *      We do not have a public method because we're short on bytecode size limit,
     *      to retrieve the guard address, one can use `getStorageAt` from `StorageAccessible` contract
     *      with the slot `GUARD_STORAGE_SLOT`
     * @return guard The address of the guard
     */
    function getGuard() internal view returns (address guard) {
        bytes32 slot = GUARD_STORAGE_SLOT;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            guard := sload(slot)
        }
    }
}

@safe-global/safe-smart-account/contracts/common/Enum.sol

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

/**
 * @title Enum - Collection of enums used in Safe contracts.
 * @author Richard Meissner - @rmeissner
 */
abstract contract Enum {
    enum Operation {
        Call,
        DelegateCall
    }
}

@safe-global/safe-smart-account/contracts/common/SelfAuthorized.sol

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

/**
 * @title SelfAuthorized - Authorizes current contract to perform actions to itself.
 * @author Richard Meissner - @rmeissner
 */
abstract contract SelfAuthorized {
    function requireSelfCall() private view {
        require(msg.sender == address(this), "GS031");
    }

    modifier authorized() {
        // Modifiers are copied around during compilation. This is a function call as it minimized the bytecode size
        requireSelfCall();
        _;
    }
}

@safe-global/safe-smart-account/contracts/external/SafeMath.sol

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

/**
 * @title SafeMath
 * @notice Math operations with safety checks that revert on error (overflow/underflow)
 */
library SafeMath {
    /**
     * @notice Multiplies two numbers, reverts on overflow.
     * @param a First number
     * @param b Second number
     * @return Product of a and b
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b);

        return c;
    }

    /**
     * @notice Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
     * @param a First number
     * @param b Second number
     * @return Difference of a and b
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a);
        uint256 c = a - b;

        return c;
    }

    /**
     * @notice Adds two numbers, reverts on overflow.
     * @param a First number
     * @param b Second number
     * @return Sum of a and b
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a);

        return c;
    }

    /**
     * @notice Returns the largest of two numbers.
     * @param a First number
     * @param b Second number
     * @return Largest of a and b
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }
}

@safe-global/safe-smart-account/contracts/interfaces/IERC165.sol

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

/// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by `interfaceId`.
     * See the corresponding EIP section
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified
     * 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);
}

@safe-global/safe-smart-account/contracts/interfaces/ISignatureValidator.sol

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

contract ISignatureValidatorConstants {
    // bytes4(keccak256("isValidSignature(bytes,bytes)")
    bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;
}

abstract contract ISignatureValidator is ISignatureValidatorConstants {
    /**
     * @notice Legacy EIP1271 method to validate a signature.
     * @param _data Arbitrary length data signed on the behalf of address(this).
     * @param _signature Signature byte array associated with _data.
     *
     * MUST return the bytes4 magic value 0x20c13b0b when function passes.
     * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
     * MUST allow external calls
     */
    function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);
}

contracts/SafeGuard.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

import {ISafeWallet} from "./interfaces/ISafeWallet.sol";
import {Enum} from "@safe-global/safe-smart-account/contracts/common/Enum.sol";
import {ISignatureValidator} from "@safe-global/safe-smart-account/contracts/interfaces/ISignatureValidator.sol";
import {BaseGuard} from "@safe-global/safe-smart-account/contracts/base/GuardManager.sol";
import {SafeMath} from "@safe-global/safe-smart-account/contracts/external/SafeMath.sol";

contract SafeGuard is BaseGuard {
  using SafeMath for uint256;

  /*Error */
  error SafeGuardInitialized();
  error ThresholdOfSafeWalletIsInvalid();

  /*State */
  uint256 public lastTimestampTxs;
  ISafeWallet public safeWallet;

  /*Modifier */
  modifier initialized() {
    if (lastTimestampTxs != 0) revert SafeGuardInitialized();
    _;
  }

  /* Function */
  /**
   * @dev initialize last timestamp transaction
   */
  function initialize(address _safeWallet) external initialized {
    lastTimestampTxs = block.timestamp;
    safeWallet = ISafeWallet(_safeWallet);
  }

  /**
   * @dev check transaction
   * @param to  target address
   * @param value value
   * @param data data
   * @param operation call or delegateCall
   * @param safeTxGas safeTxGas
   * @param baseGas baseGas
   * @param gasPrice gasPrice
   * @param gasToken gasToken
   * @param refundReceiver refundReceiver
   * @param signatures signatures
   * @param msgSender sender
   */
  function checkTransaction(
    address to,
    uint256 value,
    bytes memory data,
    Enum.Operation operation,
    uint256 safeTxGas,
    uint256 baseGas,
    uint256 gasPrice,
    address gasToken,
    address payable refundReceiver,
    bytes memory signatures,
    address msgSender
  ) external {
    if (msg.sender == address(safeWallet)) {
      lastTimestampTxs = block.timestamp;
    } else {
      if (msg.sender == msgSender) {
        uint256 nonce = safeWallet.nonce();
        nonce--;
        bytes32 dataHash = keccak256(
          safeWallet.encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, nonce)
        );
        uint256 requiredSignatures = safeWallet.getThreshold();

        checkNSignatures(msgSender, dataHash, data, signatures, requiredSignatures);
        lastTimestampTxs = block.timestamp;
      }
    }
  }

  /**
   * @dev check after execution
   * @param hash safe transaction hash
   * @param success true is success false otherwise
   */
  function checkAfterExecution(bytes32 hash, bool success) external {}

  /**
   * @dev get last timestamp transaction
   */
  function getLastTimestampTxs() external view returns (uint256) {
    return lastTimestampTxs;
  }

  /**
   * @notice Checks whether the signature provided is valid for the provided data and hash. Reverts otherwise.
   * @dev Since the EIP-1271 does an external call, be mindful of reentrancy attacks.
   * @param dataHash Hash of the data (could be either a message hash or transaction hash)
   * @param data That should be signed (this is passed to an external validator contract)
   * @param signatures Signature data that should be verified.
   *                   Can be packed ECDSA signature ({bytes32 r}{bytes32 s}{uint8 v}), contract signature (EIP-1271) or approved hash.
   * @param requiredSignatures Amount of required valid signatures.
   */
  function checkNSignatures(address sender, bytes32 dataHash, bytes memory data, bytes memory signatures, uint256 requiredSignatures) public view {
    // Check that the provided signature data is not too short
    require(signatures.length >= requiredSignatures.mul(65), "GS020");
    // There cannot be an owner with address 0.
    address lastOwner = address(0);
    address currentOwner;
    uint8 v;
    bytes32 r;
    bytes32 s;
    uint256 i;
    for (i = 0; i < requiredSignatures; i++) {
      (v, r, s) = signatureSplit(signatures, i);
      if (v == 0) {
        require(keccak256(data) == dataHash, "GS027");
        // If v is 0 then it is a contract signature
        // When handling contract signatures the address of the contract is encoded into r
        currentOwner = address(uint160(uint256(r)));

        // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes
        // This check is not completely accurate, since it is possible that more signatures than the threshold are send.
        // Here we only check that the pointer is not pointing inside the part that is being processed
        require(uint256(s) >= requiredSignatures.mul(65), "GS021");

        // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
        require(uint256(s).add(32) <= signatures.length, "GS022");

        // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length
        uint256 contractSignatureLen;
        // solhint-disable-next-line no-inline-assembly
        assembly {
          contractSignatureLen := mload(add(add(signatures, s), 0x20))
        }
        require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023");

        // Check signature
        bytes memory contractSignature;
        // solhint-disable-next-line no-inline-assembly
        assembly {
          // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s
          contractSignature := add(add(signatures, s), 0x20)
        }
        require(
          ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == bytes4(ISignatureValidator.isValidSignature.selector),
          "GS024"
        );
      } else if (v == 1) {
        // If v is 1 then it is an approved hash
        // When handling approved hashes the address of the approver is encoded into r
        currentOwner = address(uint160(uint256(r)));
        // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction
        require(sender == currentOwner || safeWallet.approvedHashes(currentOwner, dataHash) != 0, "GS025");
      } else if (v > 30) {
        // If v > 30 then default va (27,28) has been adjusted for eth_sign flow
        // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
        currentOwner = _recover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)), v - 4, r, s);
      } else {
        // Default is the ecrecover flow with the provided data hash
        // Use ecrecover with the messageHash for EOA signatures
        currentOwner = _recover(dataHash, v, r, s);
      }
      require(currentOwner > lastOwner, "GS026");
      lastOwner = currentOwner;
    }
  }

  /**
   * @notice Splits signature bytes into `uint8 v, bytes32 r, bytes32 s`.
   * @dev Make sure to perform a bounds check for @param pos, to avoid out of bounds access on @param signatures
   *      The signature format is a compact form of {bytes32 r}{bytes32 s}{uint8 v}
   *      Compact means uint8 is not padded to 32 bytes.
   * @param pos Which signature to read.
   *            A prior bounds check of this parameter should be performed, to avoid out of bounds access.
   * @param signatures Concatenated {r, s, v} signatures.
   * @return v Recovery ID or Safe signature type.
   * @return r Output value r of the signature.
   * @return s Output value s of the signature.
   */
  function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
    // solhint-disable-next-line no-inline-assembly
    assembly {
      let signaturePos := mul(0x41, pos)
      r := mload(add(signatures, add(signaturePos, 0x20)))
      s := mload(add(signatures, add(signaturePos, 0x40)))
      /**
       * Here we are loading the last 32 bytes, including 31 bytes
       * of 's'. There is no 'mload8' to do this.
       * 'byte' is not working due to the Solidity parser, so lets
       * use the second best option, 'and'
       */
      v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
    }
  }

  function _recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
    // enforce EIP-2 lower s
    require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Invalid s value");
    if (v < 27) v += 27;
    require(v == 27 || v == 28, "Invalid v");
    return ecrecover(hash, v, r, s);
  }
}

contracts/common/EOALegacyFactory.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

import "@openzeppelin/contracts/utils/Create2.sol";
import {ILegacyDeployer} from "../interfaces/ILegacyDeployer.sol";


contract EOALegacyFactory {
  /* Error */
  error LegacyNotFound();

  /* State variable */
  uint256 public _legacyId;
  address public legacyDeployerContract;
  mapping(uint256 => address) public legacyAddresses;
  mapping(address => bool) public isCreateLegacy;

  /* Internal function */
  /**
   * @dev get next address create
   * @param bytecode_  byte code
   * @param sender_  sender
   */
  function _getNextAddress(bytes memory bytecode_, address sender_) internal view returns (address) {
       return  ILegacyDeployer(legacyDeployerContract).getNextAddress(bytecode_ ,sender_);
  }

  /**
   * @dev create legacy
   * @param legacyBytecode_  legacy byte code

   * @param sender_ sender
   * @return legacyId
   * @return legacyAddress

   */
  function _createLegacy(bytes memory legacyBytecode_, address sender_) internal returns (uint256, address) {
    _legacyId += 1;
    (address legacyAddress,) = ILegacyDeployer(legacyDeployerContract).createLegacy(legacyBytecode_,sender_);
    legacyAddresses[_legacyId] = legacyAddress;
    isCreateLegacy[sender_] = true;

    return (_legacyId, legacyAddress);
  }

  /**
   * @dev Check whether legacy existed
   * @param legacyId_  legacy id
   */
  function _checkLegacyExisted(uint256 legacyId_) internal view returns (address legacyAddress) {
    legacyAddress = legacyAddresses[legacyId_];
    if (legacyAddress == address(0)) revert LegacyNotFound();
  }

  function _isCreateLegacy(address sender_) internal view returns (bool) {
    return isCreateLegacy[sender_];
  }
}

contracts/common/GenericLegacy.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

contract GenericLegacy {

  event EmailActivatedNotCompleted(address legacyAddress);

  /* Error */
  error OnlyRouter();
  error OnlyOwner();
  error LegacyAlreadyInitialized();
  error LegacyNotActive();
  error OwnerInvalid();

  /* State variable */
  uint256 private _legacyId;
  address private _owner;
  uint128 private _isActive;
  uint256 private _lackOfOutgoingTxRange;
  address public router;
  string private legacyName;
  mapping (address => string) private beneName;
  uint256 internal  MAX_PERCENT = 1000000;

  /* Modifier */
  modifier onlyRouter() {
    if (msg.sender != router) revert OnlyRouter();
    _;
  }

  modifier onlyOwner(address sender_) {
    if (sender_ != _owner) revert OnlyOwner();
    _;
  }

  modifier notInitialized() {
    if (_owner != address(0)) revert LegacyAlreadyInitialized();
    _;
  }

  modifier isActiveLegacy() {
    if (_isActive == 2) revert LegacyNotActive();
    _;
  }

  /* Public function */
  /**
   * @dev Get legacy infomation
   * @return legacyId
   * @return owner
   * @return isActive
   */
  function getLegacyInfo() public view returns (uint256, address, uint128) {
    return (_legacyId, _owner, _isActive);
  }

  /**
   * @dev Get legacy owner
   */
  function getLegacyOwner() public view returns (address) {
    return _owner;
  }

  /**
   * @dev Get is active legacy
   */
  function getIsActiveLegacy() public view returns (uint128) {
    return _isActive;
  }

  /**
   * @dev Get lackOfOutgoingTxRange
   */
  function getActivationTrigger() public view returns (uint256) {
    return _lackOfOutgoingTxRange;
  }

  /* Internal function */
  /**
   * @dev Set legacy info
   * @param legacyId_ legacy id
   * @param owner_ legacy owner
   * @param isActive_ isActive
   * @param lackOfOutgoingTxRange_ lackOfOutgoingTxRange
   * @param router_ router
   */
  function _setLegacyInfo(uint256 legacyId_, address owner_, uint128 isActive_, uint256 lackOfOutgoingTxRange_, address router_) internal {
    _legacyId = legacyId_;
    _owner = owner_;
    _isActive = isActive_;
    _lackOfOutgoingTxRange = lackOfOutgoingTxRange_;
    router = router_;
  }

  /**
   * @dev Set lackOfOutgoingTxRange legacy
   * @param lackOfOutgoingTxRange_  lackOfOutgoingTxRange
   */
  function _setActivationTrigger(uint256 lackOfOutgoingTxRange_) internal {
    _lackOfOutgoingTxRange = lackOfOutgoingTxRange_;
  }

  /**
   * @dev Inactive legacy
   */
  function _setLegacyToInactive() internal {
    _isActive = 2;
  }

  function _setLegacyName(string calldata _legacyName) internal {
    legacyName = _legacyName;
  }

  function _setBeneNickname(address beneAddress, string calldata _beneName) internal {
    beneName[beneAddress] = _beneName;
  }

  function _deleteBeneName(address beneAddress) internal {
    delete beneName[beneAddress];
  }

  function getLegacyId() public view returns (uint256) {
    return _legacyId;
  }

  ///@dev false if legacy has been deleted or activate
  function isLive() public view virtual returns (bool) {}

  ///@dev return beneficiary address  list
  function getLegacyBeneficiaries() public view virtual returns (address[] memory beneficiaries, address layer2, address layer3) {}

  ///@dev get the timestamp when activation can be triggered
  function getTriggerActivationTimestamp() public view virtual returns (uint256 beneficiariesTrigger, uint256 layer2Trigger, uint256 layer3Trigger) {}

  ///@dev return current layer for all legacy types
  function getLayer() public view virtual returns (uint8) {
    return 1; //default layer
  }

  function getLegacyName() public view returns (string memory) {
    return legacyName;
  }

  function getLastTimestamp () public virtual view returns (uint256) {}

  function getBeneNickname(address beneAddress) public view returns (string memory){
    return beneName[beneAddress];
  }
}

contracts/common/LegacyDeployer.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

import {SafeGuard} from "../SafeGuard.sol";
import {TransferLegacy} from "../forwarding/TransferLegacyContract.sol";
import {TransferEOALegacy} from "../forwarding/TransferLegacyEOAContract.sol";
import {MultisigLegacy} from "../inheritance/MultisigLegacyContract.sol";
import {ILegacyDeployer} from "../interfaces/ILegacyDeployer.sol";
import "@openzeppelin/contracts/utils/Create2.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

contract LegacyDeployer is OwnableUpgradeable, ILegacyDeployer {
  address public multisigLegacyRouter;
  address public transferLegacyRouter;
  address public transferEOALegacyRouter;

  mapping(address => uint256) internal nonceByUsers;

  error InvalidParam();

  modifier onlyRouter() {
    require(
      msg.sender == transferLegacyRouter || msg.sender == transferEOALegacyRouter || msg.sender == multisigLegacyRouter || msg.sender == owner(),
      "Router only"
    );
    _;
  }
  function initialize() public initializer {
    __Ownable_init(msg.sender);
  }

  function setParams(address _multisigLegacyRouter, address _transferLegacyRouter, address _transferEOALegacyRouter) public onlyOwner {
    if (_multisigLegacyRouter == address(0) || _transferLegacyRouter == address(0) || _transferEOALegacyRouter == address(0)) revert InvalidParam();
    multisigLegacyRouter = _multisigLegacyRouter;
    transferLegacyRouter = _transferLegacyRouter;
    transferEOALegacyRouter = _transferEOALegacyRouter;
  }

  function getNextAddress(bytes calldata byteCode, address user) external view returns (address nextLegacy) {
    uint256 nextNonce = nonceByUsers[user] + 1;
    bytes32 salt = keccak256(abi.encodePacked(user, nextNonce));
    bytes32 bytecodeHash = keccak256(byteCode);
    return Create2.computeAddress(salt, bytecodeHash);
  }

  function createLegacy(bytes calldata byteCode, address user) external onlyRouter returns (address legacyAddress, address guardAddress) {
    nonceByUsers[user] += 1;
    bytes32 salt = keccak256(abi.encodePacked(user, nonceByUsers[user]));
    legacyAddress = Create2.deploy(0, salt, byteCode);
    if (msg.sender != transferEOALegacyRouter) {
      guardAddress = Create2.deploy(0, salt, type(SafeGuard).creationCode);
    }
  }
}

contracts/common/LegacyFactory.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

import "@openzeppelin/contracts/utils/Create2.sol";
import {ISafeWallet} from "../interfaces/ISafeWallet.sol";
import {ILegacyDeployer} from "../interfaces/ILegacyDeployer.sol";
contract LegacyFactory {

  bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
  
  /* Error */
  error LegacyNotFound();
  error GuardNotFound();
  error GuardSafeWalletInvalid();
  error ModuleSafeWalletInvalid();

  /* State variable */
  uint256 internal _legacyId;
  address public legacyDeployerContract;
  mapping(uint256 => address) public legacyAddresses;
  mapping(uint256 => address) public guardAddresses;
  mapping(address => bool) internal isCreateLegacy;

  /* Internal function */
  /**
   * @dev get next address create
   * @param bytecode_  byte code
   * @param sender_  sender
   */
  function _getNextAddress(bytes memory bytecode_, address sender_) internal view returns (address) {
   return  ILegacyDeployer(legacyDeployerContract).getNextAddress(bytecode_ ,sender_);
  }


  /**
   * @dev create legacy and guard
   * @param legacyBytecode_  legacy byte code
   * @param sender_ sender
   * @return legacyId
   * @return legacyAddress
   * @return guardAddress
   */
  function _createLegacy(bytes memory legacyBytecode_, address sender_) internal returns (uint256, address, address) {
    _legacyId += 1;
    (address legacyAddress, address guardAddress) = ILegacyDeployer(legacyDeployerContract).createLegacy(legacyBytecode_,sender_);
    legacyAddresses[_legacyId] = legacyAddress;
    guardAddresses[_legacyId] = guardAddress;
    isCreateLegacy[sender_] = true;
    return (_legacyId, legacyAddress, guardAddress);
  }

  /**
   * @dev Check whether legacy existed
   * @param legacyId_  legacy id
   */
  function _checkLegacyExisted(uint256 legacyId_) internal view returns (address legacyAddress) {
    legacyAddress = legacyAddresses[legacyId_];
    if (legacyAddress == address(0)) revert LegacyNotFound();
  }

  /**
   * @dev Check whether guard existed
   * @param legacyId_ legacy id
   */
  function _checkGuardExisted(uint256 legacyId_) internal view returns (address guardAddress) {
    guardAddress = guardAddresses[legacyId_];
    if (guardAddress == address(0)) revert LegacyNotFound();
  }

  function _isCreateLegacy(address sender_) internal view returns (bool) {
    return isCreateLegacy[sender_];
  }

    /**
   * @dev Check whether the safe wallet invalid. Ensure safe wallet exist guard and legacy was created by system.
   * @param legacyId_ legacy id
   * @param safeWallet_ safe wallet address
   */
  function _checkSafeWalletValid(uint256 legacyId_, address safeWallet_) internal view {
    address guardAddress = _checkGuardExisted(legacyId_);
    address moduleAddress = _checkLegacyExisted(legacyId_);

    //Check safe wallet exist guard created by system
    bytes memory guardBytes = ISafeWallet(safeWallet_).getStorageAt(uint256(GUARD_STORAGE_SLOT), 1);
    bytes32 rawBytes = abi.decode(guardBytes, (bytes32));
    address guardSafeWalletAddress = address(uint160(uint256(rawBytes)));

     if (guardAddress != guardSafeWalletAddress) revert GuardSafeWalletInvalid();

    //Check safe wallet exist legacy created by system
    if (ISafeWallet(safeWallet_).isModuleEnabled(moduleAddress) == false) revert ModuleSafeWalletInvalid();
  }

  /**
   * @dev Check whether safe wallet exist guard.
   * @param safeWallet_ safe wallet address
   * @return bool true if guard exist, false otherwise
   */
  function _checkExistGuardInSafeWallet(address safeWallet_) internal view returns (bool) {
    bytes memory guardBytes = ISafeWallet(safeWallet_).getStorageAt(uint256(GUARD_STORAGE_SLOT), 1);
    bytes32 rawBytes = abi.decode(guardBytes, (bytes32));
    address guardSafeWalletAddress = address(uint160(uint256(rawBytes)));
    if (guardSafeWalletAddress == address(0)) return false;
    return true;
  }

  /**
   * @dev Check whether signer is signer of safewallet.
   * @param safeWallet_  safe wallet address
   * @param signer_ signer address
   */
  function _checkSignerIsOwnerOfSafeWallet(address safeWallet_, address signer_) internal view returns (bool) {
    address[] memory signers = ISafeWallet(safeWallet_).getOwners();
    for (uint256 i = 0; i < signers.length;) {
      if (signer_ == signers[i]) {
        return true;
      }
      unchecked { ++i; }
    }
    return false;
  }


}

contracts/common/LegacyRouter.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

contract LegacyRouter {
  /* State variable */
  // guard storage slot in safe wallet
  uint256 public constant BENEFICIARIES_LIMIT = 32;

  /* Internal function */
  /**
   * @dev Check beneficiaries limit
   * @param numBeneficiaries_ number of beneficiaries
   */
  function _checkNumBeneficiariesLimit(uint256 numBeneficiaries_) internal pure returns (bool) {
    if (numBeneficiaries_ == 0 || numBeneficiaries_ > BENEFICIARIES_LIMIT) {
      return false;
    }
    return true;
  }
}

contracts/forwarding/TransferLegacyContract.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Enum} from "@safe-global/safe-smart-account/contracts/common/Enum.sol";

import {GenericLegacy} from "../common/GenericLegacy.sol";

import {ISafeGuard} from "../interfaces/ISafeGuard.sol";
import {ISafeWallet} from "../interfaces/ISafeWallet.sol";
import {TransferLegacyStruct} from "../libraries/TransferLegacyStruct.sol";

import {IPremiumSetting} from "../interfaces/IPremiumSetting.sol";
import {ITransferLegacy} from "../interfaces/ITransferLegacyContract.sol";
import {IPayment} from "../interfaces/IPayment.sol";
import {IUniswapV2Router02} from "../interfaces/IUniswapV2Router02.sol";
import {NotifyLib} from "../libraries/NotifyLib.sol";

contract TransferLegacy is GenericLegacy, ITransferLegacy {
  using EnumerableSet for EnumerableSet.AddressSet;
  using SafeERC20 for IERC20;
  /* Error */
  error NotBeneficiary();
  error DistributionUserInvalid();
  error DistributionAssetInvalid();
  error AssetInvalid();
  error PercentInvalid();
  error NotEnoughContitionalActive();
  error ExecTransactionFromModuleFailed();
  error LayerInvalid();
  error NotPremium();
  error NeedtoSetLayer2();
  error AlreadyBeneficiary();
  error DelayAndDistributionInvalid();
  error InvalidGuard();
  /* State variable */
  uint128 public constant LEGACY_TYPE = 2;
  uint128 public constant MAX_TRANSFER =  2;
  uint256 public adminFeePercent;
  address public paymentContract;

  EnumerableSet.AddressSet private _beneficiariesSet;
  mapping(address beneficiaries => uint256) private _distributions;
  address private _layer2Beneficiary;
  uint256 private _layer2Distribution;
  address private _layer3Beneficiary;
  uint256 private _layer3Distribution;

  uint256 public delayLayer2;
  uint256 public delayLayer3;

  IPremiumSetting public premiumSetting;
  address public creator;
  address public safeGuard;
  address public uniswapRouter; // Uniswap router address for swapping
  address public weth; // WETH address for swapping

  /* View functions to support premium */

  ///@dev false if legacy has been deleted or activated
  function isLive() public view override returns (bool) {
    return getIsActiveLegacy() == 1;
  }

  ///@dev get the timestamp when activation can be triggered
  function getTriggerActivationTimestamp() public view override returns (uint256, uint256, uint256) {
    //last tx of safe wallet linked with this legacy
    // find guard address for this contract
    uint256 lastTimestamp = ISafeGuard(safeGuard).getLastTimestampTxs();
    uint256 lackOfOutgoingTxRange = uint256(getActivationTrigger());
    uint256 beneficiariesTrigger = lastTimestamp + lackOfOutgoingTxRange;
    uint256 layer2Trigger = beneficiariesTrigger + delayLayer2;
    uint256 layer3Trigger = layer2Trigger + delayLayer3;

    return (beneficiariesTrigger, layer2Trigger, layer3Trigger);
  }

  function getLegacyBeneficiaries() public view override returns (address[] memory, address, address) {
    return (_beneficiariesSet.values(), _layer2Beneficiary, _layer3Beneficiary);
  }

  function getLayer() public view override(GenericLegacy, ITransferLegacy) returns (uint8) {
    return getCurrentLayer(safeGuard);
  }

  function getLastTimestamp() public view override returns (uint256) {
    return ISafeGuard(safeGuard).getLastTimestampTxs();
  }

  function _swapAdminFee(address token, uint256 amountIn) internal {
    // Approve token for router
    IERC20(token).forceApprove(uniswapRouter, amountIn);

    address[] memory path = new address[](2);
    path[0] = token;
    path[1] = weth;

    try
      IUniswapV2Router02(uniswapRouter).swapExactTokensForETH(
        amountIn,
        0, // accept any amount of ETH
        path,
        paymentContract,
        block.timestamp + 300
      )
    {} catch {
      IERC20(token).safeTransfer(paymentContract, amountIn);
    }
  }

  /* View function */
  /**
   * @dev get beneficiaries list
   */
  function getBeneficiaries(address bene_) internal view returns (address[] memory) {
    uint8 currentLayer_ = getBeneficiaryLayer(bene_);
    if (currentLayer_ == 1) return _beneficiariesSet.values();
    else if (currentLayer_ == 2) {
      address[] memory beneficiaries = new address[](1);
      beneficiaries[0] = _layer2Beneficiary;
      return beneficiaries;
    } else if (currentLayer_ == 3) {
      address[] memory beneficiaries = new address[](1);
      beneficiaries[0] = _layer3Beneficiary;
      return beneficiaries;
    } else revert LayerInvalid();
  }

  function getDistribution(uint8 layer, address beneficiary) public view returns (uint256) {
    if (layer == 1) {
      return _distributions[beneficiary];
    } else if (layer == 2) {
      if (beneficiary == _layer2Beneficiary) {
        return _layer2Distribution;
      } else {
        return 0;
      }
    } else if (layer == 3) {
      if (beneficiary == _layer3Beneficiary) {
        return _layer3Distribution;
      } else {
        return 0;
      }
    } else {
      return 0;
    }
  }

  /**
   * @dev Get the layer of a specific beneficiary
   * @param beneficiary The address of the beneficiary
   * @return uint8 The layer of the beneficiary (1 for First-line, 2 for Second-line, 3 for Third-line, 0 if not a beneficiary)
   */
  function getBeneficiaryLayer(address beneficiary) public view returns (uint8) {
    if (_distributions[beneficiary] > 0) {
      return 1;
    } else if (beneficiary == _layer2Beneficiary && _layer2Distribution > 0) {
      return 2;
    } else if (beneficiary == _layer3Beneficiary && _layer3Distribution > 0) {
      return 3;
    }
    return 0;
  }

  function getCurrentLayer(address guardAddress_) internal view returns (uint8) {
    uint256 ts = block.timestamp;
    uint256 _lastTimestamp = ISafeGuard(guardAddress_).getLastTimestampTxs();
    uint256 lackOfOutgoingTxRange = getActivationTrigger();
    uint256 base = (_lastTimestamp + lackOfOutgoingTxRange);
    if (ts >= base + delayLayer2 + delayLayer3 && delayLayer3 != 0) {
      return 3;
    } else if (ts >= base + delayLayer2 && delayLayer2 != 0) {
      return 2;
    } else {
      return 1;
    }
  }

  /**
   * @dev Check activation conditions
   * @param guardAddress_ guard
   * @return bool true if eligible for activation, false otherwise
   */
  function checkActiveLegacy(address guardAddress_) external view returns (bool) {
    return _checkActiveLegacy(guardAddress_);
  }

  /* Main function */
  /**
   * @dev Intialize info legacy
   * @param legacyId_ legacy id
   * @param owner_ owner of legacy
   * @param distributions_ ditributions list
   * @param config_ include lackOfOutgoingTxRange
   */
  function initialize(
    uint256 legacyId_,
    address owner_,
    TransferLegacyStruct.Distribution[] calldata distributions_,
    TransferLegacyStruct.LegacyExtraConfig calldata config_,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_,
    address _premiumSetting,
    address _creator,
    address _safeGuard,
    address _uniswapRouter,
    address _weth,
    address _paymentContract,
    string[] calldata nicknames,
    string calldata nickName2,
    string calldata nickName3
  ) external notInitialized returns (uint256 numberOfBeneficiaries) {
    // if (owner_ == address(0)) revert OwnerInvalid();
    _setLegacyInfo(legacyId_, owner_, 1, config_.lackOfOutgoingTxRange, msg.sender);
    uniswapRouter = _uniswapRouter;
    weth = _weth;
    premiumSetting = IPremiumSetting(_premiumSetting);
    creator = _creator;
    safeGuard = _safeGuard;
    paymentContract = _paymentContract;
    adminFeePercent = IPayment(_paymentContract).getFee(); //always <= 10000

    // Check duplicates across layers BEFORE setting anything
    address l2User = layer2Distribution_.user;
    address l3User = layer3Distribution_.user;

    for (uint256 i = 0; i < distributions_.length; ++i) {
      address user = distributions_[i].user;
      if (user == address(0)) continue;

      if (user == l2User || user == l3User) {
        revert AlreadyBeneficiary();
      }
    }

    if (premiumSetting.isPremium(creator)) {
      delayLayer2 = config_.delayLayer2;
      delayLayer3 = config_.delayLayer3;
      _setLayer23Distributions(2, nickName2, layer2Distribution_);
      _setLayer23Distributions(3, nickName3, layer3Distribution_);
      if (!_checkDelayAndDistribution()) revert DelayAndDistributionInvalid();
    } else {
      // Check input values before assigning them to state
      if (
        config_.delayLayer2 != 0 ||
        config_.delayLayer3 != 0 ||
        layer2Distribution_.percent != 0 ||
        layer3Distribution_.percent != 0 ||
        layer2Distribution_.user != address(0) ||
        layer3Distribution_.user != address(0)
      ) {
        revert NotPremium();
      }

      // Do not assign state variables
    }

    numberOfBeneficiaries = _setDistributions(owner_, distributions_, nicknames);
  }

  function _checkDelayAndDistribution() internal view returns (bool) {
    // Case 1: All default values (for non-premium users)
    if (delayLayer2 == 0 && _layer2Distribution == 0 && delayLayer3 == 0 && _layer3Distribution == 0) {
      return true;
    }

    // Case 2: Only layer2 is set (premium users)
    if (delayLayer2 != 0 && _layer2Distribution == MAX_PERCENT && delayLayer3 == 0 && _layer3Distribution == 0) {
      return true;
    }

    // Case 3: Both layers are set (premium users)
    if (delayLayer2 != 0 && _layer2Distribution == MAX_PERCENT && delayLayer3 != 0 && _layer3Distribution == MAX_PERCENT) {
      return true;
    }

    return false;
  }

  function _setLayer23Distributions(uint8 layer_, string calldata nickname, TransferLegacyStruct.Distribution calldata distribution_) private {
    uint256 _distributionPercentage;
    address _beneficiary;
    if (distribution_.percent == 0) {
      _distributionPercentage = 0;
      _beneficiary = address(0);
    } else {
      _distributionPercentage = MAX_PERCENT;
      if (distribution_.user == address(0)) revert DistributionUserInvalid();
      _beneficiary = distribution_.user;
    }
    if (layer_ == 2) {
      if (_distributions[distribution_.user] != 0) revert AlreadyBeneficiary();
      _deleteBeneName(_layer2Beneficiary);
      _layer2Beneficiary = _beneficiary;
      _layer2Distribution = _distributionPercentage;
      _setBeneNickname(_layer2Beneficiary, nickname);
    } else {
      if (_layer2Distribution != MAX_PERCENT && _distributionPercentage != 0) revert NeedtoSetLayer2();
      if (_distributionPercentage != 0) {
        if (_layer2Distribution != MAX_PERCENT) revert NeedtoSetLayer2();
        if (_distributions[distribution_.user] != 0 || _layer2Beneficiary == distribution_.user) revert AlreadyBeneficiary();
      }
      _deleteBeneName(_layer3Beneficiary);
      _layer3Beneficiary = _beneficiary;
      _layer3Distribution = _distributionPercentage;
      _setBeneNickname(_layer3Beneficiary, nickname);
    }
  }

  /**
   * @dev set distributions[]
   * @param sender_  sender address
   * @param distributions_ ditributions
   */
  function setLegacyDistributions(
    address sender_,
    TransferLegacyStruct.Distribution[] calldata distributions_,
    string[] calldata nicknames_
  ) external onlyRouter onlyOwner(sender_) isActiveLegacy returns (uint256 numberOfBeneficiaries) {
    _clearDistributions();
    numberOfBeneficiaries = _setDistributions(sender_, distributions_, nicknames_);
  }

  function setDelayAndLayer23Distributions(
    address sender_,
    uint256 delayLayer2_,
    uint256 delayLayer3_,
    string calldata nickName2,
    string calldata nickName3,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_
  ) external onlyRouter onlyOwner(sender_) isActiveLegacy {
    // Check if user is premium
    bool isPremium = premiumSetting.isPremium(creator);

    if (!isPremium) {
      // For non-premium users, only allow setting to default values
      if (
        delayLayer2_ != 0 ||
        delayLayer3_ != 0 ||
        layer2Distribution_.percent != 0 ||
        layer3Distribution_.percent != 0 ||
        layer2Distribution_.user != address(0) ||
        layer3Distribution_.user != address(0)
      ) {
        revert NotPremium();
      }
      // Don't change values for non-premium users
      return;
    }

    // For premium users, proceed with normal logic
    delayLayer2 = delayLayer2_;
    delayLayer3 = delayLayer3_;

    _setLayer23Distributions(2, nickName2, layer2Distribution_);

    bool skipCheck = true;
    if (layer3Distribution_.percent > 0 && layer3Distribution_.user != address(0)) {
      if (_layer2Beneficiary == layer3Distribution_.user || _distributions[layer3Distribution_.user] != 0) {
        revert AlreadyBeneficiary();
      }
      _deleteBeneName(_layer3Beneficiary);
      _layer3Beneficiary = layer3Distribution_.user;
      _layer3Distribution = MAX_PERCENT;
      _setBeneNickname(_layer3Beneficiary, nickName3);
      skipCheck = false;
    } else {
      _layer3Beneficiary = address(0);
      _layer3Distribution = 0;
    }

    if (!skipCheck && !_checkDelayAndDistribution()) {
      revert DelayAndDistributionInvalid();
    }
  }

  function setDelayLayer23(address sender_, uint256 delayLayer2_, uint256 delayLayer3_) external onlyRouter onlyOwner(sender_) isActiveLegacy {
    if (premiumSetting.isPremium(sender_)) {
      delayLayer2 = delayLayer2_;
      delayLayer3 = delayLayer3_;
      if (!_checkDelayAndDistribution()) revert DelayAndDistributionInvalid();
    }
  }

  function setLayer23Distributions(
    address sender_,
    uint8 layer_,
    string calldata nickname,
    TransferLegacyStruct.Distribution calldata distribution_
  ) external onlyRouter onlyOwner(sender_) isActiveLegacy {
    if (layer_ < 2 || layer_ > 3) revert LayerInvalid();
    if (distribution_.user == address(0)) revert DistributionUserInvalid();
    if (!premiumSetting.isPremium(creator)) revert NotPremium();

    _setLayer23Distributions(layer_, nickname, distribution_);
    if (!_checkDelayAndDistribution()) revert DelayAndDistributionInvalid();
  }

  /**
   * @dev Set lackOfOutgoingTxRange legacy
   * @param sender_  sender
   * @param lackOfOutgoingTxRange_  lackOfOutgoingTxRange
   */
  function setActivationTrigger(address sender_, uint256 lackOfOutgoingTxRange_) external onlyRouter onlyOwner(sender_) isActiveLegacy {
    _setActivationTrigger(lackOfOutgoingTxRange_);
  }

  /**
   * @param guardAddress_  guard address
   */
  function activeLegacy(address guardAddress_, address[] calldata assets_, bool isETH_, address bene_) external onlyRouter {
    if (_checkActiveLegacy(guardAddress_)) {
      if (getIsActiveLegacy() == 1) {
        _setLegacyToInactive();
      }
      _transferAssetToBeneficiaries(assets_, isETH_, bene_);
    } else {
      revert NotEnoughContitionalActive();
    }
  }

  function setLegacyName(string calldata legacyName_) external onlyRouter isActiveLegacy {
    _setLegacyName(legacyName_);
  }

  /* Utils function */

  /**
   * @dev Check activation conditions
   * @param guardAddress_ guard
   * @return bool true if eligible for activation, false otherwise
   */
  function _checkActiveLegacy(address guardAddress_) private view returns (bool) {
    uint256 lastTimestamp = ISafeGuard(guardAddress_).getLastTimestampTxs();
    uint256 lackOfOutgoingTxRange = uint256(getActivationTrigger());
    if (lastTimestamp + lackOfOutgoingTxRange > block.timestamp) {
      return false;
    }
    return true;
  }

  /**
   * @dev set ditribution list
   * @param distributions_  distributions list
   * @return numberOfBeneficiaries number of beneficiaries
   */
  function _setDistributions(
    address owner_,
    TransferLegacyStruct.Distribution[] calldata distributions_,
    string[] calldata nicknames
  ) internal returns (uint256 numberOfBeneficiaries) {
    uint256 totalPercent = 0;
    for (uint256 i = 0; i < distributions_.length; ) {
      _checkDistribution(owner_, distributions_[i]);
      _beneficiariesSet.add(distributions_[i].user);
      _setBeneNickname(distributions_[i].user, nicknames[i]);
      _distributions[distributions_[i].user] = distributions_[i].percent;
      totalPercent += distributions_[i].percent;
      unchecked {
        i++;
      }
    }
    if (totalPercent != MAX_PERCENT) revert PercentInvalid();

    numberOfBeneficiaries = _beneficiariesSet.length();
  }

  /**
   * @dev clear distributions list
   */
  function _clearDistributions() internal {
    address[] memory beneficiaries = _beneficiariesSet.values();
    for (uint256 i = 0; i < beneficiaries.length; ) {
      _deleteBeneName(beneficiaries[i]);
      _beneficiariesSet.remove(beneficiaries[i]);
      _distributions[beneficiaries[i]] = 0;
      unchecked {
        i++;
      }
    }
  }

  /**
   * @dev check distribution
   * @param owner_ safe wallet address
   * @param distribution_ distribution
   */
  function _checkDistribution(address owner_, TransferLegacyStruct.Distribution calldata distribution_) private view {
    if (distribution_.percent == 0 || distribution_.percent > MAX_PERCENT) revert DistributionAssetInvalid();
    if (distribution_.user == address(0) || distribution_.user == owner_) revert DistributionUserInvalid();
  }

  /**
   * @dev transfer asset to beneficiaries
   */
  function _transferAssetToBeneficiaries(address[] calldata assets_, bool isETH_, address bene_) private {
    address safeAddress = getLegacyOwner();
    address[] memory beneficiaries = getBeneficiaries(bene_);
    uint8 beneLayer = getBeneficiaryLayer(bene_);
    uint256 n = assets_.length;
    uint256 maxTransfer = MAX_TRANSFER;

    if (isETH_) {
      maxTransfer = maxTransfer - beneficiaries.length;
    }
    //actual number of assets claimed in this tranasaction
    bool remaining = false;
    if (n * beneficiaries.length > maxTransfer) {
      n = maxTransfer / beneficiaries.length;
      remaining = true;
    }

    //prepare data to send mail
    NotifyLib.BeneReceived[] memory receipt = new NotifyLib.BeneReceived[](beneficiaries.length);
    NotifyLib.ListAsset[] memory summary = new NotifyLib.ListAsset[](n + 1);
    string memory symbol;
    for (uint256 i = 0; i < beneficiaries.length; ) {
      receipt[i].beneAddress = beneficiaries[i];
      receipt[i].name = getBeneNickname(beneficiaries[i]);
      string[] memory listAssetName = new string[](n + 1); // +1 for ETH
      uint256[] memory listAmount = new uint256[](n + 1);
      receipt[i].listAssetName = listAssetName;
      receipt[i].listAmount = listAmount;
      unchecked {
        i++;
      }
    }

    // Handle ETH transfer if isETH_ is true
    if (isETH_) {
      uint256 totalAmountEth = address(safeAddress).balance;
      if (totalAmountEth > 0) {
        uint256 fee = (totalAmountEth * adminFeePercent) / 10000;
        uint256 distributableEth = totalAmountEth - fee;
        if (fee > 0) _transferEthToBeneficiary(safeAddress, paymentContract, fee);

        symbol = "ETH";
        summary[n] = NotifyLib.ListAsset({listToken: address(0), listAmount: totalAmountEth, listAssetName: symbol});
        
        uint256 processedAmountETH = 0;
        for (uint256 i = 0; i < beneficiaries.length; ) {
          uint256 amount = i != beneficiaries.length - 1
            ? (distributableEth * getDistribution(beneLayer, beneficiaries[i])) / MAX_PERCENT
            : distributableEth-processedAmountETH;
          uint256 amountSent = _transferEthToBeneficiary(safeAddress, beneficiaries[i], amount);
          receipt[i].listAssetName[n] = symbol;
          receipt[i].listAmount[n] = amountSent;
          processedAmountETH+=amount;

          unchecked {
            i++;
          }
        }
      }
    }

    for (uint256 i = 0; i < n; ) {
      address token = assets_[i];
      uint256 totalAmountErc20 = IERC20(token).balanceOf(safeAddress);
      if (totalAmountErc20 > 0) {
        uint256 fee = (totalAmountErc20 * adminFeePercent) / 10000;
        uint256 distributable = totalAmountErc20 - fee;

        symbol = IERC20Metadata(token).symbol();
        summary[i] = NotifyLib.ListAsset({listToken: token, listAmount: totalAmountErc20, listAssetName: symbol});
        if (fee > 0) {
          uint256 balanceBefore = IERC20(token).balanceOf(address(this));
          _transferErc20ToBeneficiary(token, safeAddress, address(this), fee);
          uint256 actualFeeReceived =  IERC20(token).balanceOf(address(this)) - balanceBefore;
          _swapAdminFee(token, actualFeeReceived);
        }

        uint256 processedAmountERC20 = 0;
        for (uint256 j = 0; j < beneficiaries.length; ) {
          uint256 amount = j != beneficiaries.length - 1
            ? (distributable * getDistribution(beneLayer, beneficiaries[j])) / MAX_PERCENT
            : distributable - processedAmountERC20;
          if (amount > 0) {
            uint256 amountSent = _transferErc20ToBeneficiary(token, safeAddress, beneficiaries[j], amount);
            receipt[j].listAssetName[i] = symbol;
            receipt[j].listAmount[i] = amountSent;
            processedAmountERC20+=amount;
          }
          unchecked {
            j++;
          }
        }
      }

      unchecked {
        i++;
      }
    }
    // send email
    try 
    IPremiumSetting(premiumSetting).triggerActivationTransferLegacy(summary, receipt, remaining) 
    {} catch {
      emit EmailActivatedNotCompleted(address(this));
    }
  
  }
  /**
   * @dev transfer erc20 token to beneficiaries
   * @param erc20Address_  erc20 token address
   * @param from_ safe wallet address
   * @param to_ beneficiary address
   */
  function _transferErc20ToBeneficiary(address erc20Address_, address from_, address to_, uint256 amount) private returns(uint256 amountSent) {
    bytes memory transferErc20Data = abi.encodeWithSignature("transfer(address,uint256)", to_, amount);
    (bool transferErc20Success, bytes memory returnData) = ISafeWallet(from_).execTransactionFromModuleReturnData(
      erc20Address_,
      0,
      transferErc20Data,
      Enum.Operation.Call
    );

    if (!transferErc20Success || (returnData.length != 0 && !abi.decode(returnData, (bool)))) return 0;
    return amount;

  }

  /**
   * @dev transfer eth to beneficiaries
   * @param from_ safe wallet address
   * @param to_ beneficiary address
   */
  function _transferEthToBeneficiary(address from_, address to_, uint256 amount) private returns (uint256 amountSent) {
    bool transferEthSuccess = ISafeWallet(from_).execTransactionFromModule(to_, amount, "", Enum.Operation.Call);
    if (!transferEthSuccess) return 0;
    return amount;
  }
}

contracts/forwarding/TransferLegacyContractRouter.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

import {LegacyRouter} from "../common/LegacyRouter.sol";
import {LegacyFactory} from "../common/LegacyFactory.sol";
import {TransferLegacy} from "./TransferLegacyContract.sol";
import {SafeGuard} from "../SafeGuard.sol";
import {ITransferLegacy} from "../interfaces/ITransferLegacyContract.sol";
import {ISafeGuard} from "../interfaces/ISafeGuard.sol";
import {ISafeWallet} from "../interfaces/ISafeWallet.sol";
import {TransferLegacyStruct} from "../libraries/TransferLegacyStruct.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {EIP712LegacyVerifier} from "../term/VerifierTerm.sol";
import {IPremiumSetting} from "../interfaces/IPremiumSetting.sol";

contract TransferLegacyRouter is LegacyRouter, LegacyFactory, Initializable {
  address public premiumSetting;
  EIP712LegacyVerifier public verifier;
  address public paymentContract;
  address public uniswapRouter;
  address public weth;

  /* Error */
  error ExistedGuardInSafeWallet(address);
  error SignerIsNotOwnerOfSafeWallet();
  error NumBeneficiariesInvalid();
  error NumAssetsInvalid();
  error DistributionsInvalid();
  error ActivationTriggerInvalid();
  error OnlyBeneficaries();
  error SenderIsCreatedLegacy(address);
  error CannotClaim();
  error SafeWalletInvalid();

  /* Struct */
  struct LegacyMainConfig {
    string name;
    string note;
    string[] nickNames;
    TransferLegacyStruct.Distribution[] distributions;
  }

  /* Event */
  event TransferLegacyCreated(
    uint256 legacyId,
    address legacyAddress,
    address guardAddress,
    address creatorAddress,
    address safeAddress,
    LegacyMainConfig mainConfig,
    TransferLegacyStruct.LegacyExtraConfig extraConfig,
    uint256 timestamp
  );
  event TransferLegacyConfigUpdated(
    uint256 legacyId,
    LegacyMainConfig mainConfig,
    TransferLegacyStruct.LegacyExtraConfig extraConfig,
    uint256 timestamp
  );
  event TransferLegacyDistributionUpdated(uint256 legacyId, string[] nickNames, TransferLegacyStruct.Distribution[] distributions, uint256 timestamp);
  event TransferLegacyTriggerUpdated(uint256 legacyId, uint128 lackOfOutgoingTxRange, uint256 timestamp);
  event TransferLegacyNameNoteUpdated(uint256 legacyId, string name, string note, uint256 timestamp);
  event TransferLegacyActivated(uint256 legacyId, uint8 layer, uint256 timestamp);
  event TransferLegacyLayer23DistributionUpdated(
    uint256 legacyId,
    uint8 layer,
    string nickNames,
    TransferLegacyStruct.Distribution distribution,
    uint256 timestamp
  );
  event TransferLegacyLayer23Created(uint256 legacyId, uint8 layer, TransferLegacyStruct.Distribution distribution, string nickName);

  /* Modifier */
  modifier onlySafeWallet(uint256 legacyId_) {
    _checkSafeWalletValid(legacyId_, msg.sender);
    _;
  }

    constructor () {
    _disableInitializers();
  }

  function initialize(address _deployerContract, address _premiumSetting, address _verifier, address _paymentContract, address router_, address weth_) external initializer {
    legacyDeployerContract = _deployerContract;
    premiumSetting = _premiumSetting;
    verifier = EIP712LegacyVerifier(_verifier);
    paymentContract = _paymentContract;
    uniswapRouter = router_;
    weth = weth_;
  }

  /**
   * @dev Get next legacy address that would be created for a sender
   * @param sender_ The address of the sender
   * @return address The next legacy address that would be created
   */
  function getNextLegacyAddress(address sender_) external view returns (address) {
    return _getNextAddress(type(TransferLegacy).creationCode, sender_);
  }

  /**

  /* External function */

  /**
   * @dev Check activation conditions. This activation conditions is current time >= last transaction of safe wallet + lackOfOutgoingTxRange.
   * @param legacyId_ legacy id
   * @return bool true if eligible for activation, false otherwise
   */
  function checkActiveLegacy(uint256 legacyId_) external view returns (bool) {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    address guardAddress = _checkGuardExisted(legacyId_);

    return ITransferLegacy(legacyAddress).checkActiveLegacy(guardAddress);
  }

  /**
   * @dev create new legacy and guard
   * @param safeWallet   safe wallet address
   * @param mainConfig_  include name, note, nickname [], distributions[]
   * @param extraConfig_  include lackOfOutgoingTxRange
   * @return address legacy address
   * @return address guard address
   */
  function createLegacy(
    address safeWallet,
    LegacyMainConfig calldata mainConfig_,
    TransferLegacyStruct.LegacyExtraConfig calldata extraConfig_,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_,
    string calldata nickName2,
    string calldata nickName3,
    uint256 signatureTimestamp,
    bytes calldata agreementSignature
  ) external returns (address, address) {
    if (mainConfig_.distributions.length != mainConfig_.nickNames.length || mainConfig_.distributions.length == 0) revert DistributionsInvalid();
    if (safeWallet == address(0)) revert SafeWalletInvalid();
    if (_checkExistGuardInSafeWallet(safeWallet)) revert ExistedGuardInSafeWallet(safeWallet);
    if (!_checkSignerIsOwnerOfSafeWallet(safeWallet, msg.sender)) revert SignerIsNotOwnerOfSafeWallet();
    if (extraConfig_.lackOfOutgoingTxRange == 0) revert ActivationTriggerInvalid();

    (uint256 newLegacyId, address legacyAddress, address guardAddress) = _createLegacy(
      type(TransferLegacy).creationCode,
      msg.sender
    );

    verifier.storeLegacyAgreement(msg.sender, legacyAddress, signatureTimestamp, agreementSignature);

    uint256 numberOfBeneficiaries = ITransferLegacy(legacyAddress).initialize(
      newLegacyId,
      safeWallet,
      mainConfig_.distributions,
      extraConfig_,
      layer2Distribution_,
      layer3Distribution_,
      premiumSetting,
      msg.sender,
      guardAddress,
      uniswapRouter,
      weth,
      paymentContract,
      mainConfig_.nickNames,
      nickName2,
      nickName3
    );

    ITransferLegacy(legacyAddress).setLegacyName(mainConfig_.name);
   

    ISafeGuard(guardAddress).initialize(safeWallet);

    if (!_checkNumBeneficiariesLimit(numberOfBeneficiaries)) revert NumBeneficiariesInvalid();
    TransferLegacyStruct.LegacyExtraConfig memory _legacyExtraConfig = TransferLegacyStruct.LegacyExtraConfig({
      lackOfOutgoingTxRange: extraConfig_.lackOfOutgoingTxRange,
      delayLayer2: ITransferLegacy(legacyAddress).delayLayer2(),
      delayLayer3: ITransferLegacy(legacyAddress).delayLayer3()
    });

    emit TransferLegacyCreated(newLegacyId, legacyAddress, guardAddress, msg.sender, safeWallet, mainConfig_, _legacyExtraConfig, block.timestamp);

    //set private code for legacy of premium user
    IPremiumSetting(premiumSetting).setPrivateCodeAndCronjob(msg.sender, legacyAddress);

    // Emit layer2/3 creation event if configured
    uint256 distribution2 = ITransferLegacy(legacyAddress).getDistribution(2, layer2Distribution_.user);
    uint256 distribution3 = ITransferLegacy(legacyAddress).getDistribution(3, layer3Distribution_.user);

    if (distribution2 != 0) {
      emit TransferLegacyLayer23Created(newLegacyId, 2, layer2Distribution_, nickName2);
    }

    if (distribution3 != 0) {
      emit TransferLegacyLayer23Created(newLegacyId, 3, layer3Distribution_, nickName3);
    }

    return (legacyAddress, guardAddress);
  }

  /**
   * @dev set legacy config include distributions, lackOfOutGoingTxRange
   * @param legacyId_  legacy id
   * @param mainConfig_ include name, note, nickname [], distributions[]
   * @param extraConfig_ include lackOfOutgoingTxRange
   */
  function setLegacyConfig(
    uint256 legacyId_,
    LegacyMainConfig calldata mainConfig_,
    TransferLegacyStruct.LegacyExtraConfig calldata extraConfig_,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_,
    string calldata nickName2,
    string calldata nickName3
  ) external onlySafeWallet(legacyId_)  {
    address legacyAddress = _checkLegacyExisted(legacyId_);

    address owner = ITransferLegacy(legacyAddress).creator();

    bool isPremium = IPremiumSetting(premiumSetting).isPremium(owner);

    //Check ditribution length
    if (mainConfig_.distributions.length != mainConfig_.nickNames.length || mainConfig_.distributions.length == 0) revert DistributionsInvalid();

    if (_isCreateLegacy(msg.sender)) revert SenderIsCreatedLegacy(msg.sender);

    //Check invalid activation trigger
    if (extraConfig_.lackOfOutgoingTxRange == 0) revert ActivationTriggerInvalid();

    //Set distributions
    uint256 numberBeneficiaries = ITransferLegacy(legacyAddress).setLegacyDistributions(msg.sender, mainConfig_.distributions, mainConfig_.nickNames);

    //Check num beneficiaries and assets
    if (!_checkNumBeneficiariesLimit(numberBeneficiaries)) revert NumBeneficiariesInvalid();

    ITransferLegacy(legacyAddress).setActivationTrigger(msg.sender, extraConfig_.lackOfOutgoingTxRange);

    // Combine setting delay and layer 2/3 distribution (for premium user)
    ITransferLegacy(legacyAddress).setDelayAndLayer23Distributions(
      msg.sender,
      extraConfig_.delayLayer2,
      extraConfig_.delayLayer3,
      nickName2,
      nickName3,
      layer2Distribution_,
      layer3Distribution_
    );

    if (isPremium) {
      // Only emit events for premium users
      emit TransferLegacyLayer23DistributionUpdated(legacyId_, 2, nickName2, layer2Distribution_, block.timestamp);
      emit TransferLegacyLayer23DistributionUpdated(legacyId_, 3, nickName3, layer3Distribution_, block.timestamp);
    }

    TransferLegacyStruct.LegacyExtraConfig memory _legacyExtraConfig = TransferLegacyStruct.LegacyExtraConfig({
      lackOfOutgoingTxRange: extraConfig_.lackOfOutgoingTxRange,
      delayLayer2: ITransferLegacy(legacyAddress).delayLayer2(),
      delayLayer3: ITransferLegacy(legacyAddress).delayLayer3()
    });

    ITransferLegacy(legacyAddress).setLegacyName(mainConfig_.name); 

    emit TransferLegacyConfigUpdated(legacyId_, mainConfig_, _legacyExtraConfig, block.timestamp);
  }

  /**
   * @dev Set distributions[] legacy, call this function if only modify beneficiaries[], minRequiredSignatures to save gas for user.
   * @param legacyId_ legacy id
   * @param nickNames_  nick name[]
   * @param distributions_ ditributions[]
   */
  function setLegacyDistributions(
    uint256 legacyId_,
    string[] calldata nickNames_,
    TransferLegacyStruct.Distribution[] calldata distributions_
  ) external onlySafeWallet(legacyId_) {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    // Check distribution length
    if (distributions_.length != nickNames_.length || distributions_.length == 0) revert DistributionsInvalid();

    // Set distribution assets
    uint256 numberOfBeneficiaries = ITransferLegacy(legacyAddress).setLegacyDistributions(msg.sender, distributions_,nickNames_);
    //Check beneficiary limit
    if (!_checkNumBeneficiariesLimit(numberOfBeneficiaries)) revert NumBeneficiariesInvalid();

    emit TransferLegacyDistributionUpdated(legacyId_, nickNames_, distributions_, block.timestamp);
  }

  function setLayer23Distributions(
    uint256 legacyId_,
    uint8 layer_,
    string calldata nickname_,
    TransferLegacyStruct.Distribution calldata distribution_
  ) external onlySafeWallet(legacyId_) {
   _setLayer23Distributions(legacyId_, layer_, nickname_, distribution_);
  }

    function setBothLayer23Distributions(
    uint256 legacyId_,
    string calldata nicknameLayer2_,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    string calldata nicknameLayer3_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_
  ) external onlySafeWallet(legacyId_) {
    _setLayer23Distributions(legacyId_, 2, nicknameLayer2_, layer2Distribution_);
    _setLayer23Distributions(legacyId_, 3, nicknameLayer3_, layer3Distribution_);

  }

  /**
   * @dev set activation trigger time, call this function if only mofify lackOfOutgoingTxRange to save gas for user.
   * @param legacyId_ legacy id
   * @param lackOfOutgoingTxRange_ lackOfOutgoingTxRange
   */
  function setActivationTrigger(uint256 legacyId_, uint128 lackOfOutgoingTxRange_) external onlySafeWallet(legacyId_) {
    address legacyAddress = _checkLegacyExisted(legacyId_);

    //Check invalid activation trigger
    if (lackOfOutgoingTxRange_ == 0) revert ActivationTriggerInvalid();

    //Set lackOfOutgoingTxRange_
    ITransferLegacy(legacyAddress).setActivationTrigger(msg.sender, lackOfOutgoingTxRange_);

    emit TransferLegacyTriggerUpdated(legacyId_, lackOfOutgoingTxRange_, block.timestamp);
  }

  /**
   * @dev Set name and note legacy, call this function if only modify name and note to save gas for user.
   * @param legacyId_ legacy id
   * @param name_ name legacy
   * @param note_ note legacy
   */
  function setNameNote(uint256 legacyId_, string calldata name_, string calldata note_) external onlySafeWallet(legacyId_) {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    ITransferLegacy(legacyAddress).setLegacyName(name_);
    emit TransferLegacyNameNoteUpdated(legacyId_, name_, note_, block.timestamp);
  }

  /**
   * @dev Active legacy, call this function when the safewallet is eligible for activation.
   * @param legacyId_ legacy id
   */
  function activeLegacy(uint256 legacyId_, address[] calldata assets_, bool isETH_) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    address guardAddress = _checkGuardExisted(legacyId_);
    if (isETH_ == false && assets_.length == 0) revert NumAssetsInvalid();

    //Active legacy
    ITransferLegacy(legacyAddress).activeLegacy(guardAddress, assets_, isETH_, msg.sender);
    uint8 beneLayer = ITransferLegacy(legacyAddress).getBeneficiaryLayer(msg.sender);
    uint8 currentLayer = ITransferLegacy(legacyAddress).getLayer();
    if (beneLayer > currentLayer) revert CannotClaim();
    if (beneLayer == 0) revert OnlyBeneficaries();
    emit TransferLegacyActivated(legacyId_, beneLayer, block.timestamp);

  }

  /* Internal function */
    function _setLayer23Distributions(
    uint256 legacyId_,
    uint8 layer_,
    string calldata nickname_,
    TransferLegacyStruct.Distribution calldata distribution_
  ) internal {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    ITransferLegacy(legacyAddress).setLayer23Distributions(msg.sender, layer_, nickname_, distribution_);
    emit TransferLegacyLayer23DistributionUpdated(legacyId_, layer_, nickname_, distribution_, block.timestamp);
  }
}

contracts/forwarding/TransferLegacyEOAContractRouter.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {LegacyRouter} from "../common/LegacyRouter.sol";
import {EOALegacyFactory} from "../common/EOALegacyFactory.sol";
import {ITransferEOALegacy} from "../interfaces/ITransferLegacyEOAContract.sol";
import {TransferLegacyStruct} from "../libraries/TransferLegacyStruct.sol";
import {IEIP712LegacyVerifier} from "../interfaces/IEIP712LegacyVerifier.sol";
import {IPremiumSetting} from "../interfaces/IPremiumSetting.sol";
import {IPayment} from "../interfaces/IPayment.sol";
import {IUniswapV2Router02} from "../interfaces/IUniswapV2Router02.sol";

contract TransferEOALegacyRouter is LegacyRouter, EOALegacyFactory, Initializable {
  address public premiumSetting;
  IEIP712LegacyVerifier public verifier;
  address public paymentContract;
  address public uniswapRouter;
  address public weth;
  bytes public legacyCreationCode;
  address private _codeAdmin;

  /* Error */
  error NumBeneficiariesInvalid();
  error NumAssetsInvalid();
  error DistributionsInvalid();
  error ActivationTriggerInvalid();
  error SenderIsCreatedLegacy(address);
  error OnlyBeneficaries();
  error CannotClaim();
  error InvalidSwapSettings();
  error NotCodeAdmin();
  error EmptyCode();

  modifier onlyCodeAdmin() {
    if (msg.sender != _codeAdmin) revert NotCodeAdmin();
    _;
  }

  /* Struct */
  struct LegacyMainConfig {
    string name;
    string note;
    string[] nickNames;
    TransferLegacyStruct.Distribution[] distributions;
  }

  /* Event */
  event TransferEOALegacyCreated(
    uint256 indexed legacyId,
    address legacyAddress,
    address creatorAddress,
    LegacyMainConfig mainConfig,
    TransferLegacyStruct.LegacyExtraConfig extraConfig,
    uint256 timestamp
  );
  event TransferEOALegacyConfigUpdated(
    uint256 indexed legacyId,
    LegacyMainConfig mainConfig,
    TransferLegacyStruct.LegacyExtraConfig extraConfig,
    uint256 timestamp
  );
  event TransferEOALegacyDistributionUpdated(
    uint256 indexed legacyId,
    string[] nickNames,
    TransferLegacyStruct.Distribution[] distributions,
    uint256 timestamp
  );
  event TransferEOALegacyTriggerUpdated(uint256 indexed legacyId, uint128 lackOfOutgoingTxRange, uint256 timestamp);
  event TransferEOALegacyNameNoteUpdated(uint256 indexed legacyId, string name, string note, uint256 timestamp);
  event TransferEOALegacyActivated(uint256 indexed legacyId, uint8 layer, uint256 timestamp);
  event TransferEOALegacyActivedAlive(uint256 indexed legacyId, uint256 timestamp);
  event TransferEOALegacyDeleted(uint256 indexed legacyId, uint256 timestamp);
  event TransferEOALegacyLayer23DistributionUpdated(
    uint256 indexed legacyId,
    uint8 layer,
    string nickNames,
    TransferLegacyStruct.Distribution distribution,
    uint256 timestamp
  );
  event TransferEOALegacyLayer23Created(uint256 indexed legacyId, uint8 layer, TransferLegacyStruct.Distribution distribution, string nickName);
  event EmailOwnerResetNotCompleted(address legacyAddress);
  event TransferEOALegacyAutoSwapped(uint256 indexed legacyId, address storageToken, uint256 ethAmount, uint256 timestamp);
  event TransferEOALegacyUnswapped(uint256 indexed legacyId, address storageToken, uint256 tokenAmount, uint256 timestamp);
  event TransferEOALegacyActivatedWithUnswap(uint256 indexed legacyId, uint8 layer, uint256 timestamp);

    constructor () {
    _disableInitializers();
  }

  function initialize(
    address _deployerContract,
    address _premiumSetting,
    address _verifier,
    address _paymentContract,
    address router_,
    address weth_
  ) external initializer {
    if (
      _deployerContract == address(0) ||
      _premiumSetting == address(0) ||
      _verifier == address(0) ||
      _paymentContract == address(0) ||
      router_ == address(0) ||
      weth_ == address(0)
    ) revert InvalidInitialization();
    legacyDeployerContract = _deployerContract;
    premiumSetting = _premiumSetting;
    verifier = IEIP712LegacyVerifier(_verifier);
    paymentContract = _paymentContract;
    uniswapRouter = router_;
    weth = weth_;
  }

  function initializeV2(address codeAdmin_) external reinitializer(2) {
    _codeAdmin = codeAdmin_;
  }


  function setLegacyCreationCode(bytes calldata code_) external onlyCodeAdmin {
    if (code_.length == 0) revert EmptyCode();
    legacyCreationCode = code_;
  }

  /**
   * @dev Get next legacy address that would be created for a sender
   */
  function getNextLegacyAddress(address sender_) external view returns (address) {
    return _getNextAddress(legacyCreationCode, sender_);
  }

  function checkActiveLegacy(uint256 legacyId_) external view returns (bool) {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    return ITransferEOALegacy(legacyAddress).checkActiveLegacy();
  }

  function createLegacy(
    LegacyMainConfig calldata mainConfig_,
    TransferLegacyStruct.LegacyExtraConfig calldata extraConfig_,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_,
    string calldata nickName2,
    string calldata nickName3,
    uint256 signatureTimestamp,
    bytes calldata agreementSignature
  ) external returns (address) {
    if (mainConfig_.distributions.length != mainConfig_.nickNames.length || mainConfig_.distributions.length == 0) revert DistributionsInvalid();
    if (extraConfig_.lackOfOutgoingTxRange == 0) revert ActivationTriggerInvalid();
    //Check if msg.sender has already created a legacy
    if (_isCreateLegacy(msg.sender)) revert SenderIsCreatedLegacy(msg.sender);

    // Create new legacy contract
    (uint256 newLegacyId, address legacyAddress) = _createLegacy(legacyCreationCode, msg.sender);

    //Verify + store user agreement signature
    verifier.storeLegacyAgreement(msg.sender, legacyAddress, signatureTimestamp, agreementSignature);

    uint256 numberOfBeneficiaries = ITransferEOALegacy(legacyAddress).initialize(
      newLegacyId,
      msg.sender,
      mainConfig_.distributions,
      extraConfig_,
      layer2Distribution_,
      layer3Distribution_,
      premiumSetting,
      paymentContract,
      uniswapRouter,
      weth,
      mainConfig_.nickNames,
      nickName2,
      nickName3
    );

    // Check beneficiary limit
    if (!_checkNumBeneficiariesLimit(numberOfBeneficiaries)) revert NumBeneficiariesInvalid();

    TransferLegacyStruct.LegacyExtraConfig memory _legacyExtraConfig = TransferLegacyStruct.LegacyExtraConfig({
      lackOfOutgoingTxRange: extraConfig_.lackOfOutgoingTxRange,
      delayLayer2: ITransferEOALegacy(legacyAddress).delayLayer2(),
      delayLayer3: ITransferEOALegacy(legacyAddress).delayLayer3()
    });

    ITransferEOALegacy(legacyAddress).setLegacyName(mainConfig_.name, msg.sender);

    emit TransferEOALegacyCreated(newLegacyId, legacyAddress, msg.sender, mainConfig_, _legacyExtraConfig, block.timestamp);

    //set private code for legacy of premium user
    IPremiumSetting(premiumSetting).setPrivateCodeAndCronjob(msg.sender, legacyAddress);

    // Emit layer2/3 created if needed
    uint256 distribution2 = ITransferEOALegacy(legacyAddress).getDistribution(2, layer2Distribution_.user);
    uint256 distribution3 = ITransferEOALegacy(legacyAddress).getDistribution(3, layer3Distribution_.user);

    if (distribution2 != 0) {
      emit TransferEOALegacyLayer23Created(newLegacyId, 2, layer2Distribution_, nickName2);
    }

    if (distribution3 != 0) {
      emit TransferEOALegacyLayer23Created(newLegacyId, 3, layer3Distribution_, nickName3);
    }

    return legacyAddress;
  }

  function avtiveAlive(uint256 legacyId_) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);

    try 
    IPremiumSetting(premiumSetting).triggerOwnerResetReminder(legacyAddress) 
    {} catch {
      emit EmailOwnerResetNotCompleted(legacyAddress);
    }
    ITransferEOALegacy(legacyAddress).activeAlive(msg.sender);
    emit TransferEOALegacyActivedAlive(legacyId_, block.timestamp);
  }

  function setLegacyConfig(
    uint256 legacyId_,
    LegacyMainConfig calldata mainConfig_,
    TransferLegacyStruct.LegacyExtraConfig calldata extraConfig_,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_,
    string calldata nickName2,
    string calldata nickName3
  ) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);

    bool isPremium = IPremiumSetting(premiumSetting).isPremium(msg.sender);

    if (mainConfig_.distributions.length != mainConfig_.nickNames.length || mainConfig_.distributions.length == 0) revert DistributionsInvalid();
    if (extraConfig_.lackOfOutgoingTxRange == 0) revert ActivationTriggerInvalid();

    uint256 numberBeneficiaries = ITransferEOALegacy(legacyAddress).setLegacyDistributions(
      msg.sender,
      mainConfig_.distributions,
      mainConfig_.nickNames
    );
    if (!_checkNumBeneficiariesLimit(numberBeneficiaries)) revert NumBeneficiariesInvalid();

    // Set activation trigger
    ITransferEOALegacy(legacyAddress).setActivationTrigger(msg.sender, extraConfig_.lackOfOutgoingTxRange);

    // Set delay and layer 2/3 distribution - Now works for both premium and non-premium
    ITransferEOALegacy(legacyAddress).setDelayAndLayer23Distributions(
      msg.sender,
      extraConfig_.delayLayer2,
      extraConfig_.delayLayer3,
      nickName2,
      nickName3,
      layer2Distribution_,
      layer3Distribution_
    );

    // If the user is not premium, we don't emit events for layer 2/3 distributions
    if (isPremium) {
      // Only emit events for premium users (who can actually update layer 2/3)
      emit TransferEOALegacyLayer23DistributionUpdated(legacyId_, 2, nickName2, layer2Distribution_, block.timestamp);

      emit TransferEOALegacyLayer23DistributionUpdated(legacyId_, 3, nickName3, layer3Distribution_, block.timestamp);
    }

    ITransferEOALegacy(legacyAddress).setLegacyName(mainConfig_.name, msg.sender);

    // Emit final config update
    TransferLegacyStruct.LegacyExtraConfig memory _legacyExtraConfig = TransferLegacyStruct.LegacyExtraConfig({
      lackOfOutgoingTxRange: extraConfig_.lackOfOutgoingTxRange,
      delayLayer2: ITransferEOALegacy(legacyAddress).delayLayer2(),
      delayLayer3: ITransferEOALegacy(legacyAddress).delayLayer3()
    });

    emit TransferEOALegacyConfigUpdated(legacyId_, mainConfig_, _legacyExtraConfig, block.timestamp);
  }

  function setLegacyDistributions(
    uint256 legacyId_,
    string[] calldata nickNames_,
    TransferLegacyStruct.Distribution[] calldata distributions_
  ) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    if (distributions_.length != nickNames_.length || distributions_.length == 0) revert DistributionsInvalid();
    uint256 numberOfBeneficiaries = ITransferEOALegacy(legacyAddress).setLegacyDistributions(msg.sender, distributions_, nickNames_);
    if (!_checkNumBeneficiariesLimit(numberOfBeneficiaries)) revert NumBeneficiariesInvalid();

    emit TransferEOALegacyDistributionUpdated(legacyId_, nickNames_, distributions_, block.timestamp);
  }

  function setLayer23Distributions(
    uint256 legacyId_,
    uint8 layer_,
    string calldata nickname_,
    TransferLegacyStruct.Distribution calldata distribution_
  ) external {
    _setLayer23Distributions(legacyId_, layer_, nickname_, distribution_);
  }


    function setBothLayer23Distributions(
    uint256 legacyId_,
    string calldata nicknameLayer2_,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    string calldata nicknameLayer3_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_

  ) external {
    _setLayer23Distributions(legacyId_, 2, nicknameLayer2_, layer2Distribution_);
    _setLayer23Distributions(legacyId_, 3, nicknameLayer3_, layer3Distribution_);
  }

  function setActivationTrigger(uint256 legacyId_, uint128 lackOfOutgoingTxRange_) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    if (lackOfOutgoingTxRange_ == 0) revert ActivationTriggerInvalid();
    ITransferEOALegacy(legacyAddress).setActivationTrigger(msg.sender, lackOfOutgoingTxRange_);
    emit TransferEOALegacyTriggerUpdated(legacyId_, lackOfOutgoingTxRange_, block.timestamp);
  }

  function setNameNote(uint256 legacyId_, string calldata name_, string calldata note_) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    ITransferEOALegacy(legacyAddress).setLegacyName(name_, msg.sender);
    emit TransferEOALegacyNameNoteUpdated(legacyId_, name_, note_, block.timestamp);
  }

  function activeLegacy(uint256 legacyId_, address[] calldata assets_, bool isETH_) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    if (isETH_ == false && assets_.length == 0) revert NumAssetsInvalid();

    //Active legacy
    ITransferEOALegacy(legacyAddress).activeLegacy(assets_, isETH_, msg.sender);
    uint8 beneLayer = ITransferEOALegacy(legacyAddress).getBeneficiaryLayer(msg.sender);
    uint8 currentLayer = ITransferEOALegacy(legacyAddress).getLayer();
    if (beneLayer > currentLayer) revert CannotClaim();
    if (beneLayer == 0) revert OnlyBeneficaries();
    emit TransferEOALegacyActivated(legacyId_, beneLayer, block.timestamp);
  }

  /**
   * @dev Beneficiary claims the legacy; if the owner has an active storage-token swap,
   * it is atomically swapped back to ETH and distributed in the same transaction.
   */
  function activeLegacyAndUnswap(
    uint256 legacyId_,
    address[] calldata assets_,
    uint256 amountOutMin_,
    uint256 deadline_
  ) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);

    ITransferEOALegacy(legacyAddress).activeLegacyAndUnswap(
      assets_,
      msg.sender,
      amountOutMin_,
      deadline_
    );

    uint8 beneLayer = ITransferEOALegacy(legacyAddress).getBeneficiaryLayer(msg.sender);
    uint8 currentLayer = ITransferEOALegacy(legacyAddress).getLayer();
    if (beneLayer > currentLayer) revert CannotClaim();
    if (beneLayer == 0) revert OnlyBeneficaries();

    emit TransferEOALegacyActivatedWithUnswap(legacyId_, beneLayer, block.timestamp);
  }

  function deleteLegacy(uint256 legacyId_) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    isCreateLegacy[msg.sender] = false;

    ITransferEOALegacy(legacyAddress).deleteLegacy(msg.sender);
    emit TransferEOALegacyDeleted(legacyId_, block.timestamp);
  }

  function withdraw(uint256 legacyId_, uint256 amount_) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    ITransferEOALegacy(legacyAddress).withdraw(msg.sender, amount_);
  }

  /**
   * @dev Forwards ETH + swap config to the individual legacy contract.
   * The individual contract swaps ETH -> storageToken and sends tokens to the owner's wallet.
   */
  function autoSwap(
    uint256 legacyId_,
    TransferLegacyStruct.EOALegacyETHSwap calldata swap_
  ) external payable {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    ITransferEOALegacy(legacyAddress).autoSwap{value: msg.value}(msg.sender, swap_);
    emit TransferEOALegacyAutoSwapped(legacyId_, swap_.storageToken, msg.value, block.timestamp);
  }

  /**
   * @dev Forwards unswap request to the individual legacy contract.
   * Pulls storageToken from owner's wallet, swaps to ETH, sends ETH to owner.
   */
  function unswap(
    uint256 legacyId_,
    uint256 amountIn_,
    uint256 amountOutMin_,
    uint256 deadline_
  ) external {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    address storageToken = ITransferEOALegacy(legacyAddress).eoaStorageToken();
    ITransferEOALegacy(legacyAddress).unswap(msg.sender, amountIn_, amountOutMin_, deadline_);
    emit TransferEOALegacyUnswapped(legacyId_, storageToken, amountIn_, block.timestamp);
  }

  /**
   * @dev Returns the expected token amount out for a given ETH amount via Uniswap V2.
   */
  function getEthToTokenAmountOut(
    uint256 ethAmount_,
    address outputToken_
  ) external view returns (uint256) {
    address[] memory path = new address[](2);
    path[0] = weth;
    path[1] = outputToken_;
    uint256[] memory amounts = IUniswapV2Router02(uniswapRouter).getAmountsOut(ethAmount_, path);
    return amounts[1];
  }

  /**
   * @dev Returns the expected ETH amount out for a given token amount via Uniswap V2.
   */
  function getTokenToEthAmountOut(
    uint256 tokenAmount_,
    address token_
  ) external view returns (uint256) {
    address[] memory path = new address[](2);
    path[0] = token_;
    path[1] = weth;
    uint256[] memory amounts = IUniswapV2Router02(uniswapRouter).getAmountsOut(tokenAmount_, path);
    return amounts[1];
  }

  function _setLayer23Distributions(
    uint256 legacyId_,
    uint8 layer_,
    string calldata nickname_,
    TransferLegacyStruct.Distribution calldata distribution_
  ) internal {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    ITransferEOALegacy(legacyAddress).setLayer23Distributions(msg.sender, layer_, nickname_, distribution_);
    emit TransferEOALegacyLayer23DistributionUpdated(legacyId_, layer_, nickname_, distribution_, block.timestamp);
  }
}

contracts/inheritance/MultisigLegacyContract.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {GenericLegacy} from "../common/GenericLegacy.sol";
import {ISafeGuard} from "../interfaces/ISafeGuard.sol";
import {ISafeWallet} from "../interfaces/ISafeWallet.sol";
import {MultisigLegacyStruct} from "../libraries/MultisigLegacyStruct.sol";
import {Enum} from "@safe-global/safe-smart-account/contracts/common/Enum.sol";

contract MultisigLegacy is GenericLegacy {
  error BeneficiaryInvalid();
  error NotBeneficiary();
  error NotEnoughContitionalActive();
  error ExecTransactionFromModuleFailed();
  error LengthMismatch();

  using EnumerableSet for EnumerableSet.AddressSet;

  /* State variable */
  uint128 public constant LEGACY_TYPE = 1;
  uint128 public _minRequiredSignatures = 1;
  EnumerableSet.AddressSet private _beneficiariesSet;
  address public safeGuard;
  address public creator;

  /* View functions to support premium */

  ///@dev false if legacy has been deleted or activated
  function isLive() public view override returns (bool) {
    return getIsActiveLegacy() == 1;
  }

  ///@dev get the timestamp when activation can be triggered
  function getTriggerActivationTimestamp() public view override returns (uint256, uint256, uint256) {
    //last tx of safe wallet linked with this legacy
    // find guard address for this contract

    uint256 lastTimestamp = ISafeGuard(safeGuard).getLastTimestampTxs();
    uint256 lackOfOutgoingTxRange = getActivationTrigger();
    uint256 beneficiariesTrigger = lastTimestamp + lackOfOutgoingTxRange;

    return (beneficiariesTrigger, beneficiariesTrigger, beneficiariesTrigger);
  }

  function getLegacyBeneficiaries() public view override returns (address[] memory, address, address) {
    return (_beneficiariesSet.values(), address(0), address(0));
  }

  function getLastTimestamp() public view override returns (uint256) {
    return ISafeGuard(safeGuard).getLastTimestampTxs();
  }

  /* View function */
  /**
   * @dev get beneficiaries list
   */
  function getBeneficiaries() external view returns (address[] memory) {
    return _beneficiariesSet.values();
  }

  /**
   * @dev get minRequiredSignatures
   */
  function getMinRequiredSignatures() external view returns (uint128) {
    return _minRequiredSignatures;
  }

  /**
   * @dev Check activation conditions
   * @param guardAddress_ guard
   * @return bool true if eligible for activation, false otherwise
   */
  function checkActiveLegacy(address guardAddress_) external view returns (bool) {
    return _checkActiveLegacy(guardAddress_);
  }

  /* Main function */
  /**
   * @dev Initialize info legacy
   * @param legacyId_ legacy id
   * @param owner_ owner of legacy
   * @param beneficiaries_ beneficiaries list
   * @param config_ include minRequiredSignatures, lackOfOutgoingTxRange
   */
  function initialize(
    uint256 legacyId_,
    address owner_,
    address[] calldata beneficiaries_,
    MultisigLegacyStruct.LegacyExtraConfig calldata config_,
    address _safeGuard,
    address _creator,
    string[] calldata nicknames_
  ) external notInitialized returns (uint256 numberOfBeneficiaries) {
    if (owner_ == address(0)) revert OwnerInvalid();
    if (_safeGuard == address(0)) revert OwnerInvalid();
    if (_creator == address(0)) revert OwnerInvalid();

    //set info legacy
    _setLegacyInfo(legacyId_, owner_, 1, config_.lackOfOutgoingTxRange, msg.sender);

    //set minRequiredSignatures
    _setMinRequiredSignatures(config_.minRequiredSignatures);

    //set beneficiaries
    numberOfBeneficiaries = _setBeneficiaries(owner_, beneficiaries_, nicknames_);

    safeGuard = _safeGuard;
    creator = _creator;
  }

  /**
   * @dev Set beneficiaries[], minRequiredSignatures legacy
   * @param sender_  sender address
   * @param beneficiaries_ beneficiaries list
   * @param minRequiredSigs_ minRequiredSignatures
   * @return numberOfBeneficiaries numberOfBeneficiares
   */
  function setLegacyBeneficiaries(
    address sender_,
    address[] calldata beneficiaries_,
    uint128 minRequiredSigs_,
    string[] calldata nicknames_
  ) external onlyRouter onlyOwner(sender_) isActiveLegacy returns (uint256 numberOfBeneficiaries) {
    if (beneficiaries_.length != nicknames_.length) revert LengthMismatch();
    //clear beneficiaries
    _clearBeneficiaries();

    //set minRequiredSignatures
    _setMinRequiredSignatures(minRequiredSigs_);

    //set beneficiaries
    numberOfBeneficiaries = _setBeneficiaries(sender_, beneficiaries_, nicknames_);
  }

  /**
   * @dev Set lackOfOutgoingTxRange legacy
   * @param sender_  sender address
   * @param lackOfOutgoingTxRange_  lackOfOutgoingTxRange
   */
  function setActivationTrigger(address sender_, uint128 lackOfOutgoingTxRange_) external onlyRouter onlyOwner(sender_) isActiveLegacy {
    _setActivationTrigger(lackOfOutgoingTxRange_);
  }

  /**
   * @dev Active legacy
   * @param guardAddress_ guard address
   * @return newSigners new threshold list
   */
  function activeLegacy(address guardAddress_) external onlyRouter isActiveLegacy returns (address[] memory newSigners, uint256 newThreshold) {
    //Active legacy
    if (_checkActiveLegacy(guardAddress_)) {
      address[] memory beneficiariesList = _beneficiariesSet.values();
      _setLegacyToInactive();
      _clearBeneficiaries();
      (newSigners, newThreshold) = _addOwnerWithThreshold(beneficiariesList);
    } else {
      revert NotEnoughContitionalActive();
    }
  }

  function setLegacyName(string calldata legacyName_) external onlyRouter isActiveLegacy {
    _setLegacyName(legacyName_);
  }

  /* Utils function */
  /**
   * @dev Check activation conditions
   * @param guardAddress_ guard
   * @return bool true if eligible for activation, false otherwise
   */
  function _checkActiveLegacy(address guardAddress_) private view returns (bool) {
    uint256 lastTimestamp = ISafeGuard(guardAddress_).getLastTimestampTxs();
    uint256 lackOfOutgoingTxRange = getActivationTrigger();
    if (lastTimestamp + lackOfOutgoingTxRange > block.timestamp) {
      return false;
    }
    return true;
  }

  /**
   * @dev Set beneficiaries[], minRequiredSignatures legacy
   * @param owner_  owner legacy
   * @param beneficiaries_  beneficiaries[]
   */
  function _setBeneficiaries(
    address owner_,
    address[] calldata beneficiaries_,
    string[] calldata nicknames_
  ) private returns (uint256 numberOfBeneficiaries) {
    address[] memory signers = ISafeWallet(owner_).getOwners();
    for (uint256 i = 0; i < beneficiaries_.length; ) {
      _checkBeneficiaries(signers, owner_, beneficiaries_[i]);
      _beneficiariesSet.add(beneficiaries_[i]);
      _setBeneNickname(beneficiaries_[i], nicknames_[i]);
      unchecked {
        ++i;
      }
    }
    numberOfBeneficiaries = _beneficiariesSet.length();
  }

  /**
   * @dev set minRequireSignatures
   * @param minRequiredSignatures_  minRequireSignatures
   */
  function _setMinRequiredSignatures(uint128 minRequiredSignatures_) private {
    _minRequiredSignatures = minRequiredSignatures_;
  }

  /**
   * @dev Clear benecifiaries list of legacy
   */
  function _clearBeneficiaries() private {
    uint256 length = _beneficiariesSet.length();
    for (uint256 i = 0; i < length; ) {
      _deleteBeneName(_beneficiariesSet.at(0));
      _beneficiariesSet.remove(_beneficiariesSet.at(0));
      unchecked {
        ++i;
      }
    }
  }

  /**
   * @dev Add beneficiaries and set threshold in safe wallet
   * @param newSigners, newThreshold
   */
  function _addOwnerWithThreshold(address[] memory beneficiaries_) private returns (address[] memory newSigners, uint256 newThreshold) {
    address owner = getLegacyOwner();
    uint256 threshold = ISafeWallet(owner).getThreshold();
    for (uint256 i = 0; i < beneficiaries_.length; ) {
      bytes memory addOwnerData = abi.encodeWithSignature("addOwnerWithThreshold(address,uint256)", beneficiaries_[i], threshold);
      unchecked {
        ++i;
      }
      bool successAddOwner = ISafeWallet(owner).execTransactionFromModule(owner, 0, addOwnerData, Enum.Operation.Call);
      if (!successAddOwner) revert ExecTransactionFromModuleFailed();
    }
    if (threshold != _minRequiredSignatures) {
      bytes memory changeThresholdData = abi.encodeWithSignature("changeThreshold(uint256)", _minRequiredSignatures);
      bool successChangeThreshold = ISafeWallet(owner).execTransactionFromModule(owner, 0, changeThresholdData, Enum.Operation.Call);
      if (!successChangeThreshold) revert ExecTransactionFromModuleFailed();
    }
    newSigners = ISafeWallet(owner).getOwners();
    newThreshold = ISafeWallet(owner).getThreshold();
  }

  /**
   *
   * @param signers_  signer list
   * @param owner_  safe wallet address
   * @param beneficiary_ beneficiary address
   */
  function _checkBeneficiaries(address[] memory signers_, address owner_, address beneficiary_) private pure {
    if (beneficiary_ == address(0) || beneficiary_ == owner_) revert BeneficiaryInvalid();

    for (uint256 j = 0; j < signers_.length; ) {
      if (beneficiary_ == signers_[j]) revert BeneficiaryInvalid();
      unchecked {
        j++;
      }
    }
  }
}

contracts/interfaces/IEIP712LegacyVerifier.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

interface IEIP712LegacyVerifier {
    function storeLegacyAgreement(address user, address legacyAddress, uint256 timestamp, bytes calldata signature) external;
}

contracts/interfaces/ILegacyDeployer.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

interface ILegacyDeployer {
    function getNextAddress(bytes calldata byteCode, address user) external view returns (address nextLegacy);
    function createLegacy(bytes calldata byteCode, address user)  external returns (address legacyAddress, address guardAddress);
}

contracts/interfaces/IPayment.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

interface IPayment {
    /**
     * @dev Returns the admin fee percentage
     */
    function getFee() external view returns (uint256);
}

contracts/interfaces/IPremiumAutomationManager.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;
import "../libraries/NotifyLib.sol";


interface IPremiumAutomationManager {
    function addLegacyCronjob(address user, address [] memory  legacyAddresses) external ;
    function sendNotifyFromCronjob(address legacy, NotifyLib.NotifyType notifyType) external ;

}

contracts/interfaces/IPremiumLegacy.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;
///@dev for premium to view Legacy
interface IPremiumLegacy {
  
  //Generic
  function getLegacyOwner() external view returns (address);
  function getLegacyInfo() external view returns (uint256, address, uint128);
  function getActivationTrigger () external view returns (uint128);
  function getLegacyId () external view returns (uint256);

  function LEGACY_TYPE() external view returns (uint128);

  function creator() external view returns (address);
  function router() external view returns (address);


  function delayLayer2() external view returns (uint256);

  function delayLayer3() external view returns (uint256);

  function activeLegacy(address guardAddress_, address[] calldata assets_, bool isETH_) external returns (address[] memory assets, uint8 layer);

  function checkActiveLegacy(address guardAddress_) external view returns (bool);

  function getDistribution(uint8 layer, address beneficiary) external returns (uint256);

  function getBeneficiaries() external view returns (address[] memory);

  function isLive() external view returns (bool);

  function getLegacyBeneficiaries()  external view returns (address [] memory beneficiaries, address layer2, address layer3);

  function getTriggerActivationTimestamp() external view returns(uint256 beneficiariesTrigger, uint256 layer2Trigger, uint256 layer3Trigger);

  function getLayer()  external view returns (uint8);

  function getLegacyName() external view returns (string memory);

  function getLastTimestamp() external view returns (uint256);

  function getBeneficiaryLayer(address beneficiary) external view returns (uint8);

  function getBeneNickname(address beneAddress) external view returns (string memory);

}

contracts/interfaces/IPremiumSendMail.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

import {NotifyLib} from "../libraries/NotifyLib.sol";

interface IPremiumSendMail {
  function sendEmailFromManager(address legacy, NotifyLib.NotifyType notifyType) external;

  //BEFORE ACTIVATION
  function sendEmailBeforeActivationToOwner(
    string memory ownerName,
    string memory contractName,
    uint256 lastTx,
    uint256 bufferTime,
    address[] memory listBene,
    string memory ownerEmail
  ) external;

  function sendEmailBeforeActivationToBeneficiary(
    string[] memory beneNames,
    string memory contractName,
    uint256 timeCountdown,
    string[] memory beneEmails,
    uint256 legacyId,
    address contractAddress
  ) external;

  function sendEmailBeforeLayer2ToLayer1(
    string[] memory beneNames,
    string[] memory beneEmails,
    string memory contractName,
    uint256 x_days,
    uint256 legacyId,
    address contractAddress
  ) external;

  function sendEmailBeforeLayer2ToLayer2(string memory beneName, string memory beneEmail, string memory contractName, uint256 x_days) external;

  function sendEmailBeforeLayer3ToLayer12(
    string[] memory beneNames,
    string[] memory beneEmails,
    string memory contractName,
    uint256 x_days,
    uint256 legacyId,
    address contractAddress
  ) external;
  function sendEmailBeforeLayer3ToLayer3(string memory beneName, string memory beneEmail, string memory contractName, uint256 x_day) external;

  function sendEmailReadyToActivateToLayer1(
    string[] memory beneName, 
    string[] memory beneEmail, 
    string memory contractName,    
    uint256 legacyId,
    address contractAddress) external;

  //READY TO ACTIVATE
  function sendEmailReadyToActivateLayer2ToLayer1(
    string[] memory beneNameLayer1,
    string[] memory beneEmailLayer1,
    address beneAddressLayer2,
    string memory contractName,
    uint256 timeActiveLayer2
  ) external;

  function sendEmailReadyToActivateLayer2ToLayer2(
  string memory beneName, 
  string memory beneEmail, 
  string memory contractName,    
  uint256 legacyId,
  address contractAddress) external;

  function sendEmailReadyToActivateLayer3ToLayer12(
    string[] memory beneName,
    string[] memory beneEmail,
    string memory contractName,
    uint256 activationDate,
    address layer3Addr
  ) external;

  function sendEmailReadyToActivateLayer3ToLayer3(
    string memory beneName, 
    string memory beneEmail, 
    string memory contractName,
    uint256 legacyId,
    address contractAddress
    ) external;

  function sendEmailActivatedToLayer1(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    address[] memory listToken,
    uint256[] memory listAmount,
    string[] memory listAssetName
  ) external;

  function sendEmailActivatedToLayer2(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    address[] memory listToken,
    uint256[] memory listAmount,
    string[] memory listAssetName
  ) external;

  function sendMailOwnerResetToBene(string[] memory beneNames, string[] memory beneEmails, string memory contractName) external;

  //ACTIVATED
  function sendMailActivatedMultisig(string[] memory beneNames, string[] memory beneEmails, string memory contractName, address safeWallet) external;

  function sendEmailActivatedToBene(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    address[] memory listToken,
    uint256[] memory listAmount,
    string[] memory listAssetName,
    address contractAddress,
    bool remaining
  ) external;

  function sendEmailContractActivatedToOwner(
    string memory toEmail,
    string memory contractName,
    address activatedByBene,
    uint256 timeActivated,
    address safeWallet,
    NotifyLib.ListAsset[] memory _listAsset,
    NotifyLib.BeneReceived[] memory _listBeneReceived,
    address contractAddress,
    bool remaining
  ) external;

  function sendActivatedMutisigToOwner(
    string memory ownerEmail,
    string memory contractName,
    address contractAddress,
    address activatedBy,
    address safeAddress,
    string[] memory beneNames,
    address[] memory beneAddresses
  ) external;
}

contracts/interfaces/IPremiumSetting.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;
import "../libraries/NotifyLib.sol";

interface IPremiumSetting {
  function updatePremiumTime(address user, uint256 duration) external;
  function premiumExpired(address user) external view returns (uint256 expiredTimestamp);
  function isPremium(address user) external view returns (bool);
  function getTimeAhead(address user) external view returns (uint256);
  function setPrivateCodeAndCronjob(address user, address legacyAddress) external;
  function getUserData(address user) external view returns (string memory, string memory, uint256);
  function getCosignerData(address legacyAddress) external view returns (address[] memory, string[] memory, string[] memory);
  function getBeneficiaryData(address legacyAddress) external view returns (address[] memory, string[] memory, string[] memory);
  function getSecondLineData(address legacyAddress) external view returns (address, string memory, string memory);
  function getThirdLineData(address legacyAddress) external view returns (address, string memory, string memory);

  //reminder
  function triggerActivationMultisig(address legacyAddress) external;
  function triggerOwnerResetReminder(address legacyAddress) external;
  function triggerActivationTransferLegacy(
    NotifyLib.ListAsset[] memory listAsset, 
    NotifyLib.BeneReceived[] memory _listBeneReceived,
    bool remaining) external;
}

contracts/interfaces/ISafeGuard.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

interface ISafeGuard {
  function initialize(address _safeWallet) external;
  function getLastTimestampTxs() external view returns (uint256);
}

contracts/interfaces/ISafeWallet.sol

// SPDX-License-Identifier: UNLICENSED
// OpenZeppelin Contracts v5.x
pragma solidity 0.8.20;

import {Enum} from "@safe-global/safe-smart-account/contracts/common/Enum.sol";


interface ISafeWallet {
  /**
   * @notice Reads `length` bytes of storage in the currents contract
   * @param offset - the offset in the current contract's storage in words to start reading from
   * @param length - the number of words (32 bytes) of data to read
   * @return the bytes that were read.
   */
  function getStorageAt(uint256 offset, uint256 length) external view returns (bytes memory);

  //======================================== ISafe ================================================

  /**
   * @notice Sets an initial storage of the Safe contract.
   * @dev This method can only be called once.
   *      If a proxy was created without setting up, anyone can call setup and claim the proxy.
   * @param _owners List of Safe owners.
   * @param _threshold Number of required confirmations for a Safe transaction.
   * @param to Contract address for optional delegate call.
   * @param data Data payload for optional delegate call.
   * @param fallbackHandler Handler for fallback calls to this contract
   * @param paymentToken Token that should be used for the payment (0 is ETH)
   * @param payment Value that should be paid
   * @param paymentReceiver Address that should receive the payment (or 0 if tx.origin)
   */
  function setup(
    address[] calldata _owners,
    uint256 _threshold,
    address to,
    bytes calldata data,
    address fallbackHandler,
    address paymentToken,
    uint256 payment,
    address payable paymentReceiver
  ) external;

  /** @notice Executes a `operation` {0: Call, 1: DelegateCall}} transaction to `to` with `value` (Native Currency)
   *          and pays `gasPrice` * `gasLimit` in `gasToken` token to `refundReceiver`.
   * @dev The fees are always transferred, even if the user transaction fails.
   *      This method doesn't perform any sanity check of the transaction, such as:
   *      - if the contract at `to` address has code or not
   *      - if the `gasToken` is a contract or not
   *      It is the responsibility of the caller to perform such checks.
   * @param to Destination address of Safe transaction.
   * @param value Ether value of Safe transaction.
   * @param data Data payload of Safe transaction.
   * @param operation Operation type of Safe transaction.
   * @param safeTxGas Gas that should be used for the Safe transaction.
   * @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
   * @param gasPrice Gas price that should be used for the payment calculation.
   * @param gasToken Token address (or 0 if ETH) that is used for the payment.
   * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
   * @param signatures Signature data that should be verified.
   *                   Can be packed ECDSA signature ({bytes32 r}{bytes32 s}{uint8 v}), contract signature (EIP-1271) or approved hash.
   * @return success Boolean indicating transaction's success.
   */
  function execTransaction(
    address to,
    uint256 value,
    bytes calldata data,
    Enum.Operation operation,
    uint256 safeTxGas,
    uint256 baseGas,
    uint256 gasPrice,
    address gasToken,
    address payable refundReceiver,
    bytes memory signatures
  ) external payable returns (bool success);

  /**
   * @notice Checks whether the signature provided is valid for the provided data and hash. Reverts otherwise.
   * @param dataHash Hash of the data (could be either a message hash or transaction hash)
   * @param data That should be signed (this is passed to an external validator contract)
   * @param signatures Signature data that should be verified.
   *                   Can be packed ECDSA signature ({bytes32 r}{bytes32 s}{uint8 v}), contract signature (EIP-1271) or approved hash.
   */
  function checkSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures) external view;

  /**
   * @notice Checks whether the signature provided is valid for the provided data and hash. Reverts otherwise.
   * @dev Since the EIP-1271 does an external call, be mindful of reentrancy attacks.
   * @param dataHash Hash of the data (could be either a message hash or transaction hash)
   * @param data That should be signed (this is passed to an external validator contract)
   * @param signatures Signature data that should be verified.
   *                   Can be packed ECDSA signature ({bytes32 r}{bytes32 s}{uint8 v}), contract signature (EIP-1271) or approved hash.
   * @param requiredSignatures Amount of required valid signatures.
   */
  function checkNSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures, uint256 requiredSignatures) external view;

  /**
   * @notice Marks hash `hashToApprove` as approved.
   * @dev This can be used with a pre-approved hash transaction signature.
   *      IMPORTANT: The approved hash stays approved forever. There's no revocation mechanism, so it behaves similarly to ECDSA signatures
   * @param hashToApprove The hash to mark as approved for signatures that are verified by this contract.
   */
  function approveHash(bytes32 hashToApprove) external;

  /**
   * @dev Returns the domain separator for this contract, as defined in the EIP-712 standard.
   * @return bytes32 The domain separator hash.
   */
  function domainSeparator() external view returns (bytes32);

  /**
   * @notice Returns transaction hash to be signed by owners.
   * @param to Destination address.
   * @param value Ether value.
   * @param data Data payload.
   * @param operation Operation type.
   * @param safeTxGas Gas that should be used for the safe transaction.
   * @param baseGas Gas costs for data used to trigger the safe transaction.
   * @param gasPrice Maximum gas price that should be used for this transaction.
   * @param gasToken Token address (or 0 if ETH) that is used for the payment.
   * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
   * @param _nonce Transaction nonce.
   * @return Transaction hash.
   */
  function getTransactionHash(
    address to,
    uint256 value,
    bytes calldata data,
    Enum.Operation operation,
    uint256 safeTxGas,
    uint256 baseGas,
    uint256 gasPrice,
    address gasToken,
    address refundReceiver,
    uint256 _nonce
  ) external view returns (bytes32);

  /**
   * @notice Returns the pre-image of the transaction hash (see getTransactionHash).
   * @param to Destination address.
   * @param value Ether value.
   * @param data Data payload.
   * @param operation Operation type.
   * @param safeTxGas Gas that should be used for the safe transaction.
   * @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
   * @param gasPrice Maximum gas price that should be used for this transaction.
   * @param gasToken Token address (or 0 if ETH) that is used for the payment.
   * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
   * @param _nonce Transaction nonce.
   * @return Transaction hash bytes.
   */
  function encodeTransactionData(
    address to,
    uint256 value,
    bytes calldata data,
    Enum.Operation operation,
    uint256 safeTxGas,
    uint256 baseGas,
    uint256 gasPrice,
    address gasToken,
    address refundReceiver,
    uint256 _nonce
  ) external view returns (bytes memory);

  /**
   * External getter function for state variables.
   */

  /**
   * @notice Returns the version of the Safe contract.
   * @return Version string.
   */
  // solhint-disable-next-line
  function VERSION() external view returns (string memory);

  /**
   * @notice Returns the nonce of the Safe contract.
   * @return Nonce.
   */
  function nonce() external view returns (uint256);

  /**
   * @notice Returns a uint if the messageHash is signed by the owner.
   * @param messageHash Hash of message that should be checked.
   * @return Number denoting if an owner signed the hash.
   */
  function signedMessages(bytes32 messageHash) external view returns (uint256);

  /**
   * @notice Returns a uint if the messageHash is approved by the owner.
   * @param owner Owner address that should be checked.
   * @param messageHash Hash of message that should be checked.
   * @return Number denoting if an owner approved the hash.
   */
  function approvedHashes(address owner, bytes32 messageHash) external view returns (uint256);

  //======================================== IModuleManager =======================================

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

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

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

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

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

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

  //======================================== IGuardManager ========================================

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

  //======================================== IOwnerManager ========================================

  /**
   * @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
   * @dev This can only be done via a Safe transaction.
   * @param owner New owner address.
   * @param _threshold New threshold.
   */
  function addOwnerWithThreshold(address owner, uint256 _threshold) external;

  /**
   * @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
   * @dev This can only be done via a Safe transaction.
   * @param prevOwner Owner that pointed to the owner to be removed in the linked list
   * @param owner Owner address to be removed.
   * @param _threshold New threshold.
   */
  function removeOwner(address prevOwner, address owner, uint256 _threshold) external;

  /**
   * @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
   * @dev This can only be done via a Safe transaction.
   * @param prevOwner Owner that pointed to the owner to be replaced in the linked list
   * @param oldOwner Owner address to be replaced.
   * @param newOwner New owner address.
   */
  function swapOwner(address prevOwner, address oldOwner, address newOwner) external;

  /**
   * @notice Changes the threshold of the Safe to `_threshold`.
   * @dev This can only be done via a Safe transaction.
   * @param _threshold New threshold.
   */
  function changeThreshold(uint256 _threshold) external;

  /**
   * @notice Returns the number of required confirmations for a Safe transaction aka the threshold.
   * @return Threshold number.
   */
  function getThreshold() external view returns (uint256);

  /**
   * @notice Returns if `owner` is an owner of the Safe.
   * @return Boolean if `owner` is an owner of the Safe.
   */
  function isOwner(address owner) external view returns (bool);

  /**
   * @notice Returns a list of Safe owners.
   * @return Array of Safe owners.
   */
  function getOwners() external view returns (address[] memory);

  //======================================== IFallbackManager =====================================

  /**
   * @notice Set Fallback Handler to `handler` for the Safe.
   * @dev Only fallback calls without value and with data will be forwarded.
   *      This can only be done via a Safe transaction.
   *      Cannot be set to the Safe itself.
   * @param handler contract to handle fallback calls.
   */
  function setFallbackHandler(address handler) external;
}

contracts/interfaces/ITransferLegacyContract.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

import {TransferLegacyStruct} from "../libraries/TransferLegacyStruct.sol";

interface ITransferLegacy {
  function creator() external view returns (address);
  
  function delayLayer2() external view returns (uint256);

  function delayLayer3() external view returns (uint256);

  function initialize(
    uint256 legacyId_,
    address owner_,
    TransferLegacyStruct.Distribution[] calldata distributions_,
    TransferLegacyStruct.LegacyExtraConfig calldata config_,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_,
    address premiumSetting_,
    address creator_,
    address safeGuard_,
    address _uniswapRouter,
    address _weth,
    address _paymentContract,
    string[] calldata nicknames,
    string calldata nickName2,
    string calldata nickName3
  ) external returns (uint256 numberOfBeneficiaries);

  function setActivationTrigger(address sender_, uint256 lackOfOutgoingTxRange_) external;

  function setLegacyDistributions(
    address sender_,
    TransferLegacyStruct.Distribution[] calldata distributions_,
    string[] calldata nicknames
  ) external returns (uint256 numberOfBeneficiaries);

  function setDelayAndLayer23Distributions(
    address sender_,
    uint256 delayLayer2_,
    uint256 delayLayer3_,
    string calldata nickName2,
    string calldata nickName3,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_
  ) external;

  function activeLegacy(address guardAddress_, address[] calldata assets_, bool isETH_, address bene_) external;

  function checkActiveLegacy(address guardAddress_) external view returns (bool);

  function getDistribution(uint8 layer, address beneficiary) external returns (uint256);

  function setLayer23Distributions(address sender_, uint8 layer_,string calldata nickname_, TransferLegacyStruct.Distribution calldata distribution_) external;

  function setDelayLayer23(address sender_, uint256 delayLayer2_, uint256 delayLayer3_) external;

  function setLegacyName(string calldata legacyName_) external;
  
  function getBeneficiaryLayer(address beneficiary) external view returns (uint8);

  function getLayer() external view  returns (uint8)  ;

  //function setSwapSettings(TransferLegacyStruct.Swap calldata swap, address _paymentContract) external;
}

contracts/interfaces/ITransferLegacyEOAContract.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

import {TransferLegacyStruct} from "../libraries/TransferLegacyStruct.sol";
interface ITransferEOALegacy {
  function creator() external view returns (address);

  function delayLayer2() external view returns (uint256);

  function delayLayer3() external view returns (uint256);

  function initialize(
    uint256 legacyId_,
    address owner_,
    TransferLegacyStruct.Distribution[] calldata distributions_,
    TransferLegacyStruct.LegacyExtraConfig calldata config_,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_,
    address _premiumSetting,
    address _paymentContract,
    address _router,
    address _weth,
    string[] calldata nicknames,
    string calldata nickName2,
    string calldata nickName3
  ) external returns (uint256 numberOfBeneficiaries);
  function setActivationTrigger(address sender_, uint256 lackOfOutgoingTxRange_) external;

  function setLegacyDistributions(
    address sender_,
    TransferLegacyStruct.Distribution[] calldata distributions_,
    string[] calldata nicknames
  ) external returns (uint256 numberOfBeneficiaries);

  function setDelayAndLayer23Distributions(
    address sender_,
    uint256 delayLayer2_,
    uint256 delayLayer3_,
    string calldata nickName2,
    string calldata nickName3,
    TransferLegacyStruct.Distribution calldata layer2Distribution_,
    TransferLegacyStruct.Distribution calldata layer3Distribution_
  ) external;

  function activeAlive(address sender_) external;

  function activeLegacy(address[] calldata assets_, bool isETH_, address bene_) external;

  function activeLegacyAndUnswap(
    address[] calldata assets_,
    address bene_,
    uint256 amountOutMin_,
    uint256 deadline_
  ) external;

  function deleteLegacy(address sender_) external;

  function withdraw(address sender_, uint256 amount_) external;

  function checkActiveLegacy() external view returns (bool);

  function getDistribution(uint8 layer, address beneficiary) external returns (uint256);

  function setLayer23Distributions(
    address sender_,
    uint8 layer_,
    string calldata nickname_,
    TransferLegacyStruct.Distribution calldata distribution_
  ) external;

  function setDelayLayer23(address sender_, uint256 delayLayer2_, uint256 delayLayer3_) external;

  function setLegacyName(string calldata legacyName_, address sender_) external;

  function getBeneficiaryLayer(address beneficiary) external view returns (uint8);

  function getLayer() external view returns (uint8);

  //function setSwapSettings(address _router, address _weth,address _paymentContract) external ;

  function eoaStorageToken() external view returns (address);

  function autoSwap(
    address sender_,
    TransferLegacyStruct.EOALegacyETHSwap calldata swap_
  ) external payable;

  function unswap(
    address sender_,
    uint256 amountIn_,
    uint256 amountOutMin_,
    uint256 deadline_
  ) external;
}

contracts/interfaces/IUniswapV2Factory.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

contracts/interfaces/IUniswapV2Router01.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint256 amountADesired,
        uint256 amountBDesired,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);
    function addLiquidityETH(
        address token,
        uint256 amountTokenDesired,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountA, uint256 amountB);
    function removeLiquidityETH(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountToken, uint256 amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint256 amountA, uint256 amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint256 amountToken, uint256 amountETH);
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    function swapExactETHForTokens(uint256 amountOutMin, address[] calldata path, address to, uint256 deadline)
        external
        payable
        returns (uint256[] memory amounts);
    function swapTokensForExactETH(uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline)
        external
        returns (uint256[] memory amounts);
    function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline)
        external
        returns (uint256[] memory amounts);
    function swapETHForExactTokens(uint256 amountOut, address[] calldata path, address to, uint256 deadline)
        external
        payable
        returns (uint256[] memory amounts);

    function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB);
    function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external pure returns (uint256 amountOut);
    function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) external pure returns (uint256 amountIn);
    function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
    function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
}

contracts/interfaces/IUniswapV2Router02.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

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

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint256 amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
}

contracts/interfaces/IWETH.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

/// @notice Minimal WETH interface for wrapping/unwrapping ETH 1:1.
interface IWETH {
  function deposit() external payable;
  function withdraw(uint256 amount) external;
}

contracts/libraries/ArrayUtils.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

library ArrayUtils {
    function makeAddressArray(address addr) internal pure returns (address[] memory) {
        address[] memory arr = new address[](1);
        arr[0] = addr;
        return arr;
    }

    function makeStringArray(string memory str) internal pure returns (string[] memory) {
        string[] memory arr = new string[](1);
        arr[0] = str;
        return arr;
    }
}

contracts/libraries/MultisigLegacyStruct.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

library MultisigLegacyStruct {
  struct LegacyExtraConfig {
    uint128 minRequiredSignatures;
    uint128 lackOfOutgoingTxRange;
  }
}

contracts/libraries/NotifyLib.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/utils/Strings.sol";

library NotifyLib {
    struct BeneReceived {
    string name;
    address beneAddress;
    string[] listAssetName;
    uint256[] listAmount;
  }

  struct ListAsset {
    address listToken;
    uint256 listAmount;
    string listAssetName;
  }
  
  enum NotifyType {
    None, //0
    BeforeActivation, //1
    BeforeLayer2, //2
    BeforeLayer3, //3
    ReadyToActivate, //4
    Layer2ReadyToActivate, //5
    Layer3ReadyToActivate, //6
    Activated, //7
    ContractActivated, //8
    OwnerReset //9
  }

  enum RecipientType {
    Owner,
    Beneficiary,
    Secondline,
    Thirdline
  }


  
}

contracts/libraries/TransferLegacyStruct.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

library TransferLegacyStruct {
  struct LegacyExtraConfig {
    uint256 lackOfOutgoingTxRange;
    uint256 delayLayer2;
    uint256 delayLayer3;
  }

  struct Distribution {
    address user;
    uint256 percent;
  }

  struct Swap {
    address router;
    address weth;
  }

  struct EOALegacyETHSwap {
    address storageToken;
    uint256 amountOutMin;
    uint256 deadline;
  }
}

contracts/premium/PremiumSetting.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;

import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../interfaces/ISafeWallet.sol";
import "../interfaces/IPremiumLegacy.sol";
import "../interfaces/IPremiumAutomationManager.sol";
import "../interfaces/IPremiumSendMail.sol";
import "../interfaces/IPremiumSetting.sol";
import "../libraries/ArrayUtils.sol";

import {TransferLegacyStruct} from "../libraries/TransferLegacyStruct.sol";

contract PremiumSetting is OwnableUpgradeable, IPremiumSetting {
  struct UserConfig {
    string ownerName;
    string ownerEmail;
    uint256 timePriorActivation;
  }
  struct EmailMapping {
    address addr;
    string email;
    string name;
  }
  struct LegacyConfig {
    EmailMapping[] cosigners;
    EmailMapping[] beneficiaries;
    EmailMapping secondLine;
    EmailMapping thirdLine;
  }

  mapping(address => uint) public premiumExpired; // timestamp that premium package ends
  mapping(address => UserConfig) public userConfigs;
  mapping(address => LegacyConfig) public legacyCfgs;
  mapping(uint256 => address) private legacyCodeToAddress;
  mapping(address => uint256) private legacyAddressToCode;

  address public premiumRegistry; // contract serves for register premium package  & payment
  address public transferLegacyContractRouter;
  address public transferLegacyEOAContractRouter;
  address public multisigLegacyContractRouter;

  IPremiumAutomationManager public premiumAutomationManager;
  IPremiumSendMail public premiumSendMail;

  mapping(address => address[]) private legacyQueuedToAddCronjob; // legacy that user created when not subcribe premium

  /* Event */
  event PremiumTimeUpdated(address indexed user, uint256 newExpiredTime);
  event PremiumReset(address indexed user);
  event UserConfigUpdated(address indexed user, string name, string email, uint256 timePriorActivation);
  event LegacyReminderUpdated(
    address indexed user,
    uint256 legacyId,
    address legacyAddress,
    uint128 legacyType,
    EmailMapping[] cosigners,
    EmailMapping[] beneficiaries,
    EmailMapping secondLine,
    EmailMapping thirdLine
  );

  event BeneficiariesEmailSync(address indexed user, uint256 legacyId, address legacyAddress, uint128 legacyType, EmailMapping[] beneficiaries);
  event SecondLineEmailReset(address indexed user, uint256 legacyId, address legacyAddress, uint128 legacyType);
  event ThirdLineEmailReset(address indexed user, uint256 legacyId, address legacyAddress, uint128 legacyType);
  event LegacyConfigReset(address indexed user, uint256 legacyId, address legacyAddress, uint128 legacyType);
  event WatcherUpdated(
    address indexed user,
    uint256 legacyId,
    address legacyAddress,
    uint legacyType,
    string[] name,
    address[] watchers,
    bool[] isFullVisibility
  );
  event WatcherReset(address indexed user, uint256 legacyId, address legacyAddress, uint legacyType);
  event LegacyPrivateCodeSet(uint256 legacyId, address legacyAddress, uint128 legacyType, uint256 code);

  error LengthMismatch();
  error UserConfigNotSet();
  error InvalidParamAddress();

  /* Modifier */
  modifier onlyPremium(address user) {
    require(isPremium(user), "Premium only");
    _;
  }

  modifier onlyRouter() {
    require(
      msg.sender == transferLegacyContractRouter ||
        msg.sender == transferLegacyEOAContractRouter ||
        msg.sender == multisigLegacyContractRouter ||
        msg.sender == owner(),
      "Router only"
    );
    _;
  }

  modifier onlyLegacy() {
    address router = IPremiumLegacy(msg.sender).router();
    if (msg.sender != owner()) {
      require(
        router == transferLegacyContractRouter || router == transferLegacyEOAContractRouter || router == multisigLegacyContractRouter,
        "Only Legacy"
      );
    }
    _;
  }

  modifier requireUserConfig(address user) {
    if(bytes(userConfigs[user].ownerName).length == 0) revert UserConfigNotSet();
    if(userConfigs[user].timePriorActivation== 0) revert UserConfigNotSet();
    if(bytes(userConfigs[user].ownerEmail).length == 0) revert UserConfigNotSet();
    _;
  }

  constructor () {
    _disableInitializers();
  }

  function initialize() public initializer {
    __Ownable_init(msg.sender);
  }

  function setParams(
    address _premiumRegistry,
    address _transferLegacyContractRouter,
    address _transferLegacyEOAContractRouter,
    address _multisigLegacyContractRouter
  ) external onlyOwner {
    if (_premiumRegistry == address(0)) revert InvalidParamAddress();
    if(_transferLegacyContractRouter == address(0))  revert InvalidParamAddress();
    if(_transferLegacyEOAContractRouter == address(0)) revert InvalidParamAddress();
    if(_multisigLegacyContractRouter == address(0)) revert InvalidParamAddress();

    premiumRegistry = _premiumRegistry;
    transferLegacyContractRouter = _transferLegacyContractRouter;
    transferLegacyEOAContractRouter = _transferLegacyEOAContractRouter;
    multisigLegacyContractRouter = _multisigLegacyContractRouter;
  }

  function setUpReminder(address _premiumAutomationManager, address _premiumSendMail) external onlyOwner {
    if(_premiumAutomationManager == address(0)) revert InvalidParamAddress();
    if(_premiumSendMail == address(0)) revert InvalidParamAddress();
    premiumAutomationManager = IPremiumAutomationManager(_premiumAutomationManager);
    premiumSendMail = IPremiumSendMail(_premiumSendMail);
  }

  /* USER FUNCTIONS */
  ///@notice user set up emails reminder / edit configs
  ///@param timePriorActivation The time (in seconds) before the scheduled activation when email reminders should be sent.
  function setReminderConfigs(
    string calldata name,
    string calldata ownerEmail,
    uint256 timePriorActivation,
    address[] calldata legacyAddresses,
    LegacyConfig[] calldata legacyData
  ) external onlyPremium(msg.sender) {
    require(legacyAddresses.length == legacyData.length, "Length mismatch");
    require(timePriorActivation > 0, "timePriorActivation > 0");

    //update user configs
    _updateUserConfig(msg.sender, name, ownerEmail, timePriorActivation);

    //update legacy configs
    for (uint256 i = 0; i < legacyAddresses.length; i++) {
      _updateLegacyConfig(legacyAddresses[i], legacyData[i]);
    }
  }

  ///@notice update email and timePriorActivation
  ///@param timePriorActivation The time (in seconds) before the scheduled activation when email reminders should be sent.
  function updateUserConfig(string calldata name, string calldata ownerEmail, uint256 timePriorActivation) external onlyPremium(msg.sender) {
    _updateUserConfig(msg.sender, name, ownerEmail, timePriorActivation);
  }

  function updateLegacyConfig(address[] calldata legacyAddresses, LegacyConfig[] calldata legacyData) external onlyPremium(msg.sender) {
    require(legacyAddresses.length == legacyData.length, "Length mismatch");
    for (uint256 i = 0; i < legacyAddresses.length; i++) {
      _updateLegacyConfig(legacyAddresses[i], legacyData[i]);
    }
  }

  function clearLegacyConfig(address[] calldata legacyAddresses) external onlyPremium(msg.sender) {
    for (uint256 i = 0; i < legacyAddresses.length; i++) {
      IPremiumLegacy transferLegacy = IPremiumLegacy(legacyAddresses[i]);
      require(msg.sender == transferLegacy.creator(), "only legacy creator");
      _clearLegacyConfig(legacyAddresses[i]);
      emit LegacyConfigReset(msg.sender, transferLegacy.getLegacyId(), legacyAddresses[i], transferLegacy.LEGACY_TYPE());
    }
  }

  /// @dev set premiumExpired of an adress to 0
  function resetPremium(address user) external onlyOwner {
    require(premiumExpired[user] != 0, "Not an premium user");
    premiumExpired[user] = 0;
    emit PremiumReset(user);
  }

  /// @dev called by the PremiumRegistry contract to update a user's premium expiration time.
  /// @param duration amount of time (in seconds) of the premium package plan
  function updatePremiumTime(address user, uint256 duration) external {
    require(msg.sender == premiumRegistry, "_premiumRegistry only");
    require(premiumExpired[user] <= block.timestamp, "Already premium");
    if (duration >= type(uint256).max - block.timestamp) {
      premiumExpired[user] = type(uint256).max;
    } else {
      premiumExpired[user] = block.timestamp + duration;
    }

    emit PremiumTimeUpdated(user, premiumExpired[user]);

    //add queued legacy to cronjob
    if (address(premiumAutomationManager) != address(0)) {
      if (legacyQueuedToAddCronjob[user].length > 0) {
        premiumAutomationManager.addLegacyCronjob(user, legacyQueuedToAddCronjob[user]);
        delete legacyQueuedToAddCronjob[user];
      } 
    }
  }

  /* LEGACY ROUTER FUNCTIONS*/
  ///@dev router call this function when update legacy to remove email that not belong to any beneficiaries
  function syncBeneficiariesEmails(
    address user,
    address legacyAddress,
    TransferLegacyStruct.Distribution[] calldata newDistributions_
  ) external onlyRouter {
    EmailMapping[] storage beneficiaries = legacyCfgs[legacyAddress].beneficiaries;
    //remove old emails
    for (uint256 i = 0; i < beneficiaries.length; i++) {
      if (!_contains(newDistributions_, beneficiaries[i].addr)) {
        uint lastIndex = beneficiaries.length - 1;
        if (i != lastIndex) {
          beneficiaries[i] = beneficiaries[lastIndex]; // swap
        }
        beneficiaries.pop();
      }
    }

    IPremiumLegacy transferLegacy = IPremiumLegacy(legacyAddress);
    emit BeneficiariesEmailSync(user, transferLegacy.getLegacyId(), legacyAddress, transferLegacy.LEGACY_TYPE(), beneficiaries);
  }

  function resetLayerEmail(address user, address legacyAddress, uint8 layer) external onlyRouter {
    IPremiumLegacy transferLegacy = IPremiumLegacy(legacyAddress);
    require(layer == 2 || layer == 3, "invalid layer");
    if (layer == 2) {
      delete legacyCfgs[legacyAddress].secondLine;
      emit SecondLineEmailReset(user, transferLegacy.getLegacyId(), legacyAddress, transferLegacy.LEGACY_TYPE());
    } else {
      delete legacyCfgs[legacyAddress].thirdLine;
      emit ThirdLineEmailReset(user, transferLegacy.getLegacyId(), legacyAddress, transferLegacy.LEGACY_TYPE());
    }
  }

  function setPrivateCodeAndCronjob(address user, address legacyAddress) external onlyRouter {
    _setPrivateCodeIfNeeded(legacyAddress);
    address[] memory legacyAddresses = new address[](1);
    legacyAddresses[0] = legacyAddress;
    if (isPremium(user) && address(premiumAutomationManager) != address(0)) {
      premiumAutomationManager.addLegacyCronjob(user, legacyAddresses);
    } else {
      legacyQueuedToAddCronjob[user].push(legacyAddress);
    }
  }

  function triggerOwnerResetReminder(address legacyAddress) external onlyRouter {
    IPremiumLegacy legacy = IPremiumLegacy(legacyAddress);
    address creator = legacy.creator();
    if (!isPremium(creator)) return;
    if (address(premiumSendMail) == address(0)) return;

    //specify which layer need to send mail
    uint8 layer = IPremiumLegacy(legacy).getLayer();
    string memory contractName = legacy.getLegacyName();

    (, string[] memory beneEmails, string[] memory beneNames) = getBeneficiaryData(legacyAddress);
    premiumSendMail.sendMailOwnerResetToBene(beneNames, beneEmails, contractName);

    if (layer >= 2) {
      (, string memory layer2Email, string memory layer2Name) = getSecondLineData(legacyAddress);
      if (bytes(layer2Email).length > 0) {
        premiumSendMail.sendMailOwnerResetToBene(ArrayUtils.makeStringArray(layer2Name), ArrayUtils.makeStringArray(layer2Email), contractName);
      }
    }

    if (layer == 3) {
      (, string memory layer3Email, string memory layer3Name) = getThirdLineData(legacyAddress);
      if (bytes(layer3Email).length > 0) {
        premiumSendMail.sendMailOwnerResetToBene(ArrayUtils.makeStringArray(layer3Name), ArrayUtils.makeStringArray(layer3Email), contractName);
      }
    }
  }

  function triggerActivationMultisig(address legacyAddress) external onlyRouter {
    IPremiumLegacy legacy = IPremiumLegacy(legacyAddress);

    address creator = legacy.creator();
    (, string memory ownerEmail, ) = getUserData(creator);
    address safeWallet = legacy.getLegacyOwner();
    string memory contractName = legacy.getLegacyName();

    if (!isPremium(creator)) return;
    (, string[] memory beneEmails, string[] memory beneNames) = getBeneficiaryData(legacyAddress);
    if (address(premiumSendMail) == address(0)) return;
    premiumSendMail.sendMailActivatedMultisig(beneNames, beneEmails, contractName, safeWallet);

    (address []  memory  beneficiares ,,) = IPremiumLegacy(legacy).getLegacyBeneficiaries();
    string [] memory names = new string[](beneficiares.length);
     for (uint256 i = 0; i < beneficiares.length; i++) {
        names[i] = IPremiumLegacy(legacy).getBeneNickname(beneficiares[i]);
    }
    premiumSendMail.sendActivatedMutisigToOwner(ownerEmail, contractName, legacyAddress, tx.origin, safeWallet, names, beneficiares);
  }

  function triggerActivationTransferLegacy(
    NotifyLib.ListAsset[] memory listAsset,
    NotifyLib.BeneReceived[] memory _listBeneReceived,
    bool remaining
  ) external onlyLegacy{
    IPremiumLegacy legacy = IPremiumLegacy(msg.sender);
    address creator = legacy.creator();
    address safeWallet = legacy.getLegacyOwner();
    string memory contractName = legacy.getLegacyName();

    if (!isPremium(creator)) return;

    uint8 layerActivated = legacy.getBeneficiaryLayer(tx.origin);

    if (address(premiumSendMail) == address(0)) return;
    (, string memory ownerEmail, ) = getUserData(creator);

    //send email to owner
    if (bytes(ownerEmail).length > 0) {
      premiumSendMail.sendEmailContractActivatedToOwner(
        ownerEmail,
        contractName,
        tx.origin, // the beneficiary that activates legacy
        block.timestamp,
        safeWallet,
        listAsset,
        _listBeneReceived,
        msg.sender, // legacy contract address
        remaining
      );
    }

    //send email to bene
    (address [] memory beneficiaries, address layer2, address layer3) = IPremiumLegacy(msg.sender).getLegacyBeneficiaries();

    address [] memory listToken = new address [](listAsset.length);
    for(uint256 i = 0; i < listAsset.length; i++) {
      listToken[i] = listAsset[i].listToken;
    }
    if( layerActivated ==1) {
      (address [] memory cfgBeneficiaries, string [] memory cfgBeneEmails, string [] memory cfgBeneNames) = getBeneficiaryData(msg.sender);
      for(uint256 i = 0 ; i < cfgBeneficiaries.length ; i++){
        if (cfgBeneficiaries[i] == beneficiaries[i] && bytes(cfgBeneEmails[i]).length >0){
          premiumSendMail.sendEmailActivatedToBene(
            cfgBeneNames[i],
            cfgBeneEmails[i],
            contractName,
            listToken,
            _listBeneReceived[i].listAmount,
            _listBeneReceived[i].listAssetName, 
            msg.sender, //contract address
            remaining
          );
        }
      }
      return;
    }

    if (layerActivated == 2){
      (address cfgLayer2Addr, string memory cfgLayer2Email, string memory cfgLayer2Name) = getSecondLineData(msg.sender);
      if(cfgLayer2Addr == layer2 && bytes(cfgLayer2Email).length >0){
            premiumSendMail.sendEmailActivatedToBene(
            cfgLayer2Name,
            cfgLayer2Email,
            contractName,
            listToken,
            _listBeneReceived[0].listAmount,
            _listBeneReceived[0].listAssetName, 
            msg.sender, //contract address
            remaining
          );
      }
      return;
    }

    //layer 3
    (address cfgLayer3Addr, string memory cfgLayer3Email, string memory cfgLayer3Name) = getThirdLineData(msg.sender);
    if(cfgLayer3Addr == layer3 && bytes(cfgLayer3Email).length > 0) {
        premiumSendMail.sendEmailActivatedToBene(
            cfgLayer3Name,
            cfgLayer3Email,
            contractName,
            listToken,
            _listBeneReceived[0].listAmount,
            _listBeneReceived[0].listAssetName, 
            msg.sender, //contract address
            remaining
          );
    }
  }

  function setWatchers(
    address legacyAddress,
    string[] calldata names,
    address[] calldata watchers,
    bool[] calldata isFullVisibility
  ) external onlyPremium(msg.sender) {
    IPremiumLegacy legacy = IPremiumLegacy(legacyAddress);
    (uint256 legacyId, , ) = legacy.getLegacyInfo();
    uint128 legacyType = legacy.LEGACY_TYPE();
    require(msg.sender == legacy.creator(), "only legacy creator");
    require(names.length == watchers.length && watchers.length == isFullVisibility.length, "length mismatch");
    require(names.length > 0, "can not set empty");
    emit WatcherUpdated(msg.sender, legacyId, legacyAddress, legacyType, names, watchers, isFullVisibility);
  }

  function clearWatcher(address[] memory legacyAddresses) external onlyPremium(msg.sender) {
    for (uint256 i = 0; i < legacyAddresses.length; i++) {
      IPremiumLegacy legacy = IPremiumLegacy(legacyAddresses[i]);
      (uint256 legacyId, , ) = legacy.getLegacyInfo();
      uint128 legacyType = legacy.LEGACY_TYPE();
      require(msg.sender == legacy.creator(), "only legacy creator");
      emit WatcherReset(msg.sender, legacyId, legacyAddresses[i], legacyType);
    }
  }

  /* INTERNAL FUNCTIONS */
  function _updateUserConfig(address user, string calldata name, string calldata ownerEmail, uint256 timePriorActivation) internal {
    require(timePriorActivation > 0, "timePriorActivation > 0");
    userConfigs[user] = UserConfig({ownerName: name, ownerEmail: ownerEmail, timePriorActivation: timePriorActivation});
    emit UserConfigUpdated(user, name, ownerEmail, timePriorActivation);
  }

  function _updateLegacyConfig(address legacyAddr, LegacyConfig calldata newCfg) internal requireUserConfig(msg.sender) {
    //prepare data
    IPremiumLegacy legacy = IPremiumLegacy(legacyAddr);
    (uint256 legacyId, address owner, ) = legacy.getLegacyInfo();
    uint128 legacyType = legacy.LEGACY_TYPE();

    require(msg.sender == legacy.creator(), "only legacy creator");
    _clearLegacyConfig(legacyAddr);

    // Set cosigners (safe legacy) -> check cosigner valid
    LegacyConfig storage cfg = legacyCfgs[legacyAddr];
    if (newCfg.cosigners.length > 0) {
      require(legacyType != 3, "Only Safe legacy allowed to config cosigners");
      ISafeWallet safe = ISafeWallet(owner);
      require(newCfg.cosigners.length == safe.getOwners().length, "Cosginer length mismatch");
      for (uint256 j = 0; j < newCfg.cosigners.length; j++) {
        address cosigner = newCfg.cosigners[j].addr;
        require(safe.isOwner(cosigner), "invalid cosigner address");
        cfg.cosigners.push(newCfg.cosigners[j]);
      }
    }

    // Set beneficiaries - validate address in legacy by checking distribution
    if (legacyType == 1) {
      address[] memory beneficiaries = legacy.getBeneficiaries();
      for (uint256 j = 0; j < newCfg.beneficiaries.length; j++) {
        address cfgBeneficiary = newCfg.beneficiaries[j].addr;
        require(cfgBeneficiary == beneficiaries[j], "beneficiary not match in legacy");
        cfg.beneficiaries.push(newCfg.beneficiaries[j]);
      }
    } else {
      for (uint256 j = 0; j < newCfg.beneficiaries.length; j++) {
        address beneficiary = newCfg.beneficiaries[j].addr;
        require(legacy.getDistribution(1, beneficiary) != 0, "invalid beneficiary address");
        cfg.beneficiaries.push(newCfg.beneficiaries[j]);
      }
    }

    // Set second and third line - validate address in legacy by checking distribution
    if (newCfg.secondLine.addr == address(0)) {
      require(bytes(newCfg.secondLine.email).length == 0, "secondline invalid pair of address and email");
    } else {
      require(legacy.getDistribution(2, newCfg.secondLine.addr) != 0, "invalid secondline address");
      cfg.secondLine = newCfg.secondLine;
    }
    if (newCfg.thirdLine.addr == address(0)) {
      require(bytes(newCfg.thirdLine.email).length == 0, "thirdline invalid pair of address and email");
    } else {
      require(legacy.getDistribution(3, newCfg.thirdLine.addr) != 0, "invalid thirdline address");
      cfg.thirdLine = newCfg.thirdLine;
    }

    emit LegacyReminderUpdated(
      msg.sender,
      legacyId,
      legacyAddr,
      legacyType,
      newCfg.cosigners,
      newCfg.beneficiaries,
      newCfg.secondLine,
      newCfg.thirdLine
    );
  }

  function _clearLegacyConfig(address legacyAddress) internal {
    delete legacyCfgs[legacyAddress];
  }

  ///@notice set private code for legacy of premium user
  function _setPrivateCodeIfNeeded(address legacyAddress) internal {
    IPremiumLegacy legacy = IPremiumLegacy(legacyAddress);
    if (legacyAddressToCode[legacyAddress] != 0) return; //already set
    uint256 attempt = 0;
    uint256 code;

    do {
      code = (uint256(keccak256(abi.encodePacked(legacyAddress, block.timestamp, attempt))) % 9_000_000) + 1_000_000;
      attempt++;
      require(attempt < 20, "Too many attempts to generate unique code");
    } while (legacyCodeToAddress[code] != address(0)); //avoid duplicate

    legacyAddressToCode[legacyAddress] = code;
    legacyCodeToAddress[code] = legacyAddress;
    emit LegacyPrivateCodeSet(legacy.getLegacyId(), legacyAddress, legacy.LEGACY_TYPE(), code);
  }

  ///@dev to check if a beneficiary of legacy has an email configured
  function _contains(TransferLegacyStruct.Distribution[] calldata list, address addr) internal pure returns (bool) {
    for (uint i = 0; i < list.length; i++) {
      if (list[i].user == addr) return true;
    }
    return false;
  }

  function isSafeLegacy(address legacyAddress) public view returns (bool) {
    address legacyOwner = IPremiumLegacy(legacyAddress).getLegacyOwner();
    return legacyOwner.code.length > 0;
  }

  /*  VIEWS FUNCTIONS */
  function isPremium(address user) public view returns (bool) {
    return (block.timestamp < premiumExpired[user]);
  }

  function getUserData(address user) public view returns (string memory, string memory, uint256) {
    return (userConfigs[user].ownerName, userConfigs[user].ownerEmail, userConfigs[user].timePriorActivation);
  }

  function getCosignerData(address legacyAddress) external view returns (address[] memory, string[] memory, string[] memory) {
    EmailMapping[] storage list = legacyCfgs[legacyAddress].cosigners;

    uint256 len = list.length;
    address[] memory addrs = new address[](len);
    string[] memory emails = new string[](len);
    string[] memory names = new string[](len);

    for (uint256 i = 0; i < len; i++) {
      addrs[i] = list[i].addr;
      emails[i] = list[i].email;
      names[i] = list[i].name;
    }

    return (addrs, emails, names);
  }

  function getBeneficiaryData(address legacyAddress) public view returns (address[] memory, string[] memory, string[] memory) {
    EmailMapping[] storage list = legacyCfgs[legacyAddress].beneficiaries;

    uint256 len = list.length;
    address[] memory addrs = new address[](len);
    string[] memory emails = new string[](len);
    string[] memory names = new string[](len);

    for (uint256 i = 0; i < len; i++) {
      addrs[i] = list[i].addr;
      emails[i] = list[i].email;
      names[i] = list[i].name;
    }

    return (addrs, emails, names);
  }

  function getSecondLineData(address legacyAddress) public view returns (address, string memory, string memory) {
    EmailMapping storage second = legacyCfgs[legacyAddress].secondLine;
    return (second.addr, second.email, second.name);
  }

  function getThirdLineData(address legacyAddress) public view returns (address, string memory, string memory) {
    EmailMapping storage third = legacyCfgs[legacyAddress].thirdLine;
    return (third.addr, third.email, third.name);
  }

  function getTimeAhead(address user) public view returns (uint256) {
    return userConfigs[user].timePriorActivation;
  }

  function getLegacyCode(address legacyAddress) external view onlyOwner returns (uint256) {
    return legacyAddressToCode[legacyAddress];
  }

  ///@dev FE use to fetch all legacy trigger timestamp
  function getBatchLegacyTriggerTimestamp(address[] memory legacyAddresses) external view returns (uint256[][] memory) {
    uint256[][] memory result = new uint256[][](legacyAddresses.length);
    for (uint256 i = 0; i < legacyAddresses.length; i++) {
      (uint256 t1, uint256 t2, uint256 t3) = IPremiumLegacy(legacyAddresses[i]).getTriggerActivationTimestamp();

      uint256[] memory timestamps = new uint256[](3);
      timestamps[0] = t1;
      timestamps[1] = t2;
      timestamps[2] = t3;

      result[i] = timestamps;
    }
    return result;
  }
}

contracts/term/VerifierTerm.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

contract EIP712LegacyVerifier is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable {
  struct Legacy {
    address legacyAddress;
    uint256 timestamp;
    bytes signature;
  }

  mapping(address => Legacy[]) public legacySigned;
  address public transferLegacyEOA;
  address public transferLegacy;
  address public multisigLegacy;
  mapping(bytes => uint256) signatureUsed;

  event LegacySigned(address indexed user, uint256 legacyId, uint256 timestamp);

  error InvalidSignature();
  error SignatureUsed();
  error TimestampOutOfRange();
  error InvalidV();
  error HexLengthInsufficient();
  error ZeroAddressNotAllowed();
  error UnauthorizedCaller();
  error AlreadyInit();

  string private constant MESSAGE_PREFIX = "By proceeding with creating a new contract, I agree to 10102's Terms of Service";
  uint256 private constant MAX_PAST_OFFSET = 30 minutes;
  uint256 private constant MAX_FUTURE_OFFSET = 30 minutes;

  constructor () {
    _disableInitializers();
  }

  function initialize(address initialOwner) public initializer {
    __ReentrancyGuard_init();
    __Ownable_init(initialOwner);
  }

  modifier onlyRouter() {
    if (msg.sender != transferLegacy && msg.sender != transferLegacyEOA && msg.sender != multisigLegacy) revert UnauthorizedCaller();
    _;
  }

  function setRouterAddresses(address _transferLegacyEOA, address _transferLegacy, address _multisigLegacy) external onlyOwner {
    //if (transferLegacyEOA != address(0)) revert AlreadyInit();

    if (_transferLegacyEOA == address(0) || _transferLegacy == address(0) || _multisigLegacy == address(0)) {
      revert ZeroAddressNotAllowed();
    }

    transferLegacyEOA = _transferLegacyEOA;
    transferLegacy = _transferLegacy;
    multisigLegacy = _multisigLegacy;
  }

  /// @notice Store a legacy agreement signed via signMessage
  function storeLegacyAgreement(address user, address legacyAddress, uint256 timestamp, bytes calldata signature) external nonReentrant onlyRouter {
    uint256 nowTs = block.timestamp;
    if (timestamp < nowTs - MAX_PAST_OFFSET || timestamp > nowTs + MAX_FUTURE_OFFSET) {
      revert TimestampOutOfRange();
    }
    if (signatureUsed[signature] != 0) revert SignatureUsed();

    string memory message = generateMessage(timestamp);
    bytes32 ethSignedMessageHash = _getEthSignedMessageHash(message);
    address recovered = recoverSigner(ethSignedMessageHash, signature);
    if (recovered != user) {
      revert InvalidSignature();
    }

    legacySigned[user].push(Legacy({legacyAddress: legacyAddress, timestamp: timestamp, signature: signature}));
    signatureUsed[signature] = timestamp;

    emit LegacySigned(user, uint256(uint160(legacyAddress)), timestamp);
  }

  function _getEthSignedMessageHash(string memory message) internal pure returns (bytes32) {
    return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", _uintToString(bytes(message).length), message));
  }

  function getUserLegacyCount(address user) external view returns (uint256) {
    return legacySigned[user].length;
  }

  function getUserLegacy(
    address user,
    uint256 index
  ) external view returns (address legacyAddress, uint256 timestamp, string memory message, bytes memory signature) {
    Legacy memory legacy = legacySigned[user][index];
    string memory termString = generateMessage(timestamp);
    return (legacy.legacyAddress, legacy.timestamp, termString, legacy.signature);
  }

  function recoverSigner(bytes32 digest, bytes memory signature) public pure returns (address) {
    if (signature.length != 65) {
      revert InvalidSignature();
    }

    bytes32 r;
    bytes32 s;
    uint8 v;

    assembly {
      r := mload(add(signature, 0x20))
      s := mload(add(signature, 0x40))
      v := byte(0, mload(add(signature, 0x60)))
    }

    // Validate s is in lower half of secp256k1 curve order (EIP-2)
    if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
      revert InvalidSignature();
    }

    if (v < 27) v += 27;
    if (v != 27 && v != 28) {
      revert InvalidV();
    }

    return ecrecover(digest, v, r, s);
  }

   function generateMessage(uint256 timestamp) public pure returns (string memory) {
    return string.concat(MESSAGE_PREFIX, " at timestamp ", _uintToString(timestamp), ".");
  }



  function _uintToString(uint256 value) internal pure returns (string memory) {
    if (value == 0) return "0";
    uint256 temp = value;
    uint256 digits;
    while (temp != 0) {
      digits++;
      temp /= 10;
    }
    bytes memory buffer = new bytes(digits);
    while (value != 0) {
      digits -= 1;
      buffer[digits] = bytes1(uint8(48 + (value % 10)));
      value /= 10;
    }
    return string(buffer);
  }

  function _toHexString(address account) internal pure returns (string memory) {
    return _toHexString(uint256(uint160(account)), 20);
  }

  function _toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
    bytes16 _hexSymbols = "0123456789abcdef";
    bytes memory buffer = new bytes(2 + length * 2);
    buffer[0] = "0";
    buffer[1] = "x";
    for (uint256 i = 2 + length * 2; i > 2; --i) {
      buffer[i - 1] = _hexSymbols[value & 0xf];
      value >>= 4;
    }
    if (value != 0) revert HexLengthInsufficient();
    return string(buffer);
  }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.