Sepolia Testnet

Contract

0xDF3a52358fA9aA82A0BC364a41376b42D0404D13

Overview

ETH Balance

0 ETH

More Info

Multichain Info

N/A
Transaction Hash
Method
Block
From
To
Amount

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PremiumMailBeforeActivation

Compiler Version
v0.8.20+commit.a1b79de6

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion, MIT license

Contract Source Code (Solidity Standard Json-Input format)

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@chainlink/contracts/src/v0.8/functions/v1_0_0/interfaces/IFunctionsRouter.sol";
import {FunctionsRequest} from "@chainlink/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsRequest.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "../libraries/NotifyLib.sol";
contract PremiumMailBeforeActivation is OwnableUpgradeable {
  using FunctionsRequest for FunctionsRequest.Request;

  //CHAINLINK FUNCTION
  address public router = 0xb83E47C2bC239B3bf370bc41e1459A34b41238D0;
  bytes32 public donID = 0x66756e2d657468657265756d2d7365706f6c69612d3100000000000000000000;
  uint64 public subscriptionId;
  
  //PREMIUM CONTRACT
  address public sendMailRouter; // the only contract can call send email
  
  //MAIL SERVICE
  string private constant authHeader = "OGNlYWI2NGFmZTExNWRiYWJiMThhNGQzODAzYjE3OTI6ZDRlMDRjMmU1MTdmNWQzMjA4NjhiYmI3OTQ4ZTZiMzk=";


  // State variables
  bytes32 public s_lastRequestId;
  bytes public s_lastResponse;
  bytes public s_lastError;
  uint256 public mailId;

  //Callback gas limit
  uint32 public gasLimit = 300000;


  // email invoke name
  uint256 constant BEFORE_ACTIVATION_TO_OWNER = 7180104;
  uint256 constant BEFORE_ACTIVATION_TO_BENEFICIARY = 7180073;

  uint256 constant BEFORE_LAYER2_TO_OWNER = 7179589;
  uint256 constant BEFORE_LAYER2_TO_LAYER1 = 7180055;
  uint256 constant BEFORE_LAYER2_TO_LAYER2 = 7180019;

  uint256 constant BEFORE_LAYER3_TO_OWNER = 7180086;
  uint256 constant BEFORE_LAYER3_TO_LAYER12 = 7179998;
  uint256 constant BEFORE_LAYER3_TO_LAYER3 = 7179988;

  // Custom error type
  error UnexpectedRequestID(bytes32 requestId);

  error OnlyRouterCanFulfill();

  // Event to log responses
  event Response(bytes32 indexed requestId, bytes response, bytes err);
  event RequestSent(bytes32 indexed id);
  event RequestFulfilled(bytes32 indexed id);

  event SendMail(string to, NotifyLib.NotifyType notifyType);

  modifier onlyRouter() {
    require(msg.sender == sendMailRouter, "Only router");
    _;
  }

  function initialize(address _router, uint64 _subscriptionId, bytes32 _donId, uint32 _gasLimit, address _sendMailRouter) public initializer {
    router = _router;
    subscriptionId = _subscriptionId;
    donID = _donId;
    gasLimit = _gasLimit;
    sendMailRouter = _sendMailRouter;
    __Ownable_init(msg.sender);
  }

  /**
   * @notice Callback function for fulfilling a request
   * @param requestId The ID of the request to fulfill
   * @param response The HTTP response data
   * @param err Any errors from the Functions request
   */
  function fulfillRequest(bytes32 requestId, bytes memory response, bytes memory err) internal {
    if (s_lastRequestId != requestId) {
      revert UnexpectedRequestID(requestId); // Check if request IDs match
    }
    // Update the contract's state variables with the response and any errors
    s_lastResponse = response;
    s_lastError = err;

    // Emit an event to log the response
    emit Response(requestId, s_lastResponse, s_lastError);
  }

  function handleOracleFulfillment(bytes32 requestId, bytes memory response, bytes memory err) external {
    require(msg.sender == router, "Only router can fulfill");
    fulfillRequest(requestId, response, err);
    emit RequestFulfilled(requestId);
  }

  function sendEmailBeforeActivationToOwner(
    string memory ownerName,
    string memory contractName,
    uint256 lastTx,
    uint256 bufferTime,
    address[] memory listBene,
    string memory ownerEmail
  ) external onlyRouter {
    _sendEmailBeforeActivationToOwner(ownerName, contractName, lastTx, bufferTime, listBene, ownerEmail);
    _emitSendMail(ownerEmail, NotifyLib.NotifyType.BeforeActivation);
  }

  function sendEmailBeforeActivationToBeneficiary(
    string[] memory beneNames,
    string memory contractName,
    uint256 timeCountdown,
    string[] memory beneEmails
  ) external onlyRouter {
    for (uint256 i = 0; i < beneNames.length; i++) {
      if (bytes(beneEmails[i]).length > 0) {
        _sendEmailBeforeActivationToBeneficiary(beneNames[i], contractName, timeCountdown, beneEmails[i]);
        _emitSendMail(beneEmails[i], NotifyLib.NotifyType.BeforeActivation);
      }
    }
  }


  function sendEmailBeforeLayer2ToLayer1(
    string [] memory beneNames,
    string [] memory beneEmails,
    string memory contractName,
    uint256 x_days
  ) external onlyRouter {
    for (uint256 i = 0; i < beneNames.length; i++) {
      if (bytes(beneEmails[i]).length > 0) {
        _sendEmailBeforeLayer2ToLayer1(beneNames[i], beneEmails[i], contractName, x_days);
        _emitSendMail(beneEmails[i], NotifyLib.NotifyType.BeforeLayer2);
      }
    }
  }

  function sendEmailBeforeLayer2ToLayer2(string memory beneName, string memory beneEmail, string memory contractName, uint256 x_days) external onlyRouter {
    _sendEmailBeforeLayer2ToLayer2(beneName, beneEmail, contractName, x_days);
    _emitSendMail(beneEmail, NotifyLib.NotifyType.BeforeLayer2);
  }


  function sendEmailBeforeLayer3ToLayer12(
    string [] memory beneNames,
    string [] memory beneEmails,
    string memory contractName,
    uint256 x_day
  ) external onlyRouter {
    for (uint256 i = 0; i < beneNames.length; i++) {
      if (bytes(beneEmails[i]).length > 0) {
        _sendEmailBeforeLayer3ToLayer12(beneNames[i], beneEmails[i], contractName, x_day);
        _emitSendMail(beneEmails[i], NotifyLib.NotifyType.BeforeLayer3);
      }
    }
  }

  function sendEmailBeforeLayer3ToLayer3(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    uint256 x_day
  ) external onlyRouter {
    _sendEmailBeforeLayer3ToLayer3(beneName, beneEmail, contractName, x_day);
    _emitSendMail(beneEmail, NotifyLib.NotifyType.BeforeLayer3);
  }


  // common function
  function _sendEmailToAddressBegin(string memory to, string memory subject, uint256 templateId) private pure returns (string memory) {
    string memory formatEmailTo = string.concat(
      "const emailURL = 'https://api.mailjet.com/v3.1/send';",
      "const authHeader = 'Basic ",
      authHeader,
      "';",
      "const emailData = { Messages: ",
      "[ { From: {Email: '[email protected]', Name: '10102 Platform',},",
      "To: [ {Email: '",
      to,
      "', Name:'',},],",
      "TemplateID: ",
      Strings.toString(templateId),
      ", TemplateLanguage: true,",
      "Subject: '",
      subject,
      "',",
      "Variables: {"
    );
    return formatEmailTo;
  }

  function _sendEmailToAddressEnd() private pure returns (string memory) {
    string memory formatEmailEnd = string.concat(
      "},},],};",
      "const response = await Functions.makeHttpRequest({",
      "  url: emailURL,",
      "  method: 'POST',",
      "  headers: { 'Content-Type': 'application/json', 'Authorization': authHeader },",
      "  data: emailData",
      "});",
      "if (response.error) throw Error(`Failed to send email: ${JSON.stringify(response)}`);",
      "return Functions.encodeString('Email sent!');"
    );
    return formatEmailEnd;
  }

  //** Send email BeforeActivation */ -> enum = 1

  // 1. To owner
  // 2. To beneficiary

  function _sendEmailBeforeActivationToOwner(
    string memory ownerName,
    string memory contractName,
    uint256 lastTx,
    uint256 bufferTime,
    address[] memory listBene,
    string memory ownerEmail
  ) public returns (bytes32 requestId) {
    string memory subject = string.concat("Reminder - [", contractName, "] Nearing Activation");
    string memory listString = "list: [";
    for (uint256 i = 0; i < listBene.length; i++) {
      listString = string.concat(listString, "'", Strings.toHexString(listBene[i]), "'");
      if (i < listBene.length - 1) {
        listString = string.concat(listString, ",");
      }
    }
    listString = string.concat(listString, "]");

    string memory params = string.concat(
      "owner_name: '",
      ownerName,
      "', contract_name: '",
      contractName,
      "', last_tx: new Date(",
      Strings.toString(lastTx * 1000),
      "),  activate_date: '",
      Strings.toString(bufferTime / 86400),
      " day(s)',",
      listString
    );

    string memory source = string.concat(_sendEmailToAddressBegin(ownerEmail, subject, BEFORE_ACTIVATION_TO_OWNER), params, _sendEmailToAddressEnd());

    return _sendRequest(source);
  }

  function _sendEmailBeforeActivationToBeneficiary(
    string memory beneName,
    string memory contractName,
    uint256 timeCountdown,
    string memory beneEmail
  ) public returns (bytes32 requestId) {
    string memory subject = string.concat("Get Ready - [", contractName, "] Will Be Ready to Activate Soon");

    string memory params = string.concat(
      "bene_name: '",
      beneName,
      "', contract_name: '",
      contractName,
      "',  x_day_before_active: ",
      Strings.toString(timeCountdown)
    );

    string memory source = string.concat(
      _sendEmailToAddressBegin(beneEmail, subject, BEFORE_ACTIVATION_TO_BENEFICIARY),
      params,
      _sendEmailToAddressEnd()
    );

    return _sendRequest(source);
  }

  //Befor layer 2
  //1.To layer 1
  //2.To layer 2


  function _sendEmailBeforeLayer2ToLayer1(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    uint256 x_days
  ) public returns (bytes32 requestId) {
    string memory subject = string.concat("Reminder - Second-Line Activation for - [", contractName, "] Approaching");

    string memory params = string.concat(
      "bene_name: '",
      beneName,
      "',",
      "    contract_name: '",
      contractName,
      "',",
      "    x_days: '",
      Strings.toString(x_days),
      " day(s)',"
    );

    string memory source = string.concat(_sendEmailToAddressBegin(beneEmail, subject, BEFORE_LAYER2_TO_LAYER1), params, _sendEmailToAddressEnd());
    return _sendRequest(source);
  }

  function _sendEmailBeforeLayer2ToLayer2(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    uint256 x_days
  ) public returns (bytes32 requestId) {
    string memory subject = string.concat("You May Soon Be Eligible to Activate [", contractName, "]");

    string memory params = string.concat("bene_name: '", beneName, "',  contract_name: '", contractName, "', x_days: '", Strings.toString(x_days), " day(s)'");

    string memory source = string.concat(_sendEmailToAddressBegin(beneEmail, subject, BEFORE_LAYER2_TO_LAYER2), params, _sendEmailToAddressEnd());

    return _sendRequest(source);
  }

  //Befor layer 3
  //1.To layer 12
  //2.To layer 3

  function _sendEmailBeforeLayer3ToLayer12(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    uint256 x_day
  ) public returns (bytes32 requestId) {
    string memory subject = string.concat("Reminder - Third-Line Activation for [", contractName, "] Approaching");

    string memory params = string.concat(
      "bene_name: '",
      beneName,
      "',  contract_name: '",
      contractName,
      "',  x_days: '",
      Strings.toString(x_day),
      " day(s)',"
    );

    string memory source = string.concat(_sendEmailToAddressBegin(beneEmail, subject, BEFORE_LAYER3_TO_LAYER12), params, _sendEmailToAddressEnd());

    return _sendRequest(source);
  }

  function _sendEmailBeforeLayer3ToLayer3(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    uint256 x_day
  ) public returns (bytes32 requestId) {
    string memory subject = string.concat("You May Soon Be Eligible to Activate [", contractName, "]");

    string memory params = string.concat(
      "bene_name: '",
      beneName,
      "',  contract_name: '",
      contractName,
      "',  x_days: '",
      Strings.toString(x_day),
      " day(s)',"
    );

    string memory source = string.concat(_sendEmailToAddressBegin(beneEmail, subject, BEFORE_LAYER3_TO_LAYER3), params, _sendEmailToAddressEnd());

    return _sendRequest(source);
  }

  function _sendRequest(string memory source) internal returns (bytes32) {
    FunctionsRequest.Request memory req;
    req.initializeRequestForInlineJavaScript(source); 
    s_lastRequestId = IFunctionsRouter(router).sendRequest(subscriptionId, req.encodeCBOR(), FunctionsRequest.REQUEST_DATA_VERSION, gasLimit, donID);
    return s_lastRequestId;
  }

  function _emitSendMail(string memory to, NotifyLib.NotifyType notifyType) internal {
    mailId++;
    emit SendMail(to, notifyType);
  }
}

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

// solhint-disable-next-line interface-starts-with-i
interface AutomationCompatibleInterface {
  /**
   * @notice method that is simulated by the keepers to see if any work actually
   * needs to be performed. This method does does not actually need to be
   * executable, and since it is only ever simulated it can consume lots of gas.
   * @dev To ensure that it is never called, you may want to add the
   * cannotExecute modifier from KeeperBase to your implementation of this
   * method.
   * @param checkData specified in the upkeep registration so it is always the
   * same for a registered upkeep. This can easily be broken down into specific
   * arguments using `abi.decode`, so multiple upkeeps can be registered on the
   * same contract and easily differentiated by the contract.
   * @return upkeepNeeded boolean to indicate whether the keeper should call
   * performUpkeep or not.
   * @return performData bytes that the keeper should call performUpkeep with, if
   * upkeep is needed. If you would like to encode data to decode later, try
   * `abi.encode`.
   */
  function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);

  /**
   * @notice method that is actually executed by the keepers, via the registry.
   * The data returned by the checkUpkeep simulation will be passed into
   * this method to actually be executed.
   * @dev The input to this method should not be trusted, and the caller of the
   * method should not even be restricted to any single registry. Anyone should
   * be able call it, and the input should be validated, there is no guarantee
   * that the data passed in is the performData returned from checkUpkeep. This
   * could happen due to malicious keepers, racing keepers, or simply a state
   * change while the performUpkeep transaction is waiting for confirmation.
   * Always validate the data passed in.
   * @param performData is the data which was passed back from the checkData
   * simulation. If it is encoded, it can easily be decoded into other types by
   * calling `abi.decode`. This data should not be trusted, and should be
   * validated against the contract's current state.
   */
  function performUpkeep(bytes calldata performData) external;
}

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

import {FunctionsResponse} from "../libraries/FunctionsResponse.sol";

/// @title Chainlink Functions Router interface.
interface IFunctionsRouter {
  /// @notice The identifier of the route to retrieve the address of the access control contract
  /// The access control contract controls which accounts can manage subscriptions
  /// @return id - bytes32 id that can be passed to the "getContractById" of the Router
  function getAllowListId() external view returns (bytes32);

  /// @notice Set the identifier of the route to retrieve the address of the access control contract
  /// The access control contract controls which accounts can manage subscriptions
  function setAllowListId(bytes32 allowListId) external;

  /// @notice Get the flat fee (in Juels of LINK) that will be paid to the Router owner for operation of the network
  /// @return adminFee
  function getAdminFee() external view returns (uint72 adminFee);

  /// @notice Sends a request using the provided subscriptionId
  /// @param subscriptionId - A unique subscription ID allocated by billing system,
  /// a client can make requests from different contracts referencing the same subscription
  /// @param data - CBOR encoded Chainlink Functions request data, use FunctionsClient API to encode a request
  /// @param dataVersion - Gas limit for the fulfillment callback
  /// @param callbackGasLimit - Gas limit for the fulfillment callback
  /// @param donId - An identifier used to determine which route to send the request along
  /// @return requestId - A unique request identifier
  function sendRequest(
    uint64 subscriptionId,
    bytes calldata data,
    uint16 dataVersion,
    uint32 callbackGasLimit,
    bytes32 donId
  ) external returns (bytes32);

  /// @notice Sends a request to the proposed contracts
  /// @param subscriptionId - A unique subscription ID allocated by billing system,
  /// a client can make requests from different contracts referencing the same subscription
  /// @param data - CBOR encoded Chainlink Functions request data, use FunctionsClient API to encode a request
  /// @param dataVersion - Gas limit for the fulfillment callback
  /// @param callbackGasLimit - Gas limit for the fulfillment callback
  /// @param donId - An identifier used to determine which route to send the request along
  /// @return requestId - A unique request identifier
  function sendRequestToProposed(
    uint64 subscriptionId,
    bytes calldata data,
    uint16 dataVersion,
    uint32 callbackGasLimit,
    bytes32 donId
  ) external returns (bytes32);

  /// @notice Fulfill the request by:
  /// - calling back the data that the Oracle returned to the client contract
  /// - pay the DON for processing the request
  /// @dev Only callable by the Coordinator contract that is saved in the commitment
  /// @param response response data from DON consensus
  /// @param err error from DON consensus
  /// @param juelsPerGas - current rate of juels/gas
  /// @param costWithoutFulfillment - The cost of processing the request (in Juels of LINK ), without fulfillment
  /// @param transmitter - The Node that transmitted the OCR report
  /// @param commitment - The parameters of the request that must be held consistent between request and response time
  /// @return fulfillResult -
  /// @return callbackGasCostJuels -
  function fulfill(
    bytes memory response,
    bytes memory err,
    uint96 juelsPerGas,
    uint96 costWithoutFulfillment,
    address transmitter,
    FunctionsResponse.Commitment memory commitment
  ) external returns (FunctionsResponse.FulfillResult, uint96);

  /// @notice Validate requested gas limit is below the subscription max.
  /// @param subscriptionId subscription ID
  /// @param callbackGasLimit desired callback gas limit
  function isValidCallbackGasLimit(uint64 subscriptionId, uint32 callbackGasLimit) external view;

  /// @notice Get the current contract given an ID
  /// @param id A bytes32 identifier for the route
  /// @return contract The current contract address
  function getContractById(bytes32 id) external view returns (address);

  /// @notice Get the proposed next contract given an ID
  /// @param id A bytes32 identifier for the route
  /// @return contract The current or proposed contract address
  function getProposedContractById(bytes32 id) external view returns (address);

  /// @notice Return the latest proprosal set
  /// @return ids The identifiers of the contracts to update
  /// @return to The addresses of the contracts that will be updated to
  function getProposedContractSet() external view returns (bytes32[] memory, address[] memory);

  /// @notice Proposes one or more updates to the contract routes
  /// @dev Only callable by owner
  function proposeContractsUpdate(bytes32[] memory proposalSetIds, address[] memory proposalSetAddresses) external;

  /// @notice Updates the current contract routes to the proposed contracts
  /// @dev Only callable by owner
  function updateContracts() external;

  /// @dev Puts the system into an emergency stopped state.
  /// @dev Only callable by owner
  function pause() external;

  /// @dev Takes the system out of an emergency stopped state.
  /// @dev Only callable by owner
  function unpause() external;
}

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

import {CBOR} from "../../../vendor/solidity-cborutils/v2.0.0/CBOR.sol";

/// @title Library for encoding the input data of a Functions request into CBOR
library FunctionsRequest {
  using CBOR for CBOR.CBORBuffer;

  uint16 public constant REQUEST_DATA_VERSION = 1;
  uint256 internal constant DEFAULT_BUFFER_SIZE = 256;

  enum Location {
    Inline, // Provided within the Request
    Remote, // Hosted through remote location that can be accessed through a provided URL
    DONHosted // Hosted on the DON's storage
  }

  enum CodeLanguage {
    JavaScript
    // In future version we may add other languages
  }

  struct Request {
    Location codeLocation; // ════════════╸ The location of the source code that will be executed on each node in the DON
    Location secretsLocation; // ═════════╸ The location of secrets that will be passed into the source code. *Only Remote secrets are supported
    CodeLanguage language; // ════════════╸ The coding language that the source code is written in
    string source; // ════════════════════╸ Raw source code for Request.codeLocation of Location.Inline, URL for Request.codeLocation of Location.Remote, or slot decimal number for Request.codeLocation of Location.DONHosted
    bytes encryptedSecretsReference; // ══╸ Encrypted URLs for Request.secretsLocation of Location.Remote (use addSecretsReference()), or CBOR encoded slotid+version for Request.secretsLocation of Location.DONHosted (use addDONHostedSecrets())
    string[] args; // ════════════════════╸ String arguments that will be passed into the source code
    bytes[] bytesArgs; // ════════════════╸ Bytes arguments that will be passed into the source code
  }

  error EmptySource();
  error EmptySecrets();
  error EmptyArgs();
  error NoInlineSecrets();

  /// @notice Encodes a Request to CBOR encoded bytes
  /// @param self The request to encode
  /// @return CBOR encoded bytes
  function encodeCBOR(Request memory self) internal pure returns (bytes memory) {
    CBOR.CBORBuffer memory buffer = CBOR.create(DEFAULT_BUFFER_SIZE);

    buffer.writeString("codeLocation");
    buffer.writeUInt256(uint256(self.codeLocation));

    buffer.writeString("language");
    buffer.writeUInt256(uint256(self.language));

    buffer.writeString("source");
    buffer.writeString(self.source);

    if (self.args.length > 0) {
      buffer.writeString("args");
      buffer.startArray();
      for (uint256 i = 0; i < self.args.length; ++i) {
        buffer.writeString(self.args[i]);
      }
      buffer.endSequence();
    }

    if (self.encryptedSecretsReference.length > 0) {
      if (self.secretsLocation == Location.Inline) {
        revert NoInlineSecrets();
      }
      buffer.writeString("secretsLocation");
      buffer.writeUInt256(uint256(self.secretsLocation));
      buffer.writeString("secrets");
      buffer.writeBytes(self.encryptedSecretsReference);
    }

    if (self.bytesArgs.length > 0) {
      buffer.writeString("bytesArgs");
      buffer.startArray();
      for (uint256 i = 0; i < self.bytesArgs.length; ++i) {
        buffer.writeBytes(self.bytesArgs[i]);
      }
      buffer.endSequence();
    }

    return buffer.buf.buf;
  }

  /// @notice Initializes a Chainlink Functions Request
  /// @dev Sets the codeLocation and code on the request
  /// @param self The uninitialized request
  /// @param codeLocation The user provided source code location
  /// @param language The programming language of the user code
  /// @param source The user provided source code or a url
  function initializeRequest(
    Request memory self,
    Location codeLocation,
    CodeLanguage language,
    string memory source
  ) internal pure {
    if (bytes(source).length == 0) revert EmptySource();

    self.codeLocation = codeLocation;
    self.language = language;
    self.source = source;
  }

  /// @notice Initializes a Chainlink Functions Request
  /// @dev Simplified version of initializeRequest for PoC
  /// @param self The uninitialized request
  /// @param javaScriptSource The user provided JS code (must not be empty)
  function initializeRequestForInlineJavaScript(Request memory self, string memory javaScriptSource) internal pure {
    initializeRequest(self, Location.Inline, CodeLanguage.JavaScript, javaScriptSource);
  }

  /// @notice Adds Remote user encrypted secrets to a Request
  /// @param self The initialized request
  /// @param encryptedSecretsReference Encrypted comma-separated string of URLs pointing to off-chain secrets
  function addSecretsReference(Request memory self, bytes memory encryptedSecretsReference) internal pure {
    if (encryptedSecretsReference.length == 0) revert EmptySecrets();

    self.secretsLocation = Location.Remote;
    self.encryptedSecretsReference = encryptedSecretsReference;
  }

  /// @notice Adds DON-hosted secrets reference to a Request
  /// @param self The initialized request
  /// @param slotID Slot ID of the user's secrets hosted on DON
  /// @param version User data version (for the slotID)
  function addDONHostedSecrets(Request memory self, uint8 slotID, uint64 version) internal pure {
    CBOR.CBORBuffer memory buffer = CBOR.create(DEFAULT_BUFFER_SIZE);

    buffer.writeString("slotID");
    buffer.writeUInt64(slotID);
    buffer.writeString("version");
    buffer.writeUInt64(version);

    self.secretsLocation = Location.DONHosted;
    self.encryptedSecretsReference = buffer.buf.buf;
  }

  /// @notice Sets args for the user run function
  /// @param self The initialized request
  /// @param args The array of string args (must not be empty)
  function setArgs(Request memory self, string[] memory args) internal pure {
    if (args.length == 0) revert EmptyArgs();

    self.args = args;
  }

  /// @notice Sets bytes args for the user run function
  /// @param self The initialized request
  /// @param args The array of bytes args (must not be empty)
  function setBytesArgs(Request memory self, bytes[] memory args) internal pure {
    if (args.length == 0) revert EmptyArgs();

    self.bytesArgs = args;
  }
}

File 5 of 123 : FunctionsResponse.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/// @title Library of types that are used for fulfillment of a Functions request
library FunctionsResponse {
  // Used to send request information from the Router to the Coordinator
  struct RequestMeta {
    bytes data; // ══════════════════╸ CBOR encoded Chainlink Functions request data, use FunctionsRequest library to encode a request
    bytes32 flags; // ═══════════════╸ Per-subscription flags
    address requestingContract; // ══╗ The client contract that is sending the request
    uint96 availableBalance; // ═════╝ Common LINK balance of the subscription that is controlled by the Router to be used for all consumer requests.
    uint72 adminFee; // ═════════════╗ Flat fee (in Juels of LINK) that will be paid to the Router Owner for operation of the network
    uint64 subscriptionId; //        ║ Identifier of the billing subscription that will be charged for the request
    uint64 initiatedRequests; //     ║ The number of requests that have been started
    uint32 callbackGasLimit; //      ║ The amount of gas that the callback to the consuming contract will be given
    uint16 dataVersion; // ══════════╝ The version of the structure of the CBOR encoded request data
    uint64 completedRequests; // ════╗ The number of requests that have successfully completed or timed out
    address subscriptionOwner; // ═══╝ The owner of the billing subscription
  }

  enum FulfillResult {
    FULFILLED, // 0
    USER_CALLBACK_ERROR, // 1
    INVALID_REQUEST_ID, // 2
    COST_EXCEEDS_COMMITMENT, // 3
    INSUFFICIENT_GAS_PROVIDED, // 4
    SUBSCRIPTION_BALANCE_INVARIANT_VIOLATION, // 5
    INVALID_COMMITMENT // 6
  }

  struct Commitment {
    bytes32 requestId; // ═════════════════╸ A unique identifier for a Chainlink Functions request
    address coordinator; // ═══════════════╗ The Coordinator contract that manages the DON that is servicing a request
    uint96 estimatedTotalCostJuels; // ════╝ The maximum cost in Juels (1e18) of LINK that will be charged to fulfill a request
    address client; // ════════════════════╗ The client contract that sent the request
    uint64 subscriptionId; //              ║ Identifier of the billing subscription that will be charged for the request
    uint32 callbackGasLimit; // ═══════════╝ The amount of gas that the callback to the consuming contract will be given
    uint72 adminFee; // ═══════════════════╗ Flat fee (in Juels of LINK) that will be paid to the Router Owner for operation of the network
    uint72 donFee; //                      ║ Fee (in Juels of LINK) that will be split between Node Operators for servicing a request
    uint40 gasOverheadBeforeCallback; //   ║ Represents the average gas execution cost before the fulfillment callback.
    uint40 gasOverheadAfterCallback; //    ║ Represents the average gas execution cost after the fulfillment callback.
    uint32 timeoutTimestamp; // ═══════════╝ The timestamp at which a request will be eligible to be timed out
  }
}

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

// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  function getRoundData(
    uint80 _roundId
  ) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

  function latestRoundData()
    external
    view
    returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

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

// solhint-disable-next-line interface-starts-with-i
interface LinkTokenInterface {
  function allowance(address owner, address spender) external view returns (uint256 remaining);

  function approve(address spender, uint256 value) external returns (bool success);

  function balanceOf(address owner) external view returns (uint256 balance);

  function decimals() external view returns (uint8 decimalPlaces);

  function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);

  function increaseApproval(address spender, uint256 subtractedValue) external;

  function name() external view returns (string memory tokenName);

  function symbol() external view returns (string memory tokenSymbol);

  function totalSupply() external view returns (uint256 totalTokensIssued);

  function transfer(address to, uint256 value) external returns (bool success);

  function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);

  function transferFrom(address from, address to, uint256 value) external returns (bool success);
}

// SPDX-License-Identifier: BSD-2-Clause
pragma solidity ^0.8.4;

/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for appending to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library Buffer {
    /**
    * @dev Represents a mutable buffer. Buffers have a current value (buf) and
    *      a capacity. The capacity may be longer than the current value, in
    *      which case it can be extended without the need to allocate more memory.
    */
    struct buffer {
        bytes buf;
        uint capacity;
    }

    /**
    * @dev Initializes a buffer with an initial capacity.
    * @param buf The buffer to initialize.
    * @param capacity The number of bytes of space to allocate the buffer.
    * @return The buffer, for chaining.
    */
    function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
        if (capacity % 32 != 0) {
            capacity += 32 - (capacity % 32);
        }
        // Allocate space for the buffer data
        buf.capacity = capacity;
        assembly {
            let ptr := mload(0x40)
            mstore(buf, ptr)
            mstore(ptr, 0)
            let fpm := add(32, add(ptr, capacity))
            if lt(fpm, ptr) {
                revert(0, 0)
            }
            mstore(0x40, fpm)
        }
        return buf;
    }

    /**
    * @dev Initializes a new buffer from an existing bytes object.
    *      Changes to the buffer may mutate the original value.
    * @param b The bytes object to initialize the buffer with.
    * @return A new buffer.
    */
    function fromBytes(bytes memory b) internal pure returns(buffer memory) {
        buffer memory buf;
        buf.buf = b;
        buf.capacity = b.length;
        return buf;
    }

    function resize(buffer memory buf, uint capacity) private pure {
        bytes memory oldbuf = buf.buf;
        init(buf, capacity);
        append(buf, oldbuf);
    }

    /**
    * @dev Sets buffer length to 0.
    * @param buf The buffer to truncate.
    * @return The original buffer, for chaining..
    */
    function truncate(buffer memory buf) internal pure returns (buffer memory) {
        assembly {
            let bufptr := mload(buf)
            mstore(bufptr, 0)
        }
        return buf;
    }

    /**
    * @dev Appends len bytes of a byte string to a buffer. Resizes if doing so would exceed
    *      the capacity of the buffer.
    * @param buf The buffer to append to.
    * @param data The data to append.
    * @param len The number of bytes to copy.
    * @return The original buffer, for chaining.
    */
    function append(buffer memory buf, bytes memory data, uint len) internal pure returns(buffer memory) {
        require(len <= data.length);

        uint off = buf.buf.length;
        uint newCapacity = off + len;
        if (newCapacity > buf.capacity) {
            resize(buf, newCapacity * 2);
        }

        uint dest;
        uint src;
        assembly {
            // Memory address of the buffer data
            let bufptr := mload(buf)
            // Length of existing buffer data
            let buflen := mload(bufptr)
            // Start address = buffer address + offset + sizeof(buffer length)
            dest := add(add(bufptr, 32), off)
            // Update buffer length if we're extending it
            if gt(newCapacity, buflen) {
                mstore(bufptr, newCapacity)
            }
            src := add(data, 32)
        }

        // Copy word-length chunks while possible
        for (; len >= 32; len -= 32) {
            assembly {
                mstore(dest, mload(src))
            }
            dest += 32;
            src += 32;
        }

        // Copy remaining bytes
        unchecked {
            uint mask = (256 ** (32 - len)) - 1;
            assembly {
                let srcpart := and(mload(src), not(mask))
                let destpart := and(mload(dest), mask)
                mstore(dest, or(destpart, srcpart))
            }
        }

        return buf;
    }

    /**
    * @dev Appends a byte string to a buffer. Resizes if doing so would exceed
    *      the capacity of the buffer.
    * @param buf The buffer to append to.
    * @param data The data to append.
    * @return The original buffer, for chaining.
    */
    function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
        return append(buf, data, data.length);
    }

    /**
    * @dev Appends a byte to the buffer. Resizes if doing so would exceed the
    *      capacity of the buffer.
    * @param buf The buffer to append to.
    * @param data The data to append.
    * @return The original buffer, for chaining.
    */
    function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
        uint off = buf.buf.length;
        uint offPlusOne = off + 1;
        if (off >= buf.capacity) {
            resize(buf, offPlusOne * 2);
        }

        assembly {
            // Memory address of the buffer data
            let bufptr := mload(buf)
            // Address = buffer address + sizeof(buffer length) + off
            let dest := add(add(bufptr, off), 32)
            mstore8(dest, data)
            // Update buffer length if we extended it
            if gt(offPlusOne, mload(bufptr)) {
                mstore(bufptr, offPlusOne)
            }
        }

        return buf;
    }

    /**
    * @dev Appends len bytes of bytes32 to a buffer. Resizes if doing so would
    *      exceed the capacity of the buffer.
    * @param buf The buffer to append to.
    * @param data The data to append.
    * @param len The number of bytes to write (left-aligned).
    * @return The original buffer, for chaining.
    */
    function append(buffer memory buf, bytes32 data, uint len) private pure returns(buffer memory) {
        uint off = buf.buf.length;
        uint newCapacity = len + off;
        if (newCapacity > buf.capacity) {
            resize(buf, newCapacity * 2);
        }

        unchecked {
            uint mask = (256 ** len) - 1;
            // Right-align data
            data = data >> (8 * (32 - len));
            assembly {
                // Memory address of the buffer data
                let bufptr := mload(buf)
                // Address = buffer address + sizeof(buffer length) + newCapacity
                let dest := add(bufptr, newCapacity)
                mstore(dest, or(and(mload(dest), not(mask)), data))
                // Update buffer length if we extended it
                if gt(newCapacity, mload(bufptr)) {
                    mstore(bufptr, newCapacity)
                }
            }
        }
        return buf;
    }

    /**
    * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed
    *      the capacity of the buffer.
    * @param buf The buffer to append to.
    * @param data The data to append.
    * @return The original buffer, for chhaining.
    */
    function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
        return append(buf, bytes32(data), 20);
    }

    /**
    * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed
    *      the capacity of the buffer.
    * @param buf The buffer to append to.
    * @param data The data to append.
    * @return The original buffer, for chaining.
    */
    function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
        return append(buf, data, 32);
    }

    /**
     * @dev Appends a byte to the end of the buffer. Resizes if doing so would
     *      exceed the capacity of the buffer.
     * @param buf The buffer to append to.
     * @param data The data to append.
     * @param len The number of bytes to write (right-aligned).
     * @return The original buffer.
     */
    function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
        uint off = buf.buf.length;
        uint newCapacity = len + off;
        if (newCapacity > buf.capacity) {
            resize(buf, newCapacity * 2);
        }

        uint mask = (256 ** len) - 1;
        assembly {
            // Memory address of the buffer data
            let bufptr := mload(buf)
            // Address = buffer address + sizeof(buffer length) + newCapacity
            let dest := add(bufptr, newCapacity)
            mstore(dest, or(and(mload(dest), not(mask)), data))
            // Update buffer length if we extended it
            if gt(newCapacity, mload(bufptr)) {
                mstore(bufptr, newCapacity)
            }
        }
        return buf;
    }
}

File 9 of 123 : CBOR.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "../../@ensdomains/buffer/v0.1.0/Buffer.sol";

/**
* @dev A library for populating CBOR encoded payload in Solidity.
*
* https://datatracker.ietf.org/doc/html/rfc7049
*
* The library offers various write* and start* methods to encode values of different types.
* The resulted buffer can be obtained with data() method.
* Encoding of primitive types is staightforward, whereas encoding of sequences can result
* in an invalid CBOR if start/write/end flow is violated.
* For the purpose of gas saving, the library does not verify start/write/end flow internally,
* except for nested start/end pairs.
*/

library CBOR {
    using Buffer for Buffer.buffer;

    struct CBORBuffer {
        Buffer.buffer buf;
        uint256 depth;
    }

    uint8 private constant MAJOR_TYPE_INT = 0;
    uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
    uint8 private constant MAJOR_TYPE_BYTES = 2;
    uint8 private constant MAJOR_TYPE_STRING = 3;
    uint8 private constant MAJOR_TYPE_ARRAY = 4;
    uint8 private constant MAJOR_TYPE_MAP = 5;
    uint8 private constant MAJOR_TYPE_TAG = 6;
    uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;

    uint8 private constant TAG_TYPE_BIGNUM = 2;
    uint8 private constant TAG_TYPE_NEGATIVE_BIGNUM = 3;

    uint8 private constant CBOR_FALSE = 20;
    uint8 private constant CBOR_TRUE = 21;
    uint8 private constant CBOR_NULL = 22;
    uint8 private constant CBOR_UNDEFINED = 23;

    function create(uint256 capacity) internal pure returns(CBORBuffer memory cbor) {
        Buffer.init(cbor.buf, capacity);
        cbor.depth = 0;
        return cbor;
    }

    function data(CBORBuffer memory buf) internal pure returns(bytes memory) {
        require(buf.depth == 0, "Invalid CBOR");
        return buf.buf.buf;
    }

    function writeUInt256(CBORBuffer memory buf, uint256 value) internal pure {
        buf.buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM));
        writeBytes(buf, abi.encode(value));
    }

    function writeInt256(CBORBuffer memory buf, int256 value) internal pure {
        if (value < 0) {
            buf.buf.appendUint8(
                uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_NEGATIVE_BIGNUM)
            );
            writeBytes(buf, abi.encode(uint256(-1 - value)));
        } else {
            writeUInt256(buf, uint256(value));
        }
    }

    function writeUInt64(CBORBuffer memory buf, uint64 value) internal pure {
        writeFixedNumeric(buf, MAJOR_TYPE_INT, value);
    }

    function writeInt64(CBORBuffer memory buf, int64 value) internal pure {
        if(value >= 0) {
            writeFixedNumeric(buf, MAJOR_TYPE_INT, uint64(value));
        } else{
            writeFixedNumeric(buf, MAJOR_TYPE_NEGATIVE_INT, uint64(-1 - value));
        }
    }

    function writeBytes(CBORBuffer memory buf, bytes memory value) internal pure {
        writeFixedNumeric(buf, MAJOR_TYPE_BYTES, uint64(value.length));
        buf.buf.append(value);
    }

    function writeString(CBORBuffer memory buf, string memory value) internal pure {
        writeFixedNumeric(buf, MAJOR_TYPE_STRING, uint64(bytes(value).length));
        buf.buf.append(bytes(value));
    }

    function writeBool(CBORBuffer memory buf, bool value) internal pure {
        writeContentFree(buf, value ? CBOR_TRUE : CBOR_FALSE);
    }

    function writeNull(CBORBuffer memory buf) internal pure {
        writeContentFree(buf, CBOR_NULL);
    }

    function writeUndefined(CBORBuffer memory buf) internal pure {
        writeContentFree(buf, CBOR_UNDEFINED);
    }

    function startArray(CBORBuffer memory buf) internal pure {
        writeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
        buf.depth += 1;
    }

    function startFixedArray(CBORBuffer memory buf, uint64 length) internal pure {
        writeDefiniteLengthType(buf, MAJOR_TYPE_ARRAY, length);
    }

    function startMap(CBORBuffer memory buf) internal pure {
        writeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
        buf.depth += 1;
    }

    function startFixedMap(CBORBuffer memory buf, uint64 length) internal pure {
        writeDefiniteLengthType(buf, MAJOR_TYPE_MAP, length);
    }

    function endSequence(CBORBuffer memory buf) internal pure {
        writeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
        buf.depth -= 1;
    }

    function writeKVString(CBORBuffer memory buf, string memory key, string memory value) internal pure {
        writeString(buf, key);
        writeString(buf, value);
    }

    function writeKVBytes(CBORBuffer memory buf, string memory key, bytes memory value) internal pure {
        writeString(buf, key);
        writeBytes(buf, value);
    }

    function writeKVUInt256(CBORBuffer memory buf, string memory key, uint256 value) internal pure {
        writeString(buf, key);
        writeUInt256(buf, value);
    }

    function writeKVInt256(CBORBuffer memory buf, string memory key, int256 value) internal pure {
        writeString(buf, key);
        writeInt256(buf, value);
    }

    function writeKVUInt64(CBORBuffer memory buf, string memory key, uint64 value) internal pure {
        writeString(buf, key);
        writeUInt64(buf, value);
    }

    function writeKVInt64(CBORBuffer memory buf, string memory key, int64 value) internal pure {
        writeString(buf, key);
        writeInt64(buf, value);
    }

    function writeKVBool(CBORBuffer memory buf, string memory key, bool value) internal pure {
        writeString(buf, key);
        writeBool(buf, value);
    }

    function writeKVNull(CBORBuffer memory buf, string memory key) internal pure {
        writeString(buf, key);
        writeNull(buf);
    }

    function writeKVUndefined(CBORBuffer memory buf, string memory key) internal pure {
        writeString(buf, key);
        writeUndefined(buf);
    }

    function writeKVMap(CBORBuffer memory buf, string memory key) internal pure {
        writeString(buf, key);
        startMap(buf);
    }

    function writeKVArray(CBORBuffer memory buf, string memory key) internal pure {
        writeString(buf, key);
        startArray(buf);
    }

    function writeFixedNumeric(
        CBORBuffer memory buf,
        uint8 major,
        uint64 value
    ) private pure {
        if (value <= 23) {
            buf.buf.appendUint8(uint8((major << 5) | value));
        } else if (value <= 0xFF) {
            buf.buf.appendUint8(uint8((major << 5) | 24));
            buf.buf.appendInt(value, 1);
        } else if (value <= 0xFFFF) {
            buf.buf.appendUint8(uint8((major << 5) | 25));
            buf.buf.appendInt(value, 2);
        } else if (value <= 0xFFFFFFFF) {
            buf.buf.appendUint8(uint8((major << 5) | 26));
            buf.buf.appendInt(value, 4);
        } else {
            buf.buf.appendUint8(uint8((major << 5) | 27));
            buf.buf.appendInt(value, 8);
        }
    }

    function writeIndefiniteLengthType(CBORBuffer memory buf, uint8 major)
        private
        pure
    {
        buf.buf.appendUint8(uint8((major << 5) | 31));
    }

    function writeDefiniteLengthType(CBORBuffer memory buf, uint8 major, uint64 length)
        private
        pure
    {
        writeFixedNumeric(buf, major, length);
    }

    function writeContentFree(CBORBuffer memory buf, uint8 value) private pure {
        buf.buf.appendUint8(uint8((MAJOR_TYPE_CONTENT_FREE << 5) | value));
    }
}

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

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        AccessControlStorage storage $ = _getAccessControlStorage();
        bytes32 previousAdminRole = getRoleAdmin(role);
        $._roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (!hasRole(role, account)) {
            $._roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

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

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

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

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../../../utils/introspection/ERC165Upgradeable.sol";
import {IERC1155Receiver} from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";

/**
 * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 */
abstract contract ERC1155HolderUpgradeable is Initializable, ERC165Upgradeable, IERC1155Receiver {
    function __ERC1155Holder_init() internal onlyInitializing {
    }

    function __ERC1155Holder_init_unchained() internal onlyInitializing {
    }
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
    }

    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/utils/ERC721Holder.sol)

pragma solidity ^0.8.20;

import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
 * {IERC721-setApprovalForAll}.
 */
abstract contract ERC721HolderUpgradeable is Initializable, IERC721Receiver {
    function __ERC721Holder_init() internal onlyInitializing {
    }

    function __ERC721Holder_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

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

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

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165Upgradeable is Initializable, IERC165 {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

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

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

File 22 of 123 : IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC5267.sol)

pragma solidity >=0.4.16;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

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

pragma solidity ^0.8.20;

import {IERC1155} from "./IERC1155.sol";
import {IERC1155MetadataURI} from "./extensions/IERC1155MetadataURI.sol";
import {ERC1155Utils} from "./utils/ERC1155Utils.sol";
import {Context} from "../../utils/Context.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {Arrays} from "../../utils/Arrays.sol";
import {IERC1155Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the basic standard multi-token.
 * See https://eips.ethereum.org/EIPS/eip-1155
 * Originally based on code by Enjin: https://github.com/enjin/erc-1155
 */
abstract contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, IERC1155Errors {
    using Arrays for uint256[];
    using Arrays for address[];

    mapping(uint256 id => mapping(address account => uint256)) private _balances;

    mapping(address account => mapping(address operator => bool)) private _operatorApprovals;

    // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
    string private _uri;

    /**
     * @dev See {_setURI}.
     */
    constructor(string memory uri_) {
        _setURI(uri_);
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC1155).interfaceId ||
            interfaceId == type(IERC1155MetadataURI).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC1155MetadataURI-uri}.
     *
     * This implementation returns the same URI for *all* token types. It relies
     * on the token type ID substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC].
     *
     * Clients calling this function must replace the `\{id\}` substring with the
     * actual token type ID.
     */
    function uri(uint256 /* id */) public view virtual returns (string memory) {
        return _uri;
    }

    /// @inheritdoc IERC1155
    function balanceOf(address account, uint256 id) public view virtual returns (uint256) {
        return _balances[id][account];
    }

    /**
     * @dev See {IERC1155-balanceOfBatch}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] memory accounts,
        uint256[] memory ids
    ) public view virtual returns (uint256[] memory) {
        if (accounts.length != ids.length) {
            revert ERC1155InvalidArrayLength(ids.length, accounts.length);
        }

        uint256[] memory batchBalances = new uint256[](accounts.length);

        for (uint256 i = 0; i < accounts.length; ++i) {
            batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i));
        }

        return batchBalances;
    }

    /// @inheritdoc IERC1155
    function setApprovalForAll(address operator, bool approved) public virtual {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /// @inheritdoc IERC1155
    function isApprovedForAll(address account, address operator) public view virtual returns (bool) {
        return _operatorApprovals[account][operator];
    }

    /// @inheritdoc IERC1155
    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public virtual {
        address sender = _msgSender();
        if (from != sender && !isApprovedForAll(from, sender)) {
            revert ERC1155MissingApprovalForAll(sender, from);
        }
        _safeTransferFrom(from, to, id, value, data);
    }

    /// @inheritdoc IERC1155
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) public virtual {
        address sender = _msgSender();
        if (from != sender && !isApprovedForAll(from, sender)) {
            revert ERC1155MissingApprovalForAll(sender, from);
        }
        _safeBatchTransferFrom(from, to, ids, values, data);
    }

    /**
     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. Will mint (or burn) if `from`
     * (or `to`) is the zero address.
     *
     * Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received}
     *   or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value.
     * - `ids` and `values` must have the same length.
     *
     * NOTE: The ERC-1155 acceptance check is not performed in this function. See {_updateWithAcceptanceCheck} instead.
     */
    function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal virtual {
        if (ids.length != values.length) {
            revert ERC1155InvalidArrayLength(ids.length, values.length);
        }

        address operator = _msgSender();

        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids.unsafeMemoryAccess(i);
            uint256 value = values.unsafeMemoryAccess(i);

            if (from != address(0)) {
                uint256 fromBalance = _balances[id][from];
                if (fromBalance < value) {
                    revert ERC1155InsufficientBalance(from, fromBalance, value, id);
                }
                unchecked {
                    // Overflow not possible: value <= fromBalance
                    _balances[id][from] = fromBalance - value;
                }
            }

            if (to != address(0)) {
                _balances[id][to] += value;
            }
        }

        if (ids.length == 1) {
            uint256 id = ids.unsafeMemoryAccess(0);
            uint256 value = values.unsafeMemoryAccess(0);
            emit TransferSingle(operator, from, to, id, value);
        } else {
            emit TransferBatch(operator, from, to, ids, values);
        }
    }

    /**
     * @dev Version of {_update} that performs the token acceptance check by calling
     * {IERC1155Receiver-onERC1155Received} or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it
     * contains code (eg. is a smart contract at the moment of execution).
     *
     * IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any
     * update to the contract state after this function would break the check-effect-interaction pattern. Consider
     * overriding {_update} instead.
     */
    function _updateWithAcceptanceCheck(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) internal virtual {
        _update(from, to, ids, values);
        if (to != address(0)) {
            address operator = _msgSender();
            if (ids.length == 1) {
                uint256 id = ids.unsafeMemoryAccess(0);
                uint256 value = values.unsafeMemoryAccess(0);
                ERC1155Utils.checkOnERC1155Received(operator, from, to, id, value, data);
            } else {
                ERC1155Utils.checkOnERC1155BatchReceived(operator, from, to, ids, values, data);
            }
        }
    }

    /**
     * @dev Transfers a `value` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `from` must have a balance of tokens of type `id` of at least `value` amount.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
        _updateWithAcceptanceCheck(from, to, ids, values, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     * - `ids` and `values` must have the same length.
     */
    function _safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        _updateWithAcceptanceCheck(from, to, ids, values, data);
    }

    /**
     * @dev Sets a new URI for all token types, by relying on the token type ID
     * substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC].
     *
     * By this mechanism, any occurrence of the `\{id\}` substring in either the
     * URI or any of the values in the JSON file at said URI will be replaced by
     * clients with the token type ID.
     *
     * For example, the `https://token-cdn-domain/\{id\}.json` URI would be
     * interpreted by clients as
     * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
     * for token type ID 0x4cce0.
     *
     * See {uri}.
     *
     * Because these URIs cannot be meaningfully represented by the {URI} event,
     * this function emits no events.
     */
    function _setURI(string memory newuri) internal virtual {
        _uri = newuri;
    }

    /**
     * @dev Creates a `value` amount of tokens of type `id`, and assigns them to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _mint(address to, uint256 id, uint256 value, bytes memory data) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
        _updateWithAcceptanceCheck(address(0), to, ids, values, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `values` must have the same length.
     * - `to` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        _updateWithAcceptanceCheck(address(0), to, ids, values, data);
    }

    /**
     * @dev Destroys a `value` amount of tokens of type `id` from `from`
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `from` must have at least `value` amount of tokens of type `id`.
     */
    function _burn(address from, uint256 id, uint256 value) internal {
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
        _updateWithAcceptanceCheck(from, address(0), ids, values, "");
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `from` must have at least `value` amount of tokens of type `id`.
     * - `ids` and `values` must have the same length.
     */
    function _burnBatch(address from, uint256[] memory ids, uint256[] memory values) internal {
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        _updateWithAcceptanceCheck(from, address(0), ids, values, "");
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the zero address.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        if (operator == address(0)) {
            revert ERC1155InvalidOperator(address(0));
        }
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Creates an array in memory with only one value for each of the elements provided.
     */
    function _asSingletonArrays(
        uint256 element1,
        uint256 element2
    ) private pure returns (uint256[] memory array1, uint256[] memory array2) {
        assembly ("memory-safe") {
            // Load the free memory pointer
            array1 := mload(0x40)
            // Set array length to 1
            mstore(array1, 1)
            // Store the single element at the next word after the length (where content starts)
            mstore(add(array1, 0x20), element1)

            // Repeat for next array locating it right after the first array
            array2 := add(array1, 0x40)
            mstore(array2, 1)
            mstore(add(array2, 0x20), element2)

            // Update the free memory pointer by pointing after the second array
            mstore(0x40, add(array2, 0x40))
        }
    }
}

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
 * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[ERC].
 */
interface IERC1155MetadataURI is IERC1155 {
    /**
     * @dev Returns the URI for token type `id`.
     *
     * If the `\{id\}` substring is present in the URI, it must be replaced by
     * clients with the actual token type ID.
     */
    function uri(uint256 id) external view returns (string memory);
}

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

pragma solidity >=0.6.2;

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

/**
 * @dev Required interface of an ERC-1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[ERC].
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

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

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] calldata accounts,
        uint256[] calldata ids
    ) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the zero address.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {IERC1155Receiver-onERC1155Received} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `value` amount.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {IERC1155Receiver-onERC1155BatchReceived} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
     *
     * Requirements:
     *
     * - `ids` and `values` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external;
}

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC-1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC-1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

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

pragma solidity ^0.8.20;

import {IERC1155Receiver} from "../IERC1155Receiver.sol";
import {IERC1155Errors} from "../../../interfaces/draft-IERC6093.sol";

/**
 * @dev Library that provide common ERC-1155 utility functions.
 *
 * See https://eips.ethereum.org/EIPS/eip-1155[ERC-1155].
 *
 * _Available since v5.1._
 */
library ERC1155Utils {
    /**
     * @dev Performs an acceptance check for the provided `operator` by calling {IERC1155Receiver-onERC1155Received}
     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
     *
     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
     * Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept
     * the transfer.
     */
    function checkOnERC1155Received(
        address operator,
        address from,
        address to,
        uint256 id,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length > 0) {
            try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) {
                if (response != IERC1155Receiver.onERC1155Received.selector) {
                    // Tokens rejected
                    revert IERC1155Errors.ERC1155InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    // non-IERC1155Receiver implementer
                    revert IERC1155Errors.ERC1155InvalidReceiver(to);
                } else {
                    assembly ("memory-safe") {
                        revert(add(reason, 0x20), mload(reason))
                    }
                }
            }
        }
    }

    /**
     * @dev Performs a batch acceptance check for the provided `operator` by calling {IERC1155Receiver-onERC1155BatchReceived}
     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
     *
     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
     * Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept
     * the transfer.
     */
    function checkOnERC1155BatchReceived(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) internal {
        if (to.code.length > 0) {
            try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (
                bytes4 response
            ) {
                if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
                    // Tokens rejected
                    revert IERC1155Errors.ERC1155InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    // non-IERC1155Receiver implementer
                    revert IERC1155Errors.ERC1155InvalidReceiver(to);
                } else {
                    assembly ("memory-safe") {
                        revert(add(reason, 0x20), mload(reason))
                    }
                }
            }
        }
    }
}

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

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

pragma solidity ^0.8.20;

import {ERC20} from "../ERC20.sol";
import {Context} from "../../../utils/Context.sol";

/**
 * @dev Extension of {ERC20} that allows token holders to destroy both their own
 * tokens and those that they have an allowance for, in a way that can be
 * recognized off-chain (via event analysis).
 */
abstract contract ERC20Burnable is Context, ERC20 {
    /**
     * @dev Destroys a `value` amount of tokens from the caller.
     *
     * See {ERC20-_burn}.
     */
    function burn(uint256 value) public virtual {
        _burn(_msgSender(), value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, deducting from
     * the caller's allowance.
     *
     * See {ERC20-_burn} and {ERC20-allowance}.
     *
     * Requirements:
     *
     * - the caller must have allowance for ``accounts``'s tokens of at least
     * `value`.
     */
    function burnFrom(address account, uint256 value) public virtual {
        _spendAllowance(account, _msgSender(), value);
        _burn(account, value);
    }
}

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

pragma solidity ^0.8.20;

import {IERC20Permit} from "./IERC20Permit.sol";
import {ERC20} from "../ERC20.sol";
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
import {Nonces} from "../../../utils/Nonces.sol";

/**
 * @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
    bytes32 private constant PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    /**
     * @dev Permit deadline has expired.
     */
    error ERC2612ExpiredSignature(uint256 deadline);

    /**
     * @dev Mismatched signature.
     */
    error ERC2612InvalidSigner(address signer, address owner);

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC-20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /// @inheritdoc IERC20Permit
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        if (block.timestamp > deadline) {
            revert ERC2612ExpiredSignature(deadline);
        }

        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        if (signer != owner) {
            revert ERC2612InvalidSigner(signer, owner);
        }

        _approve(owner, spender, value);
    }

    /// @inheritdoc IERC20Permit
    function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
        return super.nonces(owner);
    }

    /// @inheritdoc IERC20Permit
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
        return _domainSeparatorV4();
    }
}

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

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

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

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

pragma solidity ^0.8.20;

import {IERC721} from "./IERC721.sol";
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
import {ERC721Utils} from "./utils/ERC721Utils.sol";
import {Context} from "../../utils/Context.sol";
import {Strings} from "../../utils/Strings.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    mapping(uint256 tokenId => address) private _owners;

    mapping(address owner => uint256) private _balances;

    mapping(uint256 tokenId => address) private _tokenApprovals;

    mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /// @inheritdoc IERC721
    function balanceOf(address owner) public view virtual returns (uint256) {
        if (owner == address(0)) {
            revert ERC721InvalidOwner(address(0));
        }
        return _balances[owner];
    }

    /// @inheritdoc IERC721
    function ownerOf(uint256 tokenId) public view virtual returns (address) {
        return _requireOwned(tokenId);
    }

    /// @inheritdoc IERC721Metadata
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /// @inheritdoc IERC721Metadata
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /// @inheritdoc IERC721Metadata
    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
        _requireOwned(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /// @inheritdoc IERC721
    function approve(address to, uint256 tokenId) public virtual {
        _approve(to, tokenId, _msgSender());
    }

    /// @inheritdoc IERC721
    function getApproved(uint256 tokenId) public view virtual returns (address) {
        _requireOwned(tokenId);

        return _getApproved(tokenId);
    }

    /// @inheritdoc IERC721
    function setApprovalForAll(address operator, bool approved) public virtual {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /// @inheritdoc IERC721
    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /// @inheritdoc IERC721
    function transferFrom(address from, address to, uint256 tokenId) public virtual {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        // Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
        address previousOwner = _update(to, tokenId, _msgSender());
        if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /// @inheritdoc IERC721
    function safeTransferFrom(address from, address to, uint256 tokenId) public {
        safeTransferFrom(from, to, tokenId, "");
    }

    /// @inheritdoc IERC721
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
        transferFrom(from, to, tokenId);
        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     *
     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
     * core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances
     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
     */
    function _getApproved(uint256 tokenId) internal view virtual returns (address) {
        return _tokenApprovals[tokenId];
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
     * particular (ignoring whether it is owned by `owner`).
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
        return
            spender != address(0) &&
            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
    }

    /**
     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
     * Reverts if:
     * - `spender` does not have approval from `owner` for `tokenId`.
     * - `spender` does not have approval to manage all of `owner`'s assets.
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
        if (!_isAuthorized(owner, spender, tokenId)) {
            if (owner == address(0)) {
                revert ERC721NonexistentToken(tokenId);
            } else {
                revert ERC721InsufficientApproval(spender, tokenId);
            }
        }
    }

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
     *
     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the
     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
     * remain consistent with one another.
     */
    function _increaseBalance(address account, uint128 value) internal virtual {
        unchecked {
            _balances[account] += value;
        }
    }

    /**
     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that
     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).
     *
     * Emits a {Transfer} event.
     *
     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
     */
    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
        address from = _ownerOf(tokenId);

        // Perform (optional) operator check
        if (auth != address(0)) {
            _checkAuthorized(from, auth, tokenId);
        }

        // Execute the update
        if (from != address(0)) {
            // Clear approval. No need to re-authorize or emit the Approval event
            _approve(address(0), tokenId, address(0), false);

            unchecked {
                _balances[from] -= 1;
            }
        }

        if (to != address(0)) {
            unchecked {
                _balances[to] += 1;
            }
        }

        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        return from;
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner != address(0)) {
            revert ERC721InvalidSender(address(0));
        }
    }

    /**
     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal {
        address previousOwner = _update(address(0), tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        } else if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
     * are aware of the ERC-721 standard to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is like {safeTransferFrom} in the sense that it invokes
     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `tokenId` token must exist and be owned by `from`.
     * - `to` cannot be the zero address.
     * - `from` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId) internal {
        _safeTransfer(from, to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
     * either the owner of the token, or approved to operate on all tokens held by this owner.
     *
     * Emits an {Approval} event.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address to, uint256 tokenId, address auth) internal {
        _approve(to, tokenId, auth, true);
    }

    /**
     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
     * emitted in the context of transfers.
     */
    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
        // Avoid reading the owner unless necessary
        if (emitEvent || auth != address(0)) {
            address owner = _requireOwned(tokenId);

            // We do not use _isAuthorized because single-token approvals should not be able to call approve
            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
                revert ERC721InvalidApprover(auth);
            }

            if (emitEvent) {
                emit Approval(owner, to, tokenId);
            }
        }

        _tokenApprovals[tokenId] = to;
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Requirements:
     * - operator can't be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        if (operator == address(0)) {
            revert ERC721InvalidOperator(operator);
        }
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
     * Returns the owner.
     *
     * Overrides to ownership logic should be done to {_ownerOf}.
     */
    function _requireOwned(uint256 tokenId) internal view returns (address) {
        address owner = _ownerOf(tokenId);
        if (owner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
        return owner;
    }
}

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

pragma solidity >=0.6.2;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

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

pragma solidity >=0.6.2;

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

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

File 37 of 123 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity >=0.5.0;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

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

pragma solidity ^0.8.20;

import {IERC721Receiver} from "../IERC721Receiver.sol";
import {IERC721Errors} from "../../../interfaces/draft-IERC6093.sol";

/**
 * @dev Library that provide common ERC-721 utility functions.
 *
 * See https://eips.ethereum.org/EIPS/eip-721[ERC-721].
 *
 * _Available since v5.1._
 */
library ERC721Utils {
    /**
     * @dev Performs an acceptance check for the provided `operator` by calling {IERC721Receiver-onERC721Received}
     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
     *
     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
     * Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept
     * the transfer.
     */
    function checkOnERC721Received(
        address operator,
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal {
        if (to.code.length > 0) {
            try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {
                if (retval != IERC721Receiver.onERC721Received.selector) {
                    // Token rejected
                    revert IERC721Errors.ERC721InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    // non-IERC721Receiver implementer
                    revert IERC721Errors.ERC721InvalidReceiver(to);
                } else {
                    assembly ("memory-safe") {
                        revert(add(reason, 0x20), mload(reason))
                    }
                }
            }
        }
    }
}

File 39 of 123 : 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)
        }
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

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

// 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)
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

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

pragma solidity ^0.8.20;

import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
 * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
 * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    // slither-disable-next-line constable-states
    string private _nameFallback;
    // slither-disable-next-line constable-states
    string private _versionFallback;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /// @inheritdoc IERC5267
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _name which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Name() internal view returns (string memory) {
        return _name.toStringWithFallback(_nameFallback);
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _version which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Version() internal view returns (string memory) {
        return _version.toStringWithFallback(_versionFallback);
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
     */
    function toDataWithIntendedValidatorHash(
        address validator,
        bytes32 messageHash
    ) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, hex"19_00")
            mstore(0x02, shl(96, validator))
            mstore(0x16, messageHash)
            digest := keccak256(0x00, 0x36)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

File 46 of 123 : 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);
}

File 47 of 123 : ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

File 49 of 123 : 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;
    }
}

File 50 of 123 : 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))
        }
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;

/**
 * @dev Provides tracking nonces for addresses. Nonces will only increment.
 */
abstract contract Nonces {
    /**
     * @dev The nonce used for an `account` is not the expected current nonce.
     */
    error InvalidAccountNonce(address account, uint256 currentNonce);

    mapping(address account => uint256) private _nonces;

    /**
     * @dev Returns the next unused nonce for an address.
     */
    function nonces(address owner) public view virtual returns (uint256) {
        return _nonces[owner];
    }

    /**
     * @dev Consumes a nonce.
     *
     * Returns the current value and increments nonce.
     */
    function _useNonce(address owner) internal virtual returns (uint256) {
        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
        // decremented or reset. This guarantees that the nonce never overflows.
        unchecked {
            // It is important to do x++ and not ++x here.
            return _nonces[owner]++;
        }
    }

    /**
     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
     */
    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
        uint256 current = _useNonce(owner);
        if (nonce != current) {
            revert InvalidAccountNonce(owner, current);
        }
    }
}

// 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)
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        assembly ("memory-safe") {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {toShortStringWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using
     * {toShortStringWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

// 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)
        }
    }
}

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

// 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))
        }
    }
}

File 59 of 123 : 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;
        }
    }
}

// SPDX-License-Identifier: LGPL-3.0-only
/* solhint-disable one-contract-per-file */
pragma solidity >=0.7.0 <0.9.0;

import {SelfAuthorized} from "./../common/SelfAuthorized.sol";
import {IERC165} from "./../interfaces/IERC165.sol";
import {IGuardManager} from "./../interfaces/IGuardManager.sol";
import {Enum} from "./../libraries/Enum.sol";
// solhint-disable-next-line no-unused-import
import {GUARD_STORAGE_SLOT} from "../libraries/SafeStorage.sol";

/**
 * @title ITransactionGuard Interface
 */
interface ITransactionGuard is IERC165 {
    /**
     * @notice Checks the transaction details.
     * @dev The function needs to implement transaction validation logic.
     * @param to The address to which the transaction is intended.
     * @param value The native token value of the transaction in Wei.
     * @param data The transaction data.
     * @param operation Operation type (0 for `CALL`, 1 for `DELEGATECALL`).
     * @param safeTxGas Gas used for the transaction.
     * @param baseGas The base gas for the transaction.
     * @param gasPrice The price of gas in Wei for the transaction.
     * @param gasToken The token used to pay for gas.
     * @param refundReceiver The address which should receive the refund.
     * @param signatures The signatures of the transaction.
     * @param msgSender The address of the message 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;

    /**
     * @notice Checks after execution of the transaction.
     * @dev The function needs to implement a check after the execution of the transaction.
     * @param hash The hash of the executed transaction.
     * @param success The status of the transaction execution.
     */
    function checkAfterExecution(bytes32 hash, bool success) external;
}

/**
 * @title Base Transaction Guard
 */
abstract contract BaseTransactionGuard is ITransactionGuard {
    /**
     * @inheritdoc IERC165
     */
    function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {
        return
            interfaceId == type(ITransactionGuard).interfaceId || // 0xe6d7a83a
            interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7
    }
}

/**
 * @title Guard Manager
 * @notice A contract managing transaction guards which perform pre and post-checks on Safe transactions.
 * @author Richard Meissner - @rmeissner
 */
abstract contract GuardManager is SelfAuthorized, IGuardManager {
    /**
     * @inheritdoc IGuardManager
     */
    function setGuard(address guard) external override authorized {
        if (guard != address(0) && !ITransactionGuard(guard).supportsInterface(type(ITransactionGuard).interfaceId))
            revertWithError("GS300");

        /* solhint-disable no-inline-assembly */
        /// @solidity memory-safe-assembly
        assembly {
            sstore(GUARD_STORAGE_SLOT, guard)
        }
        /* solhint-enable no-inline-assembly */
        emit ChangedGuard(guard);
    }

    /**
     * @notice Internal method to retrieve the current guard.
     * @dev 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) {
        /* solhint-disable no-inline-assembly */
        /// @solidity memory-safe-assembly
        assembly {
            guard := sload(GUARD_STORAGE_SLOT)
        }
        /* solhint-enable no-inline-assembly */
    }
}

File 61 of 123 : SelfAuthorized.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

import {ErrorMessage} from "../libraries/ErrorMessage.sol";

/**
 * @title Self Authorized
 * @notice Authorizes current contract to perform actions on itself.
 * @author Richard Meissner - @rmeissner
 */
abstract contract SelfAuthorized is ErrorMessage {
    /**
     * @dev Ensure that the `msg.sender` is the current contract.
     */
    function requireSelfCall() private view {
        if (msg.sender != address(this)) revertWithError("GS031");
    }

    /**
     * @notice Ensure that a function is authorized.
     * @dev This modifier authorizes calls by ensuring that the contract called itself.
     */
    modifier authorized() {
        // Modifiers are copied around during compilation. This is a function call to minimized the bytecode size.
        requireSelfCall();
        _;
    }
}

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

/**
 * @title ERC-165 Inteface
 * @dev More details at <https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol>
 */
interface IERC165 {
    /**
     * @notice Returns true if this contract implements the interface defined by `interfaceId`.
     * @dev 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.
     * @param interfaceId The ID of the interface to check support for.
     * @return Whether or not the interface is supported.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// SPDX-License-Identifier: LGPL-3.0-only
/* solhint-disable one-contract-per-file */
pragma solidity >=0.7.0 <0.9.0;

/**
 * @title IGuardManager - A contract interface managing transaction guards which perform pre and post-checks on Safe transactions.
 * @author @safe-global/safe-protocol
 */
interface IGuardManager {
    /**
     * @notice Transaction guard changed.
     * @param guard The address of the new transaction guard.
     */
    event ChangedGuard(address indexed guard);

    /**
     * @notice Set Transaction Guard `guard` for the Safe. Make sure you trust the guard.
     * @dev Set a guard that checks Safe transactions before and after 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. ⚠️⚠️⚠️
     * @param guard The address of the guard to be used or the 0 address to disable the guard
     */
    function setGuard(address guard) external;
}

File 64 of 123 : Enum.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/**
 * @title Enum
 * @notice Collection of enums used in Safe Smart Account contracts.
 * @author @safe-global/safe-protocol
 */
library Enum {
    /**
     * @notice A Safe transaction operation.
     * @custom:variant Call The Safe transaction is executed with the `CALL` opcode.
     * @custom:variant Delegatecall The Safe transaction is executed with the `DELEGATECALL` opcode.
     */
    enum Operation {
        Call,
        DelegateCall
    }
}

File 65 of 123 : ErrorMessage.sol
// SPDX-License-Identifier: LGPL-3.0-only

pragma solidity >=0.7.0 <0.9.0;

/**
 * @title Error Message
 * @notice Revert with with Safe error codes.
 * @dev This contract specializes in reverting for the Safe 5-byte error codes (`GS***`).
 *      This is conceptually very similar to error codes introduced in Solidity version 0.8.
 *      The implementation using assembly saves a lot of gas and code size.
 * @author Shebin John - @remedcu
 */
abstract contract ErrorMessage {
    /**
     * @notice Revert with a Safe 5-byte error code `GS***`.
     * @dev This function behaves in the same way as the built-in Solidity `revert("GS***")` but
     *      it only works for revert messages that are exactly 5 bytes long.
     * @param error The error string to revert with.
     */
    function revertWithError(bytes5 error) internal pure {
        /* solhint-disable no-inline-assembly */
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Selector for method "Error(string)".
            mstore(add(ptr, 0x04), 0x20) // String offset.
            mstore(add(ptr, 0x24), 0x05) // Revert reason length (5 bytes for bytes5).
            mstore(add(ptr, 0x44), error) // Revert reason.
            revert(ptr, 0x64) // Revert data length is 4 bytes for selector + offset + error length + error.
        }
        /* solhint-enable no-inline-assembly */
    }
}

File 66 of 123 : SafeStorage.sol
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/**
 * @title Safe Storage
 * @notice Storage layout of the Safe smart account contracts to be used in libraries.
 * @dev Should be always the first base contract of a library that is used with a Safe.
 * @author Richard Meissner - @rmeissner
 */
abstract contract SafeStorage {
    /**
     * @dev See <../common/Singleton.sol>.
     */
    address internal singleton;

    /**
     * @dev See <../common/ModuleManager.sol>.
     */
    mapping(address => address) internal modules;

    /**
     * @dev See <../common/OwnerManager.sol>.
     */
    mapping(address => address) internal owners;

    /**
     * @dev See <../common/OwnerManager.sol>.
     */
    uint256 internal ownerCount;

    /**
     * @dev See <../common/OwnerManager.sol>.
     */
    uint256 internal threshold;

    /**
     * @dev See <../Safe.sol>.
     */
    uint256 internal nonce;

    /**
     * @dev See <../Safe.sol>.
     */
    bytes32 internal _deprecatedDomainSeparator;

    /**
     * @dev See <../Safe.sol>.
     */
    mapping(bytes32 => uint256) internal signedMessages;

    /**
     * @dev See <../Safe.sol>.
     */
    mapping(address => mapping(bytes32 => uint256)) internal approvedHashes;
}

/**
 * @dev The storage slot used for storing the currently configured fallback handler address.
 *      Precomputed value of: `keccak256("fallback_manager.handler.address")`.
 */
bytes32 constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;

/**
 * @dev The storage slot used for storing the currently configured transaction guard.
 *      Precomputed value of: `keccak256("guard_manager.guard.address")`.
 */
bytes32 constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;

/**
 * @dev The storage slot used for storing the currently configured module guard.
 *      Precomputed value of: `keccak256("module_manager.module_guard.address")`.
 */
bytes32 constant MODULE_GUARD_STORAGE_SLOT = 0xb104e0b93118902c651344349b610029d694cfdec91c589c91ebafbcd0289947;

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

import "@openzeppelin/contracts/access/AccessControl.sol";

contract AccessGuard is AccessControl {
  bytes32 public constant OPERATOR = keccak256("OPERATOR");

  modifier onlyAdmin() {
    _checkRole(DEFAULT_ADMIN_ROLE);
    _;
  }

  modifier onlyOperator() {
    _checkRole(OPERATOR);
    _;
  }

  function addOperator(address operator) external onlyAdmin {
    _grantRole(OPERATOR, operator);
  }

  function removeOperator(address operator) external onlyAdmin {
    _revokeRole(OPERATOR, operator);
  }
}

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

import "@openzeppelin/contracts/access/Ownable.sol";

contract ERC20Whitelist is Ownable {
  mapping(address => bool) private _whitelist;

  constructor() Ownable(_msgSender()) {}

  function updateWhitelist(address[] calldata erc20Addresses_, bool isAccepted_) external onlyOwner {
    for (uint256 i = 0; i < erc20Addresses_.length; ) {
      _whitelist[erc20Addresses_[i]] = isAccepted_;
      unchecked {
        ++i;
      }
    }
  }

  function isAcceptedERC20(address erc20Address_) external view returns (bool) {
    return _whitelist[erc20Address_];
  }
}

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

import "@openzeppelin/contracts/utils/Create2.sol";

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

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

  /* 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) {
    uint256 nextNonce = nonceByUsers[sender_] + 1;
    bytes32 salt = keccak256(abi.encodePacked(sender_, nextNonce));
    bytes32 bytecodeHash = keccak256(bytecode_);
    return Create2.computeAddress(salt, bytecodeHash);
  }

  /**
   * @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;
    nonceByUsers[sender_] += 1;
    bytes32 salt = keccak256(abi.encodePacked(sender_, nonceByUsers[sender_]));
    address legacyAddress = Create2.deploy(0, salt, legacyBytecode_);
    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_];
  }
}

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

import {IERC20Whitelist} from "../interfaces/IERC20Whitelist.sol";
contract GenericLegacy {
  /* 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;

  /* 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];
  }
}

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

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

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

  /* State variable */
  uint256 internal _legacyId;
  mapping(uint256 => address) public legacyAddresses;
  mapping(uint256 => address) public guardAddresses;
  mapping(address => uint256) internal nonceByUsers;
  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) {
    uint256 nextNonce = nonceByUsers[sender_] + 1;
    bytes32 salt = keccak256(abi.encodePacked(sender_, nextNonce));
    bytes32 bytecodeHash = keccak256(bytecode_);
    return Create2.computeAddress(salt, bytecodeHash);
  }

  /**
   * @dev create legacy and guard
   * @param legacyBytecode_  legacy byte code
   * @param guardByteCode_ guard byte code
   * @param sender_ sender
   * @return legacyId
   * @return legacyAddress
   * @return guardAddress
   */
  function _createLegacy(bytes memory legacyBytecode_, bytes memory guardByteCode_, address sender_) internal returns (uint256, address, address) {
    _legacyId += 1;
    nonceByUsers[sender_] += 1;
    bytes32 salt = keccak256(abi.encodePacked(sender_, nonceByUsers[sender_]));
    address legacyAddress = Create2.deploy(0, salt, legacyBytecode_);
    address guardAddress = Create2.deploy(0, salt, guardByteCode_);
    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;
  }


}

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

import {AccessGuard} from "../access/AccessGuard.sol";

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

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

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

contract Payment is AccessControl {
    uint256 public constant FEE_DENOMINATOR = 10000;
    bytes32 public constant WITHDRAWER = keccak256("WITHDRAWER");
    bytes32 public constant OPERATOR = keccak256("OPERATOR");
    uint256 public  claimFee; 
    bool isActive; // if false, no fee will be charged

    event ClaimFeeUpdated(uint256 claimFee, bool isActive);
    event WithdrawERC20(address token, address to, uint256 amount);
    event WithdrawAllERC20(address token, address to);
    event WithdrawETH(address to, uint256 amount);
    event WithdrawAllETH(address to);

    constructor() {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    function setClaimFee(uint256 _claimFee, bool _isActive) external onlyRole(OPERATOR){
        require(_claimFee < FEE_DENOMINATOR, "Claim fee must be less than FEE_DENOMINATOR");
        claimFee = _claimFee;
        isActive = _isActive;
        emit ClaimFeeUpdated(_claimFee, _isActive);
    }

    /**
     * @dev Returns the admin fee percentage
     */
    function getFee() external view returns (uint256) {
        return isActive ? claimFee : 0;
    }

    function withdrawERC20(address _token, address _to, uint256 _amount) external onlyRole(WITHDRAWER){
        IERC20(_token).transfer(_to, _amount);
        emit WithdrawERC20(_token, _to, _amount);
    }

    function withdrawAllERC20(address _token, address _to) external onlyRole(WITHDRAWER){
        uint256 balance = IERC20(_token).balanceOf(address(this));
        IERC20(_token).transfer(_to, balance);
        emit WithdrawAllERC20(_token, _to);
    }

    function withdrawETH(address _to, uint256 _amount) external onlyRole(WITHDRAWER){
        payable(_to).transfer(_amount);
        emit WithdrawETH(_to, _amount);
    }

    function withdrawAllETH(address _to) external onlyRole(WITHDRAWER){
        uint256 balance = address(this).balance;
        payable(_to).transfer(balance);
        emit WithdrawAllETH(_to);
    }

    receive() external payable {}

}

// SPDX-License-Identifier: MIT
// 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 {IERC20} from "../interfaces/IERC20.sol";
import {ISafeGuard} from "../interfaces/ISafeGuard.sol";
import {ISafeWallet} from "../interfaces/ISafeWallet.sol";
import {TransferLegacyStruct} from "../libraries/TransferLegacyStruct.sol";
import {Enum} from "../libraries/Enum.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;

  /* 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 = 100;
  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 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).approve(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).transfer(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 == 100 && delayLayer3 == 0 && _layer3Distribution == 0) {
      return true;
    }

    // Case 3: Both layers are set (premium users)
    if (delayLayer2 != 0 && _layer2Distribution == 100 && delayLayer3 != 0 && _layer3Distribution == 100) {
      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 = 100;
      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 != 100 && _distributionPercentage != 0) revert NeedtoSetLayer2();
      if (_distributionPercentage != 0) {
        if (_layer2Distribution != 100) 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 = 100;
      _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 returns (address[] memory assets, uint8 layer) {
    if (_checkActiveLegacy(guardAddress_)) {
      if (getIsActiveLegacy() == 1) {
        _setLegacyToInactive();
      }
      (assets, layer) = _transferAssetToBeneficiaries(guardAddress_, 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 != 100) 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 pure {
    if (distribution_.percent == 0 || distribution_.percent > 100) revert DistributionAssetInvalid();
    if (distribution_.user == address(0) || distribution_.user == owner_) revert DistributionAssetInvalid();
  }

  /**
   * @dev transfer asset to beneficiaries
   */
  function _transferAssetToBeneficiaries(
    address guardAddress_,
    address[] calldata assets_,
    bool isETH_,
    address bene_
  ) private returns (address[] memory assets, uint8 currentLayer) {
    address safeAddress = getLegacyOwner();
    address[] memory beneficiaries = getBeneficiaries(bene_);
    currentLayer = getCurrentLayer(guardAddress_);
    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;
      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});
      for (uint256 i = 0; i < beneficiaries.length; ) {
        uint256 amount = (distributableEth * getDistribution(beneLayer, beneficiaries[i])) / 100;
        if (amount > 0) {
          _transferEthToBeneficiary(safeAddress, beneficiaries[i], amount);
          receipt[i].listAssetName[n] = symbol;
          receipt[i].listAmount[n] = amount;
        }
        unchecked {
          i++;
        }
      }
      assets = new address[](1);
      assets[0] = address(0);
      // Do not return here; continue to process ERC20 tokens
    }

    // Handle ERC20 transfers

    assets = new address[](n);

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

      symbol = IERC20(token).symbol();
      summary[i] = NotifyLib.ListAsset({listToken: token, listAmount: totalAmountErc20, listAssetName: symbol});

      if (fee > 0) {
        _transferErc20ToBeneficiary(token, safeAddress, address(this), fee);
        _swapAdminFee(token, fee);
      }
      for (uint256 j = 0; j < beneficiaries.length; ) {
        uint256 amount = (distributable * getDistribution(beneLayer, beneficiaries[j])) / 100;
        if (amount > 0) {
          _transferErc20ToBeneficiary(token, safeAddress, beneficiaries[j], amount);
          receipt[j].listAssetName[i] = symbol;
          receipt[j].listAmount[i] = amount;
        }
        unchecked {
          j++;
        }
      }
      assets[i] = token;
      unchecked {
        i++;
      }
    }
    // send notification & email
    IPremiumSetting(premiumSetting).triggerActivationTransferLegacy(summary, receipt, remaining);
  }
  /**
   * @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 {
    bytes memory transferErc20Data = abi.encodeWithSignature("transfer(address,uint256)", to_, amount);
    bool transferErc20Success = ISafeWallet(from_).execTransactionFromModule(erc20Address_, 0, transferErc20Data, Enum.Operation.Call);
    if (!transferErc20Success) revert ExecTransactionFromModuleFailed();
  }

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

// SPDX-License-Identifier: MIT
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, address[] assetAddresses, bool isETH, 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);
    _;
  }

  function initialize(address _premiumSetting, address _verifier, address _paymentContract, address router_, address weth_) external initializer {
    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,
      type(SafeGuard).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();

    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_) {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    ITransferLegacy(legacyAddress).setLayer23Distributions(msg.sender, layer_, nickname_, distribution_);
    emit TransferLegacyLayer23DistributionUpdated(legacyId_, layer_, nickname_, distribution_, block.timestamp);
  }

  /**
   * @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
    (address[] memory assets, uint8 currentLayer) = ITransferLegacy(legacyAddress).activeLegacy(guardAddress, assets_, isETH_, msg.sender);
    uint8 beneLayer = ITransferLegacy(legacyAddress).getBeneficiaryLayer(msg.sender);
    if (beneLayer > currentLayer) revert CannotClaim();
    if (beneLayer == 0) revert OnlyBeneficaries();
    emit TransferLegacyActivated(legacyId_, beneLayer, assets, isETH_, block.timestamp);

  }

  /* Internal function */

}

// SPDX-License-Identifier: MIT
// 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 {IERC20} from "../interfaces/IERC20.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";

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

  /* 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 = 100; 
  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;

  modifier onlyLive() {
    if (_isLive != 1) {
      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).approve(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).transfer(paymentContract, amountIn);
    }
  }

  /* 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 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 == 100 && delayLayer3 == 0 && _layer3Distribution == 0) {
      return true;
    }

    // Case 3: Both layers are set (premium users)
    if (delayLayer2 != 0 && _layer2Distribution == 100 && delayLayer3 != 0 && _layer3Distribution == 100) {
      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 = 100;
      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 != 100 && _distributionPercentage != 0) revert NeedtoSetLayer2();
      if (_distributionPercentage != 0) {
        if (_layer2Distribution != 100) 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();
  }

  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();
  }

  /**
   * @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 = 100;
      _setBeneNickname(_layer3Beneficiary, nickName3);
      skipCheck = false;
    } else {
      _layer3Beneficiary = address(0);
      _layer3Distribution = 0;
    }

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

  /**
   * @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 onlyLive {
    if (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_ check is native token
   */
  function activeLegacy(
    address[] calldata assets_,
    bool isETH_,
    address bene
  ) external onlyRouter onlyLive returns (address[] memory assets, uint8 layer) {
    if (_checkActiveLegacy()) {
      if (getIsActiveLegacy() == 1) {
        _setLegacyToInactive();
      }
      (assets, layer) = _transferAssetToBeneficiaries(assets_, isETH_, bene);
    } else {
      revert NotEnoughContitionalActive();
    }
  }

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

  /* 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 != 100) 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 pure {
    if (distribution_.percent == 0 || distribution_.percent > 100) 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 returns (address[] memory assets, uint8 currentLayer) {
    address ownerAddress = getLegacyOwner();
    address[] memory beneficiaries = getBeneficiaries(bene_);
    currentLayer = getCurrentLayer();
    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;
      uint256 fee = (totalAmountEth * adminFeePercent) / 10000;
      uint256 distributableEth = totalAmountEth - fee;
      if (fee > 0) {
        _transferEthToBeneficiary(paymentContract, fee);
      }
      
      summary[n] = NotifyLib.ListAsset({listToken: address(0), listAmount: totalAmountEth, listAssetName: "ETH"});
      for (uint256 i = 0; i < beneficiaries.length; ) {
        uint256 amount = (distributableEth * getDistribution(beneLayer, beneficiaries[i])) / 100;
        if (amount > 0) {
          _transferEthToBeneficiary(beneficiaries[i], amount);
          receipt[i].listAssetName[n] = "ETH";
          receipt[i].listAmount[n] = amount;
        }
        unchecked {
          i++;
        }
      }
      assets = new address[](1);
      assets[0] = address(0);
    }

    assets = new address[](n);
    for (uint256 i = 0; i < n; ) {
      address token = assets_[i];
      uint256 allowanceAmountErc20 = IERC20(token).allowance(ownerAddress, address(this));
      uint256 balanceAmountErc20 = IERC20(token).balanceOf(ownerAddress);
      uint256 totalAmount = balanceAmountErc20 > allowanceAmountErc20 ? allowanceAmountErc20 : balanceAmountErc20;

      string memory symbol = IERC20(token).symbol();
      summary[i] = NotifyLib.ListAsset({listToken: token, listAmount: totalAmount, listAssetName: symbol});

      uint256 fee = (totalAmount * adminFeePercent) / 10000;
      uint256 distributable = totalAmount - fee;

      if (fee > 0) {
        bool feePullSuccess = IERC20(token).transferFrom(ownerAddress, address(this), fee);
        if (!feePullSuccess) revert SafeTransfromFailed(token, ownerAddress, address(this));
        _swapAdminFee(token, fee);
      }
      for (uint256 j = 0; j < beneficiaries.length; ) {
        uint256 amount = (distributable * getDistribution(beneLayer, beneficiaries[j])) / 100;
        if (amount > 0) {
          _transferErc20ToBeneficiary(token, ownerAddress, beneficiaries[j], amount);
          receipt[j].listAssetName[i] = symbol;
          receipt[j].listAmount[i] = amount;
        }
        unchecked {
          j++;
        }
      }
      assets[i] = token;
      unchecked {
        i++;
      }
    }
    // send notification & email
    IPremiumSetting(premiumSetting).triggerActivationTransferLegacy(
      summary,
      receipt,
      isRemaining
    );

    return (assets, currentLayer);
  }

  /**
   * @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 {
    bool success = IERC20(erc20Address_).transferFrom(from_, to_, amount_);
    if (!success) revert SafeTransfromFailed(erc20Address_, from_, to_);
  }

  /**
   * @dev transfer eth to beneficiaries
   * @param to_ beneficiary address
   */
  function _transferEthToBeneficiary(address to_, uint256 amount_) private {
    if (address(this).balance < amount_) {
      revert NotEnoughETH();
    }
    (bool success, ) = payable(to_).call{value: amount_}("");
    if (!success) {
      revert ExecTransactionFromModuleFailed();
    }
  }
}

// SPDX-License-Identifier: MIT
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 {TransferEOALegacy} from "./TransferLegacyEOAContract.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";

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

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

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

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

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

  /**
   * @dev Get next legacy address that would be created for a sender
   */
  function getNextLegacyAddress(address sender_) external view returns (address) {
    return _getNextAddress(type(TransferEOALegacy).creationCode, 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(type(TransferEOALegacy).creationCode, 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);

    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_);
    IPremiumSetting(premiumSetting).triggerOwnerResetReminder(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);
    

    // 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 {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    ITransferEOALegacy(legacyAddress).setLayer23Distributions(msg.sender, layer_, nickname_, distribution_);
    emit TransferEOALegacyLayer23DistributionUpdated(legacyId_, layer_, nickname_, distribution_, block.timestamp);
  }

  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).activeAlive(msg.sender);
    ITransferEOALegacy(legacyAddress).setLegacyName(name_);
    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
    (address[] memory assets, uint8 currentLayer) = ITransferEOALegacy(legacyAddress).activeLegacy(assets_, isETH_, msg.sender);
    uint8 beneLayer = ITransferEOALegacy(legacyAddress).getBeneficiaryLayer(msg.sender);
    if (beneLayer > currentLayer) revert CannotClaim();
    if (beneLayer == 0) revert OnlyBeneficaries();
    emit TransferEOALegacyActivated(legacyId_, beneLayer, assets, isETH_, 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_);
  }
}

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

import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {GenericLegacy} from "../common/GenericLegacy.sol";
import {IERC20} from "../interfaces/IERC20.sol";
import {ISafeGuard} from "../interfaces/ISafeGuard.sol";
import {ISafeWallet} from "../interfaces/ISafeWallet.sol";
import {MultisigLegacyStruct} from "../libraries/MultisigLegacyStruct.sol";
import {Enum} from "../libraries/Enum.sol";

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

  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
  ) 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_);

    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_
  ) external onlyRouter onlyOwner(sender_) isActiveLegacy returns (uint256 numberOfBeneficiaries) {
    //clear beneficiaries
    _clearBeneficiaries();

    //set minRequiredSignatures
    _setMinRequiredSignatures(minRequiredSigs_);

    //set beneficiaries
    numberOfBeneficiaries = _setBeneficiaries(sender_, beneficiaries_);
  }

  /**
   * @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 benficiariesList = _beneficiariesSet.values();
      _setLegacyToInactive();
      _clearBeneficiaries();
      (newSigners, newThreshold) = _addOwnerWithThreshold(benficiariesList);
    } 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_) 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]);
      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; ) {
      _beneficiariesSet.remove(_beneficiariesSet.at(0));
      unchecked {
        ++i;
      }
    }
  }

  /**
   * @dev Add beneficiaries and set threshold in safe wallet
   * @param newSigners, newThreshold
   */
  function _addOwnerWithThreshold(address[] memory beneficiries_) private returns (address[] memory newSigners, uint256 newThreshold) {
    address owner = getLegacyOwner();
    uint256 threshold = ISafeWallet(owner).getThreshold();
    for (uint256 i = 0; i < beneficiries_.length; ) {
      bytes memory addOwnerData = abi.encodeWithSignature("addOwnerWithThreshold(address,uint256)", beneficiries_[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++;
      }
    }
  }
}

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

import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";

import {LegacyRouter} from "../common/LegacyRouter.sol";
import {LegacyFactory} from "../common/LegacyFactory.sol";
import {MultisigLegacy} from "./MultisigLegacyContract.sol";
import {SafeGuard} from "../SafeGuard.sol";
import {IMultisigLegacy} from "../interfaces/IMultisigLegacyContract.sol";
import {ISafeGuard} from "../interfaces/ISafeGuard.sol";
import {ISafeWallet} from "../interfaces/ISafeWallet.sol";
import {MultisigLegacyStruct} from "../libraries/MultisigLegacyStruct.sol";
import {EIP712LegacyVerifier} from "../term/VerifierTerm.sol";
import {IPremiumSetting} from "../interfaces/IPremiumSetting.sol";
contract MultisigLegacyRouter is LegacyRouter, LegacyFactory, ReentrancyGuardUpgradeable {
  EIP712LegacyVerifier public verifier;
  address public premiumSetting;

  
  /* Error */
  error ExistedGuardInSafeWallet(address);
  error SignerIsNotOwnerOfSafeWallet();
  error NumBeneficiariesInvalid();
  error BeneficiariesInvalid();
  error MinRequiredSignaturesInvalid();
  error ActivationTriggerInvalid();

  /* Struct */
  struct LegacyMainConfig {
    string name;
    string note;
    string[] nickNames;
    address[] beneficiaries;
  }

  /* Event */
  event MultisigLegacyCreated(
    uint256 legacyId,
    address legacyAddress,
    address guardAddress,
    address creatorAddress,
    address safeAddress,
    LegacyMainConfig mainConfig,
    MultisigLegacyStruct.LegacyExtraConfig extraConfig,
    uint256 timestamp
  );

  event MultisigLegacyConfigUpdated(
    uint256 legacyId,
    LegacyMainConfig mainConfig,
    MultisigLegacyStruct.LegacyExtraConfig extraConfig,
    uint256 timestamp
  );
  event MultisigLegacyBeneficiariesUpdated(
    uint256 legacyId,
    string[] nickName,
    address[] beneficiaries,
    uint128 minRequiredSignatures,
    uint256 timestamp
  );
  event MultisigLegacyActivationTriggerUpdated(uint256 legacyId, uint256 lackOfOutgoingTxRange, uint256 timestamp);
  event MultisigLegacyNameNoteUpdated(uint256 legacyId, string name, string note, uint256 timestamp);
  event MultisigLegacyActivated(uint256 legacyId, address[] newSigners, uint256 newThreshold, bool success, uint256 timestamp);

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

  function initialize(address _premiumSetting, address _verifier) public initializer {
    __ReentrancyGuard_init();
    premiumSetting = _premiumSetting;
    verifier = EIP712LegacyVerifier(_verifier);
  }

  /**
   * @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(MultisigLegacy).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 IMultisigLegacy(legacyAddress).checkActiveLegacy(guardAddress);
  }

  /* External function */
  /**
   * @dev Create new legacy and guard.
   * @param safeWallet safeWallet address
   * @param mainConfig_  include name, note, nickname[], beneficiaries[]
   * @param extraConfig_ include minRequireSignature, lackOfOutgoingTxRange
   * @return address legacy address
   * @return address guard address
   */
  function createLegacy(
    address safeWallet,
    LegacyMainConfig calldata mainConfig_,
    MultisigLegacyStruct.LegacyExtraConfig calldata extraConfig_,
    uint256 signatureTimestamp,
    bytes calldata agreementSignature
  ) external nonReentrant returns (address, address) {
    //Check beneficiaries length
    if (mainConfig_.beneficiaries.length != mainConfig_.nickNames.length || mainConfig_.beneficiaries.length == 0) revert BeneficiariesInvalid();

    // Check invalid guard
    if (_checkExistGuardInSafeWallet(safeWallet)) {
      revert ExistedGuardInSafeWallet(safeWallet);
    }

    //Check invalid safe wallet
    if (!_checkSignerIsOwnerOfSafeWallet(safeWallet, msg.sender)) revert SignerIsNotOwnerOfSafeWallet();

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

    // Create new legacy and guard
    (uint256 newLegacyId, address legacyAddress, address guardAddress) = _createLegacy(
      type(MultisigLegacy).creationCode,
      type(SafeGuard).creationCode,
      msg.sender
    );

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

    // Initialize legacy
    uint256 numberOfBeneficiaries = IMultisigLegacy(legacyAddress).initialize(
      newLegacyId,
      safeWallet,
      mainConfig_.beneficiaries,
      extraConfig_,
      guardAddress,
      msg.sender
    );

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

    //Initialize safeguard
    ISafeGuard(guardAddress).initialize();

    //Check min require signatures
    if (extraConfig_.minRequiredSignatures == 0 || extraConfig_.minRequiredSignatures > numberOfBeneficiaries) revert MinRequiredSignaturesInvalid();

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


    emit MultisigLegacyCreated(newLegacyId, legacyAddress, guardAddress, msg.sender, safeWallet, mainConfig_, extraConfig_, block.timestamp);

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

    return (legacyAddress, guardAddress);
  }

  /**
   * @dev Set legacy config include beneficiaries, minRequireSignatures, lackOfOutgoingTxRange.
   * @param legacyId_ legacy Id
   * @param mainConfig_ include name, note, nickname[], beneficiaries[]
   * @param extraConfig_ include minRequireSignature, lackOfOutgoingTxRange
   */
  function setLegacyConfig(
    uint256 legacyId_,
    LegacyMainConfig calldata mainConfig_,
    MultisigLegacyStruct.LegacyExtraConfig calldata extraConfig_
  ) external onlySafeWallet(legacyId_) nonReentrant {
    address legacyAddress = _checkLegacyExisted(legacyId_);

    //Check beneficiaries length
    if (mainConfig_.beneficiaries.length != mainConfig_.nickNames.length || mainConfig_.beneficiaries.length == 0) revert BeneficiariesInvalid();

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

    //Set beneficiaries
    uint256 numberOfBeneficiaries = IMultisigLegacy(legacyAddress).setLegacyBeneficiaries(
      msg.sender,
      mainConfig_.beneficiaries,
      extraConfig_.minRequiredSignatures
    );

    //Check min require signatures
    if (extraConfig_.minRequiredSignatures == 0 || extraConfig_.minRequiredSignatures > numberOfBeneficiaries) revert MinRequiredSignaturesInvalid();

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

    //Set lackOfOutgoingTxRange
    IMultisigLegacy(legacyAddress).setActivationTrigger(msg.sender, extraConfig_.lackOfOutgoingTxRange);

    IMultisigLegacy(legacyAddress).setLegacyName(mainConfig_.name);
    
    emit MultisigLegacyConfigUpdated(legacyId_, mainConfig_, extraConfig_, block.timestamp);
  }

  /**
   * @dev Set beneficiaries[], minRequiredSignatures_ legacy, call this function if only modify beneficiaries[], minRequiredSignatures to save gas for user.
   * @param legacyId_ legacy id
   * @param nickName_ nick name[]
   * @param beneficiaries_ beneficiaries []
   * @param minRequiredSignatures_ minRequiredSignatures
   */

  function setLegacyBeneficiaries(
    uint256 legacyId_,
    string[] calldata nickName_,
    address[] calldata beneficiaries_,
    uint128 minRequiredSignatures_
  ) external onlySafeWallet(legacyId_) nonReentrant {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    //Check  beneficiaries length
    if (beneficiaries_.length != nickName_.length || beneficiaries_.length == 0) revert BeneficiariesInvalid();

    //Set beneficiaries[]
    uint256 numberOfBeneficiaries = IMultisigLegacy(legacyAddress).setLegacyBeneficiaries(msg.sender, beneficiaries_, minRequiredSignatures_);

    //Check min require signatures
    if (minRequiredSignatures_ == 0 || minRequiredSignatures_ > numberOfBeneficiaries) revert MinRequiredSignaturesInvalid();

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

    emit MultisigLegacyBeneficiariesUpdated(legacyId_, nickName_, beneficiaries_, minRequiredSignatures_, block.timestamp);
  }

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

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

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

    emit MultisigLegacyActivationTriggerUpdated(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_);
    IMultisigLegacy(legacyAddress).setLegacyName(name_);
    emit MultisigLegacyNameNoteUpdated(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_) external nonReentrant {
    address legacyAddress = _checkLegacyExisted(legacyId_);
    address guardAddress = _checkGuardExisted(legacyId_);

    //trigger reminder
    IPremiumSetting(premiumSetting).triggerActivationMultisig(legacyAddress);

    //Active legacy
    (address[] memory newSigners, uint256 newThreshold) = IMultisigLegacy(legacyAddress).activeLegacy(guardAddress);

    emit MultisigLegacyActivated(legacyId_, newSigners, newThreshold, true, block.timestamp);
    
 
  }

}

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

interface IEIP712LegacyVerifier {
    function storeLegacyAgreement(address user, address legacyAddress, uint256 timestamp, bytes calldata signature) external;
}

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

interface IERC20 {
  function allowance(address owner, address spender) external view returns (uint256);

  function balanceOf(address account) external view returns (uint256);

  function transfer(address to, uint256 value) external returns (bool);

  function transferFrom(address from, address to, uint256 value) external returns (bool);

  function name() external view returns (string memory);

  function symbol() external view returns (string memory);

  function decimals() external view returns (uint8);
  
  function totalSupply() external view returns (uint);

  function approve(address spender, uint value) external returns (bool);

}

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

interface IERC20Whitelist {
  function isAcceptedERC20(address erc20Address_) external view returns (bool);
}

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

import {MultisigLegacyStruct} from "../libraries/MultisigLegacyStruct.sol";

interface IMultisigLegacy {
  function initialize(
    uint256 legacyId_,
    address owner_,
    address[] calldata beneficiaries_,
    MultisigLegacyStruct.LegacyExtraConfig calldata config_,
    address _safeGuard,
    address creator
  ) external returns (uint256 numberOfBeneficiaries);

  function setLegacyBeneficiaries(
    address sender_,
    address[] calldata beneficiaries_,
    uint128 minRequiredSigs_
  ) external returns (uint256 numberOfBeneficiaries);

  function setActivationTrigger(address sender_, uint256 lackOfOutgoingTxRange_) external;

  function activeLegacy(address guardAddress_) external returns (address[] memory newSigners, uint256 newThreshold);

  function checkActiveLegacy(address guardAddress_) external view returns (bool);

  function setLegacyName(string calldata legacyName_) external;

}

File 84 of 123 : IPayment.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

interface IPayment {
    /**
     * @dev Returns the admin fee percentage
     */
    function getFee() external view returns (uint256);
}

// SPDX-License-Identifier: MIT
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 ;

}

// SPDX-License-Identifier: MIT
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);

}

// SPDX-License-Identifier: MIT
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
  ) external;

  function sendEmailBeforeLayer2ToLayer1(string[] memory beneNames, string[] memory beneEmails, string memory contractName, uint256 x_days) 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) 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) 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) 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) 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;
}

// SPDX-License-Identifier: MIT
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 setPrivateCodeIfNeeded(address legacyAddress) external;
  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;
}

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


interface ProxyAmin {
    function upgradeAndCall(
        address proxy,
        address implementation,
        bytes memory data
    ) external;

    function upgradeTo(address newImplementation) external;
    function upgrade(address proxy, address implementation) external;

    function upgradeToAndCall(address newImplementation, bytes calldata data)external payable;
}

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

interface ISafeGuard {
  function initialize() external;
  function getLastTimestampTxs() external view returns (uint256);
}

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

import {Enum} from "../libraries/Enum.sol";

interface ISafeWallet {
  function execTransactionFromModule(address to, uint256 value, bytes memory data, Enum.Operation operation) external returns (bool success);
  function getStorageAt(uint256 offset, uint256 length) external view returns (bytes memory);
  function getOwners() external view returns (address[] memory);
  function getThreshold() external view returns (uint256);
  function isModuleEnabled(address module) external view returns (bool);
  function disableModule(address prevModule, address module) external;
  function setGuard(address guard) external;
  function isOwner(address owner) external view returns (bool);

}

//SPDX-License-Identifier: MIT
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 returns (address[] memory assets, uint8 layer);

  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 setSwapSettings(TransferLegacyStruct.Swap calldata swap, address _paymentContract) external;
}

//SPDX-License-Identifier: MIT
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 returns (address[] memory assets, uint8 layer);

  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_) external;

  function getBeneficiaryLayer(address beneficiary) external view returns (uint8);

  //function setSwapSettings(address _router, address _weth,address _paymentContract) external ;
}

//SPDX-License-Identifier: MIT
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;
}

//SPDX-License-Identifier: MIT
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);
}

//SPDX-License-Identifier: MIT
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;
}

// SPDX-License-Identifier: MIT
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;
    }
}

File 98 of 123 : Enum.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

library Enum {
  enum Operation {
    Call,
    DelegateCall
  }
}

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

library FormatUnits {
    function format(uint256 amount, uint8 decimals) internal pure returns (string memory) {
        return format(amount, decimals, 6);  // maximum 6 digits after .
    }

    function format(uint256 amount, uint8 decimals, uint8 fractionalDigits) internal pure returns (string memory) {
        if (decimals == 0) {
            return _toString(amount);
        }

        uint256 integerPart = amount / (10 ** decimals);
        uint256 fractionalPart = amount % (10 ** decimals);

        if (fractionalDigits < decimals) {
            fractionalPart /= 10 ** (decimals - fractionalDigits);
        }

        string memory fractionalStr = _padZeros(_toString(fractionalPart), fractionalDigits);
        return string(abi.encodePacked(_toString(integerPart), ".", fractionalStr));
    }

    function _toString(uint256 value) private 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 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    function _padZeros(string memory str, uint8 length) private pure returns (string memory) {
        bytes memory bStr = bytes(str);
        if (bStr.length >= length) {
            return str;
        }
        bytes memory padded = new bytes(length);
        uint256 padLen = length - bStr.length;
        for (uint256 i = 0; i < padLen; i++) {
            padded[i] = "0";
        }
        for (uint256 i = 0; i < bStr.length; i++) {
            padded[padLen + i] = bStr[i];
        }
        return string(padded);
    }
}

File 100 of 123 : MultisigLegacyStruct.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

library MultisigLegacyStruct {
  struct LegacyExtraConfig {
    uint128 minRequiredSignatures;
    uint128 lackOfOutgoingTxRange;
  }
}

File 101 of 123 : NotifyLib.sol
// SPDX-License-Identifier: MIT
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
  }


  
}

File 102 of 123 : TransferLegacyStruct.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

library TransferLegacyStruct {
  struct LegacyExtraConfig {
    uint256 lackOfOutgoingTxRange;
    uint256 delayLayer2;
    uint256 delayLayer3;
  }

  struct Distribution {
    address user;
    uint8 percent;
  }

  struct Swap {
    address router;
    address weth;
  }
}

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

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";

contract MockERC1155 is ERC1155 {
  uint256 private tokenId;

  constructor() ERC1155("https://uri.sotatek.works") {}

  function mint(address user, uint256 amount) public {
    _mint(user, tokenId, 5, "");
    tokenId++;
  }
}

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

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract ERC20Token is ERC20, Ownable {
    uint8  _decimals;

    constructor(string memory name, string memory symbol, uint8 _tokenDecimals) ERC20(name, symbol) Ownable(msg.sender) {

        _decimals = _tokenDecimals;
    }

    function mint(address to, uint256 amount) external onlyOwner {
        _mint(to, amount);
    }

    function burn(uint256 amount) external {
        _burn(msg.sender, amount);

    }

    function decimals() public view virtual override returns (uint8) {
        return _decimals;
    }
}

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

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract MockERC721 is ERC721 {
  uint256 private tokenId;

  constructor() ERC721("Test Token", "Test Token") {}

  function mint(address user, uint256 amount) public {
    for (uint256 i = 0; i < amount; i++) {
      _mint(user, tokenId);
      tokenId++;
    }
  }
}

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

import "../libraries/FormatUnits.sol";

contract FormatUnitsTestWrapper {
    using FormatUnits for uint256;

    function callFormat(uint256 amount, uint8 decimals) external pure returns (string memory) {
        return amount.format(decimals);
    }
}

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

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract LegacyToken is ERC20, Ownable {
  constructor(string memory name, string memory symbol) ERC20(name, symbol) Ownable(msg.sender) {}

  function mint(address to, uint256 amount) public {
    _mint(to, amount);
  }
}

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

import {AutomationCompatibleInterface} from "@chainlink/contracts/src/v0.8/automation/interfaces/AutomationCompatibleInterface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IPremiumSetting.sol";
import "../interfaces/IPremiumLegacy.sol";
import "../interfaces/IPremiumAutomationManager.sol";
import "../libraries/NotifyLib.sol";
import {ISafeWallet} from "../interfaces/ISafeWallet.sol";


contract PremiumAutomation is AutomationCompatibleInterface {
  using NotifyLib for *;
  bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
  address public user;
  IPremiumSetting public setting;
  IPremiumAutomationManager public manager;
  address[] public legacyContracts;
  mapping(address legacy => mapping(NotifyLib.NotifyType => uint256)) lastNotify;
  mapping(address => bool) enableNotify; //fasle if activated / deleted
  uint256 public defaultNotifyAhead; // time to notify before activation if user doesn't set it
  uint256 public keepupId;
  address public forwarder;

  event KeepupIdAndForwarderSet(uint256 indexed keepupId, address indexed forwarder);
  
  modifier onlyManager() {
    require(msg.sender == address(manager), "Only Manager");
    _;
  }

  modifier onlyForwarder()  { 
    require(msg.sender == forwarder, "Only Forwarder");
    _; 
  }

  function initialize(address _user, address _premiumSetting, uint256 _defaultNotifyAhead) public  {
    require(user == address(0), "Already initialized");
    user = _user;
    setting = IPremiumSetting(_premiumSetting);
    manager = IPremiumAutomationManager(msg.sender);
    defaultNotifyAhead = _defaultNotifyAhead;
  }

  ///@dev check if there is any notification to send
  function checkUpkeep(bytes calldata) external view override returns (bool upkeepNeeded, bytes memory performData) {
    if (!setting.isPremium(user)) return (false, "");

    uint256 notifyAhead = setting.getTimeAhead(user) > 0 ? setting.getTimeAhead(user) : defaultNotifyAhead;

    for (uint256 i = 0; i < legacyContracts.length; i++) {
      address legacy = legacyContracts[i];

      if(!enableNotify[legacy]) continue;
      if (!_checkGuardInSafeWalletLegacy(legacy)) return (false, "");


      if (!IPremiumLegacy(legacy).isLive()) {
        return (true, abi.encode(legacy, NotifyLib.NotifyType.ContractActivated)); //mark disabled
      }
      // bene , layer2, layer 3
      (uint256 t1, uint256 t2, uint256 t3) = IPremiumLegacy(legacy).getTriggerActivationTimestamp();
      uint8 currentLayer = IPremiumLegacy(legacy).getLayer();
      uint256 nowTs = block.timestamp;
      uint256 notifyCooldown = IPremiumLegacy(legacy).getActivationTrigger();

      ///Multisig Legacy is always in layer1 
      //Transfer Legacy can switch to layer 2 or 3
      if (currentLayer == 1) {
        if (nowTs  >= t2 - notifyAhead && t2 != t1 && isCooldownOver(legacy, NotifyLib.NotifyType.BeforeLayer2, notifyCooldown)) {
          return (true, abi.encode(legacy, NotifyLib.NotifyType.BeforeLayer2));
        }

        if (nowTs >= t1 && isCooldownOver(legacy, NotifyLib.NotifyType.ReadyToActivate, notifyCooldown)) {
          uint256 lastNotifyBefore = lastNotify[legacy][NotifyLib.NotifyType.BeforeActivation];
          uint256 lastNotifyReady = lastNotify[legacy][NotifyLib.NotifyType.ReadyToActivate];
          if (lastNotifyReady <= lastNotifyBefore) { // must notiy before
            return (true, abi.encode(legacy, NotifyLib.NotifyType.ReadyToActivate));
          }
        }

        if (nowTs  >= t1 - notifyAhead && nowTs < t1  && isCooldownOver(legacy, NotifyLib.NotifyType.BeforeActivation, notifyCooldown)) {
          return (true, abi.encode(legacy, NotifyLib.NotifyType.BeforeActivation));
        }
      }

      if (currentLayer == 2) {
        if (nowTs  >= t3 - notifyAhead && t3 != t2 && isCooldownOver(legacy, NotifyLib.NotifyType.BeforeLayer3, notifyCooldown)) {
          return (true, abi.encode(legacy, NotifyLib.NotifyType.BeforeLayer3));
        }

        if (nowTs >= t2  && isCooldownOver(legacy, NotifyLib.NotifyType.Layer2ReadyToActivate, notifyCooldown)) {
          uint256 lastNotifyBeforeL2 = lastNotify[legacy][NotifyLib.NotifyType.BeforeLayer2];
          uint256 lastNotifyReadyL2 = lastNotify[legacy][NotifyLib.NotifyType.Layer2ReadyToActivate];
          if (lastNotifyReadyL2 <= lastNotifyBeforeL2) { // must notiy before
            return (true, abi.encode(legacy, NotifyLib.NotifyType.Layer2ReadyToActivate));
          }
        }
      }

      if (currentLayer == 3) {
        uint256 lastNotifyLayer3 = lastNotify[legacy][NotifyLib.NotifyType.Layer3ReadyToActivate];
        uint256 lastNotifyLayer2 = lastNotify[legacy][NotifyLib.NotifyType.Layer2ReadyToActivate];
        if (isCooldownOver(legacy, NotifyLib.NotifyType.Layer3ReadyToActivate, notifyCooldown)
          && lastNotifyLayer3 <= lastNotifyLayer2
        ) {
          return (true, abi.encode(legacy, NotifyLib.NotifyType.Layer3ReadyToActivate));
        }
      }
    }

    return (false, "");
  }

  function performUpkeep(bytes calldata data) external override {
    if(!setting.isPremium((user))) return;
    (address legacy, NotifyLib.NotifyType notifyType) = abi.decode(data, (address, NotifyLib.NotifyType));
    //Already notified when contract activated
    if (notifyType == NotifyLib.NotifyType.ContractActivated) {
        enableNotify[legacy] = false;
        return; 
    }
    lastNotify[legacy][notifyType] = block.timestamp;
    //send reminder
    IPremiumAutomationManager(manager).sendNotifyFromCronjob(legacy, notifyType);
  }

  function addLegacyIfNeed(address[] memory legacyAddresses) external onlyManager {
    for (uint256 i = 0; i < legacyAddresses.length; i++) {
      address legacy = legacyAddresses[i];
      if (enableNotify[legacy] == false) {
        legacyContracts.push(legacy);
        enableNotify[legacy] = true;
      }
    }
  }

  function setKeepUpIdAndForwarder(uint256 _keepupId, address _forwarder) external onlyManager {
    keepupId = _keepupId;
    forwarder = _forwarder;
    emit KeepupIdAndForwarderSet(keepupId, forwarder);
  }

  function decodePerformData(bytes calldata data) external pure returns (address legacy, NotifyLib.NotifyType notifyType) {
    return abi.decode(data, (address, NotifyLib.NotifyType));
  }

  function isCooldownOver(address legacy, NotifyLib.NotifyType notifyType, uint256 cooldown) internal view returns (bool) {
    return block.timestamp > lastNotify[legacy][notifyType] + cooldown;

  }

  function _checkGuardInSafeWalletLegacy(address legacyAddress) internal view returns (bool) {
    IPremiumLegacy legacy = IPremiumLegacy(legacyAddress);
    if (legacy.LEGACY_TYPE() == 3) return true; // Skip check EOA legacy (Live by default when created)
    address safeWallet_ = legacy.getLegacyOwner();
    bytes memory guardSafeWalletBytes = ISafeWallet(safeWallet_).getStorageAt(uint256(GUARD_STORAGE_SLOT), 1);
    address guardSafeWalletAddress = address(uint160(uint256(bytes32(guardSafeWalletBytes))));
    if (guardSafeWalletAddress == address(0)) return false;
    return true;
  }
}

//SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/Create2.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../libraries/NotifyLib.sol";
import "../interfaces/IPremiumLegacy.sol";
import "./PremiumAutomation.sol";
import "../interfaces/IPremiumSendMail.sol";
import {LinkTokenInterface} from "@chainlink/contracts/src/v0.8/shared/interfaces/LinkTokenInterface.sol";
import "../libraries/ArrayUtils.sol";

struct RegistrationParams {
  string name;
  bytes encryptedEmail;
  address upkeepContract;
  uint32 gasLimit;
  address adminAddress;
  uint8 triggerType;
  bytes checkData;
  bytes triggerConfig;
  bytes offchainConfig;
  uint96 amount;
}

interface AutomationRegistrarInterface {
  function registerUpkeep(RegistrationParams calldata requestParams) external returns (uint256);
}

interface IKeeperRegistryMaster {
  function addFunds(uint256 id, uint96 amount) external;
  function getForwarder(uint256 upkeepID) external view returns (address);
  function getMinBalance(uint256 id) external view returns (uint96);
  function getMinBalanceForUpkeep(uint256 id) external view returns (uint96 minBalance);
  function getBalance(uint256 id) external view returns (uint96 balance);
}

contract PremiumAutomationManager is OwnableUpgradeable {
  using NotifyLib for *;
  LinkTokenInterface public i_link;
  AutomationRegistrarInterface public i_registrar;
  mapping(address => uint256) public nonceByUsers;
  mapping(address => address) public cronjob; //store cron-job contract address for each user
  address public premiumSetting;
  uint32 baseGasLimit; //500000 1000000

  address public notification; // deprecated

  uint256 public defaultNotifyAhead; // time to notify before activation if user doesn't set it

  IPremiumSendMail public premiumSendMail; //SendMail Router

  IKeeperRegistryMaster public keeperRegistry; // to add fund dynamically
  uint256 notifyId;


  event CronjobCreated(address indexed user, address indexed cronjobAddress);
  event LegacyAdded(address indexed user, address[] indexed legacyAddress, address indexed cronjobAddress);
  event NotificationSent(
    address indexed legacy,
    NotifyLib.NotifyType notifyType,
    NotifyLib.RecipientType recipientType,
    address[] recipients,
    string body
  );

  modifier onlySetting() {
    require(msg.sender == premiumSetting || msg.sender == owner(), "only setting");
    _;
  }

  modifier onlyCronjob() {
    address user = PremiumAutomation(msg.sender).user();
    require(cronjob[user] == msg.sender, "only crobjob");
    _;
  }

  function initialize() public initializer {
    __Ownable_init(msg.sender);
  }

  function setParams(
    address _i_link,
    address _i_registrar,
    address _keeperRegistry,
    address _premiumSetting,
    uint32 _baseGasLimit,
    address _premiumSendMail, //send mail router 
    uint256 _defaultNotifyAhead
  ) external onlyOwner {
    require(_i_link != address(0), "invalid _i_link");
    require(_i_registrar != address(0), "invalid _i_registrar");
    require(_premiumSetting != address(0), "invalid _premiumSetting");
    require(_baseGasLimit > 0, "invaid _baseGasLimit");
    require(_defaultNotifyAhead > 0, "invalid _defaultNotifyAhead");

    premiumSetting = _premiumSetting;
    i_link = LinkTokenInterface(_i_link);
    i_registrar = AutomationRegistrarInterface(_i_registrar);
    keeperRegistry = IKeeperRegistryMaster(_keeperRegistry);
    baseGasLimit = _baseGasLimit;
    defaultNotifyAhead = _defaultNotifyAhead;
    premiumSendMail = IPremiumSendMail(_premiumSendMail);
    i_link.approve(address(keeperRegistry), type(uint256).max);
    i_link.approve(address(i_registrar), type(uint256).max);
  }
  ///@dev create contract cronjob for user (if not created yet) and add legacy to cronjob
  function addLegacyCronjob(address user, address[] memory legacyAddresses) external onlySetting {
    if (!IPremiumSetting(premiumSetting).isPremium(user)) {
      return;
    }
    if (cronjob[user] == address(0)) {
      _createCronjob(user);
    }
    _addLegacy(user, legacyAddresses);
  }

  function addLegacy(address user, address[] memory legacyAddresses) external onlyOwner {
    _addLegacy(user, legacyAddresses);
  }

  function resetCronjob(address user) external onlyOwner {
    delete cronjob[user];
  }

  function resetCronjobs(address[] memory users) external onlyOwner {
    for (uint256 i = 0; i < users.length; i++) {
      delete cronjob[users[i]];
    }
  }

  function createCronjob(address user) external onlyOwner {
    _createCronjob(user);
  }

  function _createCronjob(address user) internal {
    nonceByUsers[user] += 1;
    bytes32 salt = keccak256(abi.encodePacked(user, nonceByUsers[user]));
    address cronjobAddress = Create2.deploy(0, salt, type(PremiumAutomation).creationCode);

    PremiumAutomation(cronjobAddress).initialize(user, premiumSetting, defaultNotifyAhead);
    cronjob[user] = cronjobAddress;

    RegistrationParams memory params = RegistrationParams({
      name: string.concat("Cronjob ", Strings.toHexString(user)),
      encryptedEmail: "",
      upkeepContract: cronjobAddress,
      gasLimit: baseGasLimit,
      adminAddress: owner(),
      triggerType: 0,
      checkData: "",
      triggerConfig: "",
      offchainConfig: "",
      amount: 1e18 //0.1
    });

    _registerAndPredictID(params);

    emit CronjobCreated(user, cronjobAddress);
  }

  function _registerAndPredictID(RegistrationParams memory params) internal {
    uint256 upkeepID = i_registrar.registerUpkeep(params);
    if (upkeepID != 0) {
      // set keepupId and forwarder
      address forwarder = IKeeperRegistryMaster(keeperRegistry).getForwarder(upkeepID);
      PremiumAutomation(params.upkeepContract).setKeepUpIdAndForwarder(upkeepID, forwarder);
      _fundKeepupIfNeeded(upkeepID);
    } else {
      revert("auto-approve disabled");
    }
  }

  function _addLegacy(address user, address[] memory legacyAddresses) internal {
    address cronjobAddress = cronjob[user];
    if (cronjobAddress != address(0)) {
      PremiumAutomation(cronjobAddress).addLegacyIfNeed(legacyAddresses);
      emit LegacyAdded(user, legacyAddresses, cronjobAddress);
      _fundKeepupIfNeeded(PremiumAutomation(cronjobAddress).keepupId());
    }
  }

  function sendNotifyFromCronjob(address legacy, NotifyLib.NotifyType notifyType) external onlyCronjob {
    //send email
    if (address(premiumSendMail) != address(0)) {
      _sendEmailFromManager(legacy, notifyType);
    }

    //Fund keepup if needed
    uint256 keepupId = PremiumAutomation(msg.sender).keepupId();
    _fundKeepupIfNeeded(keepupId);
  }


  function sendEmailFromManager(address legacy, NotifyLib.NotifyType notifyType) external onlyOwner {
    _sendEmailFromManager(legacy, notifyType);
  }

  function _sendEmailFromManager(address legacy, NotifyLib.NotifyType notifyType) internal {
    // return;
    //process send email for each type of notify
    if (notifyType == NotifyLib.NotifyType.BeforeActivation) {
      _handleBeforeActivation(legacy);
    }
    if (notifyType == NotifyLib.NotifyType.ReadyToActivate) {
      _handleReadyToActivate(legacy);
    }
    
    if (notifyType == NotifyLib.NotifyType.BeforeLayer2) {
      _handleBeforeLayer2(legacy);
    }

    if (notifyType == NotifyLib.NotifyType.Layer2ReadyToActivate) {
      _handleReadyToActivateLayer2(legacy);
    }

    if (notifyType == NotifyLib.NotifyType.BeforeLayer3) {
      _handleBeforeLayer3(legacy);
    }

    if (notifyType == NotifyLib.NotifyType.Layer3ReadyToActivate) {
      _handleReadyToActivateLayer3(legacy);
    }
  }

  function withdrawLINK(address to) external onlyOwner{
    i_link.transfer(to, i_link.balanceOf(address(this)));
  }

  function _fundKeepupIfNeeded(uint256 keepupId) internal {
    uint96 minBalance = IKeeperRegistryMaster(keeperRegistry).getMinBalance(keepupId);
    uint96 balance = IKeeperRegistryMaster(keeperRegistry).getBalance(keepupId);
    if (balance <= (minBalance * 13000) / 10000) {
      IKeeperRegistryMaster(keeperRegistry).addFunds(keepupId, (minBalance * 13000) / 10000);
    }
  }

  function _handleReadyToActivate(address legacy) internal {
    string memory contractName = IPremiumLegacy(legacy).getLegacyName();
    // send email to layer 1 only
    (, string [] memory beneEmails, string [] memory beneNames) = IPremiumSetting(premiumSetting).getBeneficiaryData(legacy);
    premiumSendMail.sendEmailReadyToActivateToLayer1(beneNames, beneEmails, contractName);
  }

  function _handleReadyToActivateLayer2(address legacy) internal {
    // send email to layer 1 
    string memory contractName = IPremiumLegacy(legacy).getLegacyName();
    (, string [] memory beneEmails, string [] memory beneNames) = IPremiumSetting(premiumSetting).getBeneficiaryData(legacy);
    (address layer2Address,string memory layerEmail , string memory layer2Name) = IPremiumSetting(premiumSetting).getSecondLineData(legacy);
    (, uint256 t2, ) = IPremiumLegacy(legacy).getTriggerActivationTimestamp();
    IPremiumSendMail(premiumSendMail).sendEmailReadyToActivateLayer2ToLayer1(beneNames, beneEmails, layer2Address, contractName, t2);
    IPremiumSendMail(premiumSendMail).sendEmailReadyToActivateLayer2ToLayer2(layer2Name, layerEmail, contractName);
  }

  function _handleReadyToActivateLayer3(address legacy) internal {
    string memory contractName = IPremiumLegacy(legacy).getLegacyName();
    (, string [] memory beneEmails, string [] memory beneNames) = IPremiumSetting(premiumSetting).getBeneficiaryData(legacy);
    (, string memory layer2Email, string memory layer2Name) = IPremiumSetting(premiumSetting).getSecondLineData(legacy);
    (address layer3Address, string memory layer3Email, string memory layer3Name) = IPremiumSetting(premiumSetting).getThirdLineData(legacy);
    (, uint256 t3, ) = IPremiumLegacy(legacy).getTriggerActivationTimestamp();
    IPremiumSendMail(premiumSendMail).sendEmailReadyToActivateLayer3ToLayer3(layer3Name, layer3Email, contractName);
    IPremiumSendMail(premiumSendMail).sendEmailReadyToActivateLayer3ToLayer12(beneNames, beneEmails, contractName, t3, layer3Address);
    if (bytes(layer2Email).length != 0) {
      IPremiumSendMail(premiumSendMail).sendEmailReadyToActivateLayer3ToLayer12(
        ArrayUtils.makeStringArray(layer2Name), 
        ArrayUtils.makeStringArray(layer2Email), contractName, t3, layer3Address);
    }
  }


  function _handleBeforeActivation(address legacy) internal {
    string memory contractName = IPremiumLegacy(legacy).getLegacyName();
    (uint256 t1, , ) = IPremiumLegacy(legacy).getTriggerActivationTimestamp();
    (string memory ownerName, string memory ownerEmail, ) = IPremiumSetting(premiumSetting).getUserData(IPremiumLegacy(legacy).creator());
    (address[] memory beneAddrs, string[] memory beneEmails, string[] memory beneNames) = IPremiumSetting(premiumSetting).getBeneficiaryData(legacy);
    uint256 lastTimestamp = IPremiumLegacy(legacy).getLastTimestamp();
    // 1.to owner
    if (bytes(ownerEmail).length != 0) {
      premiumSendMail.sendEmailBeforeActivationToOwner(ownerName, contractName, lastTimestamp, t1-lastTimestamp, beneAddrs, ownerEmail);
    }

    // 2.to beneficiary
    uint256 timeCountdown = t1 > lastTimestamp ? (t1 - lastTimestamp) / 86400 : 0;
    premiumSendMail.sendEmailBeforeActivationToBeneficiary(beneNames, contractName, timeCountdown, beneEmails);
  }

  function _handleBeforeLayer2(address legacy) internal {
    //prepare data
    string memory contractName = IPremiumLegacy(legacy).getLegacyName();
    (, uint256 t2, ) = IPremiumLegacy(legacy).getTriggerActivationTimestamp();
    uint256 dayTillActivate = t2 > block.timestamp ? (t2 - block.timestamp) / 86400 : 0;
    (, string[] memory beneEmails, string[] memory beneNames) = IPremiumSetting(premiumSetting).getBeneficiaryData(legacy);
    (, string memory layer2Email, string memory layer2Name) = IPremiumSetting(premiumSetting).getSecondLineData(legacy);


    //2.to layer1
    premiumSendMail.sendEmailBeforeLayer2ToLayer1(beneNames, beneEmails, contractName, dayTillActivate);

    //3.to layer2
    if (bytes(layer2Email).length != 0) {
      premiumSendMail.sendEmailBeforeLayer2ToLayer2(layer2Name, layer2Email, contractName, dayTillActivate);
    }
    return;
  }

  function _handleBeforeLayer3(address legacy) internal {
    //prepare data
    string memory contractName = IPremiumLegacy(legacy).getLegacyName();
    (, , uint256 t3) = IPremiumLegacy(legacy).getTriggerActivationTimestamp();
    (, string memory layer2Email, string memory layer2Name) = IPremiumSetting(premiumSetting).getSecondLineData(legacy);
    (, string memory layer3Email, string memory layer3Name) = IPremiumSetting(premiumSetting).getThirdLineData(legacy);
    (, string [] memory beneEmails, string [] memory beneNames) = IPremiumSetting(premiumSetting).getBeneficiaryData(legacy);
    uint256 dayTillActivate = t3 > block.timestamp  ? (t3 - block.timestamp) / 86400 : 0;
    //1.to layer1
    premiumSendMail.sendEmailBeforeLayer3ToLayer12(beneNames, beneEmails, contractName, dayTillActivate);

    //2.to layer2
    if (bytes(layer2Email).length != 0) {
      premiumSendMail.sendEmailBeforeLayer3ToLayer12(ArrayUtils.makeStringArray(layer2Name), ArrayUtils.makeStringArray(layer2Email), contractName, dayTillActivate);
    }

    //3.to layer3
    if (bytes(layer3Email).length != 0) {
      premiumSendMail.sendEmailBeforeLayer3ToLayer3(layer3Name, layer3Email, contractName, dayTillActivate);
    }
  }

  function handleActivated(address legacy, address[] memory listToken, uint256[] calldata listAmount, address activatedByBene) external onlySetting {
    string memory contractName = IPremiumLegacy(legacy).getLegacyName();
    (, string[] memory beneEmails, string[] memory beneNames) = IPremiumSetting(premiumSetting).getBeneficiaryData(legacy);
    (, string memory layer2Email, string memory layer2Name) = IPremiumSetting(premiumSetting).getSecondLineData(legacy);
    // (, string memory layer3Email, string memory layer3Name) = IPremiumSetting(premiumSetting).getThirdLineData(legacy);
    (, address layer2, address layer3) = IPremiumLegacy(legacy).getLegacyBeneficiaries();
    string[] memory listAssetName = new string[](listToken.length);
    for (uint256 i = 0; i < listToken.length; i++) {
      listAssetName[i] = ERC20(listToken[i]).symbol();
    }

    //to owner

    //to beneficiaries all layers
    if (activatedByBene == layer2) {
      if (bytes(layer2Email).length != 0) {
        premiumSendMail.sendEmailActivatedToLayer2(layer2Name, layer2Email, contractName, listToken, listAmount, listAssetName);
      }
    } else {
      if (activatedByBene != layer3) {
        // => activated by layer 1
        for (uint i = 0; i < beneEmails.length; i++) {
          if (bytes(beneEmails[i]).length != 0) {
            premiumSendMail.sendEmailActivatedToLayer1(beneNames[i], beneEmails[i], contractName, listToken, listAmount, listAssetName);
          }
        }
      } else {
        // => activated by layer 3
        // No template found
      }
    }
  }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@chainlink/contracts/src/v0.8/functions/v1_0_0/interfaces/IFunctionsRouter.sol";
import {FunctionsRequest} from "@chainlink/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsRequest.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "../libraries/NotifyLib.sol";
import "../libraries/FormatUnits.sol";
import "../interfaces/IPremiumLegacy.sol";
import "../interfaces/IPremiumSetting.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract PremiumMailActivated is OwnableUpgradeable {
  using FunctionsRequest for FunctionsRequest.Request;
  using FormatUnits for uint256;
  struct BeneReceived {
    string name;
    address beneAddress;
    string[] listAssetName;
    uint256[] listAmount;
  }

  struct ListAsset {
    address listToken;
    uint256 listAmount;
    string listAssetName;
  }

  //CHAINLINK FUNCTION
  address public router = 0xb83E47C2bC239B3bf370bc41e1459A34b41238D0;
  bytes32 public donID = 0x66756e2d657468657265756d2d7365706f6c69612d3100000000000000000000;
  uint64 public subscriptionId;

  //PREMIUM CONTRACT
  address public sendMailRouter; // the only contract can call send email

  //MAIL SERVICE
  string private constant authHeader = "OGNlYWI2NGFmZTExNWRiYWJiMThhNGQzODAzYjE3OTI6ZDRlMDRjMmU1MTdmNWQzMjA4NjhiYmI3OTQ4ZTZiMzk=";

  // State variables
  bytes32 public s_lastRequestId;
  bytes public s_lastResponse;
  bytes public s_lastError;
  uint256 public mailId;

  //Callback gas limit
  uint32 public gasLimit = 300000;

  // email invoke name
  uint256 constant ACTIVATED_TO_BENE= 7179581;
  uint256 constant ACTIVATED_TO_BENE_WITH_REMAINING = 7179575;
  uint256 constant ACTIVATED_MULTISIG = 7180065;
  uint256 constant CONTRACT_ACTIVATED_TO_OWNER = 7196254;

  uint256 constant OWNER_RESET_TO_BENE = 7190445;
  uint256 constant OWNER_RESET_TO_LAYER2 = 7190445;
  uint256 constant OWNER_RESET_TO_LAYER3 = 7190445;

  // Custom error type
  error UnexpectedRequestID(bytes32 requestId);
  error OnlyRouterCanFulfill();

  // Event to log responses
  event Response(bytes32 indexed requestId, bytes response, bytes err);
  event RequestSent(bytes32 indexed id);
  event RequestFulfilled(bytes32 indexed id);
  event SendMail(string to, NotifyLib.NotifyType notifyType);

  modifier onlyRouter() {
    require(msg.sender == sendMailRouter, "Only router");
    _;
  }

  function initialize(address _router, uint64 _subscriptionId, bytes32 _donId, uint32 _gasLimit, address _sendMailRouter) public initializer {
    router = _router;
    subscriptionId = _subscriptionId;
    donID = _donId;
    gasLimit = _gasLimit;
    sendMailRouter = _sendMailRouter;
    __Ownable_init(msg.sender);
  }

  function setParams(address _router, uint64 _subscriptionId, bytes32 _donId, uint32 _gasLimit, address _sendMailRouter) external onlyOwner {
    router = _router;
    subscriptionId = _subscriptionId;
    donID = _donId;
    gasLimit = _gasLimit;
    sendMailRouter = _sendMailRouter;
  }

  /**
   * @notice Callback function for fulfilling a request
   * @param requestId The ID of the request to fulfill
   * @param response The HTTP response data
   * @param err Any errors from the Functions request
   */
  function fulfillRequest(bytes32 requestId, bytes memory response, bytes memory err) internal {
    if (s_lastRequestId != requestId) {
      revert UnexpectedRequestID(requestId);
    }
    s_lastResponse = response;
    s_lastError = err;
    emit Response(requestId, s_lastResponse, s_lastError);
  }

  function handleOracleFulfillment(bytes32 requestId, bytes memory response, bytes memory err) external {
    require(msg.sender == router, "Only router can fulfill");
    fulfillRequest(requestId, response, err);
    emit RequestFulfilled(requestId);
  }

  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 onlyRouter {
    if (!remaining) {
      _sendEmailActivatedToBene(beneName, beneEmail, contractName, listToken, listAmount, listAssetName, contractAddress);
    } else {
      _sendEmailActivatedToBeneWithRemaining(beneName, beneEmail, contractName, listToken, listAmount, listAssetName, contractAddress);
    }
    _emitSendMail(beneEmail, NotifyLib.NotifyType.ContractActivated);
  }

  function sendEmailContractActivatedToOwner(
    string memory toEmail,
    string memory contractName,
    address activatedByBene,
    uint256 timeActivated,
    address safeWallet,
    ListAsset[] memory _listAsset,
    BeneReceived[] memory _listBeneReceived,
    address contractAddress,
    bool remaining
  ) external onlyRouter {
    _sendEmailContractActivatedToOwner(
      toEmail,
      contractName,
      activatedByBene,
      timeActivated,
      safeWallet,
      _listAsset,
      _listBeneReceived,
      contractAddress,
      remaining
    );
    _emitSendMail(toEmail, NotifyLib.NotifyType.ContractActivated);
  }

  function sendMailActivatedMultisig(
    string[] memory beneNames,
    string[] memory beneEmails,
    string memory contractName,
    address safeWallet
  ) external onlyRouter {
    for (uint256 i = 0; i < beneNames.length; i++) {
      if (bytes(beneEmails[i]).length > 0) {
        _sendActivatedMutisig(beneNames[i], beneEmails[i], contractName, safeWallet);
        _emitSendMail(beneEmails[i], NotifyLib.NotifyType.ContractActivated);
      }
    }
  }

  //Onwer Reset
  function sendMailOwnerResetToBene(string[] memory beneNames, string[] memory beneEmails, string memory contractName) external onlyRouter {
    for (uint256 i = 0; i < beneNames.length; i++) {
      if (bytes(beneEmails[i]).length > 0) {
        _sendEmailOwnerResetToBene(beneNames[i], beneEmails[i], contractName);
        _emitSendMail(beneEmails[i], NotifyLib.NotifyType.OwnerReset);
      }
    }
  }

  // common function
  function _sendEmailToAddressBegin(string memory to, string memory subject, uint256 templateId) private pure returns (string memory) {
    string memory formatEmailTo = string.concat(
      "const emailURL = 'https://api.mailjet.com/v3.1/send';",
      "const authHeader = 'Basic ",
      authHeader,
      "';",
      "const emailData = { Messages: ",
      "[ { From: {Email: '[email protected]', Name: '10102 Platform',},",
      "To: [ {Email: '",
      to,
      "', Name:'',},],",
      "TemplateID: ",
      Strings.toString(templateId),
      ", TemplateLanguage: true,",
      "Subject: '",
      subject,
      "',",
      "Variables: {"
    );
    return formatEmailTo;
  }

  function _sendEmailToAddressEnd() private pure returns (string memory) {
    string memory formatEmailEnd = string.concat(
      "},},],};",
      "const response = await Functions.makeHttpRequest({",
      "  url: emailURL,",
      "  method: 'POST',",
      "  headers: { 'Content-Type': 'application/json', 'Authorization': authHeader },",
      "  data: emailData",
      "});",
      "if (response.error) throw Error(`Failed to send email: ${JSON.stringify(response)}`);",
      "return Functions.encodeString('Email sent!');"
    );
    return formatEmailEnd;
  }

  //** Activated */
  // 1. To layer1
  // 2. To layer2

  function _sendEmailActivatedToBene(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    address[] memory listToken,
    uint256[] memory listAmount,
    string[] memory listAssetName,
    address contractAddress
  ) internal returns (bytes32 requestId) {
    string memory listAsset = "listAsset: [";
    for (uint256 i = 0; i < listToken.length; i++) {
      address tokenAddr = listToken[i];
      uint8 decimals = tokenAddr != address(0) ? ERC20(tokenAddr).decimals() : 18;
      listAsset = string.concat(
        listAsset,
        "    {assetAddr: '",
        Strings.toHexString(tokenAddr),
        "', amount: '",
        listAmount[i].format(decimals),
        "', assetName: '",
        listAssetName[i],
        "' }"
      );
      if (i < listToken.length - 1) {
        listAsset = string.concat(listAsset, ",");
      }
    }
    listAsset = string.concat(listAsset, "]");

    string memory subject = string.concat("[", contractName, "] Activated - You have Received Your Inheritance");

    string memory params = string.concat(
      " bene_name: '",
      beneName,
      "',  contract_name: '",
      contractName,
      "',",
      listAsset,
      ", contract_address: '",
      Strings.toHexString(contractAddress),
      "'"
    );

    string memory source = string.concat(_sendEmailToAddressBegin(beneEmail, subject, ACTIVATED_TO_BENE), params, _sendEmailToAddressEnd());

    return _sendRequest(source);
  }

  function _sendEmailActivatedToBeneWithRemaining(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    address[] memory listToken,
    uint256[] memory listAmount,
    string[] memory listAssetName,
    address contractAddress
  ) internal returns (bytes32 requestId) {
    string memory subject = string.concat("[", contractName, "] Activated with Remaining Funds - You have Received Partial Inheritance");
    string memory listAsset = "listAsset: [";
    for (uint256 i = 0; i < listToken.length; i++) {
      address tokenAddr = listToken[i];
      uint8 decimals = tokenAddr != address(0) ? ERC20(tokenAddr).decimals() : 18;
      listAsset = string.concat(
        listAsset,
        "    {assetAddr: '",
        Strings.toHexString(tokenAddr),
        "', amount: '",
        listAmount[i].format(decimals),
        "', assetName: '",
        listAssetName[i],
        "' }"
      );
      if (i < listToken.length - 1) {
        listAsset = string.concat(listAsset, ",");
      }
    }
    listAsset = string.concat(listAsset, "]");

    string memory params = string.concat(
      "  bene_name: '",
      beneName,
      "',  contract_name: '",
      contractName,
      "',",
      listAsset,
      ", contract_address: '",
      Strings.toHexString(contractAddress),
      "'"
    );
    string memory source = string.concat(
      _sendEmailToAddressBegin(beneEmail, subject, ACTIVATED_TO_BENE_WITH_REMAINING),
      params,
      _sendEmailToAddressEnd()
    );
    return _sendRequest(source);
  }

  //** Contract activated */ Same email
  // 1. To owner
  // 2. To layer1

  function _sendEmailContractActivatedToOwner(
    string memory toEmail,
    string memory contractName,
    address activatedByBene,
    uint256 timeActivated,
    address safeWallet,
    ListAsset[] memory _listAsset,
    BeneReceived[] memory _listBeneReceived,
    address contractAddress,
    bool remaining
  ) internal returns (bytes32 requestId) {
    uint8 [] memory decimals = new uint8[](_listAsset.length); 
    string memory listAsset = "listAsset: [";
    for (uint256 i = 0; i < _listAsset.length; i++) {
      address tokenAddr = _listAsset[i].listToken;
      decimals[i] = _listAsset[i].listToken != address(0) ? ERC20(tokenAddr).decimals() : 18;
      listAsset = string.concat(
        listAsset,
        "    {assetAddr: '",
        Strings.toHexString(tokenAddr),
        "', amount: '",
        _listAsset[i].listAmount.format(decimals[i]),
        "', assetName: '",
        _listAsset[i].listAssetName,
        "' }"
      );
      if (i < _listAsset.length - 1) {
        listAsset = string.concat(listAsset, ",");
      }
    }
    listAsset = string.concat(listAsset, "]");

    string memory listBeneReceived = "listBeneficiaries: [";
    for (uint256 i = 0; i < _listBeneReceived.length; i++) {
      listBeneReceived = string.concat(
        listBeneReceived,
        "    {beneName: '",
        _listBeneReceived[i].name,
        "', beneAddr: '",
        Strings.toHexString(_listBeneReceived[i].beneAddress),
        "', amounts: '"
      );

      string memory listAssetAmount = "";
      for (uint256 j = 0; j < _listBeneReceived[i].listAmount.length; j++) {
        listAssetAmount = string.concat(
          listAssetAmount,
          (_listBeneReceived[i].listAmount[j]).format(decimals[j]),
          " ",
          _listBeneReceived[i].listAssetName[j],
          " "
        );
        if (j < _listBeneReceived[i].listAmount.length - 1) {
          listAssetAmount = string.concat(listAssetAmount, ",");
        }
      }
      listAssetAmount = string.concat(listAssetAmount, "' }");
      if (i < _listBeneReceived.length - 1) {
        listAssetAmount = string.concat(listAssetAmount, ",");
      }
      listBeneReceived = string.concat(listBeneReceived, listAssetAmount);
    }
    listBeneReceived = string.concat(listBeneReceived, "]");

    string memory subject = string.concat("[", contractName, "] Was Activated");

    string memory params = string.concat(
      " bene_addr: '",
      Strings.toHexString(activatedByBene),
      "',  contract_name: '",
      contractName,
      "',  active_date: new Date(",
      Strings.toString(timeActivated * 1000),
      "), safe_wallet: '",
      Strings.toHexString(safeWallet),
      "',",
      listAsset,
      ",",
      listBeneReceived,
      ", contract_address: '",
      Strings.toHexString(contractAddress),
      "', remaining: '",
      remaining ? "true'" : "false'"
    );

    string memory source = string.concat(_sendEmailToAddressBegin(toEmail, subject, CONTRACT_ACTIVATED_TO_OWNER), params, _sendEmailToAddressEnd());
    return _sendRequest(source);
  }

  function _sendActivatedMutisig(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    address safeWallet
  ) internal returns (bytes32) {
    string memory subject = string.concat("You Have Been Added as a Co-Signer to the Safe Wallet for ", contractName);
    string memory params = string.concat(
      "bene_name: '",
      beneName,
      "', contract_name: '",
      contractName,
      "', safe_address: '",
      Strings.toHexString(safeWallet),
      "'"
    );
    string memory source = string.concat(_sendEmailToAddressBegin(beneEmail, subject, ACTIVATED_MULTISIG), params, _sendEmailToAddressEnd());
    return _sendRequest(source);
  }

  function _sendEmailOwnerResetToBene(string memory beneName, string memory beneEmail, string memory contractName) internal returns (bytes32) {
    string memory subject = string.concat("The activation timeline of [", contractName, "] has been reset");
    string memory params = string.concat("bene_name: '", beneName, "', contract_name: '", contractName, "'");
    string memory source = string.concat(_sendEmailToAddressBegin(beneEmail, subject, OWNER_RESET_TO_BENE), params, _sendEmailToAddressEnd());
    return _sendRequest(source);
  }

  function _sendRequest(string memory source) internal returns (bytes32) {
    FunctionsRequest.Request memory req;
    req.initializeRequestForInlineJavaScript(source);
    s_lastRequestId = IFunctionsRouter(router).sendRequest(subscriptionId, req.encodeCBOR(), FunctionsRequest.REQUEST_DATA_VERSION, gasLimit, donID);
    return s_lastRequestId;
  }

  function _emitSendMail(string memory to, NotifyLib.NotifyType notifyType) internal {
    mailId++;
    emit SendMail(to, notifyType);
  }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@chainlink/contracts/src/v0.8/functions/v1_0_0/interfaces/IFunctionsRouter.sol";
import {FunctionsRequest} from "@chainlink/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsRequest.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "../libraries/NotifyLib.sol";

contract PremiumMailReadyToActivate is OwnableUpgradeable {
  using FunctionsRequest for FunctionsRequest.Request;
  //CHAINLINK FUNCTION
  address public router = 0xb83E47C2bC239B3bf370bc41e1459A34b41238D0;
  bytes32 public donID = 0x66756e2d657468657265756d2d7365706f6c69612d3100000000000000000000;
  uint64 public subscriptionId;

  //PREMIUM CONTRACT
  address public sendMailRouter; // the only contract can call send email

  //MAIL SERVICE
  string private constant authHeader = "OGNlYWI2NGFmZTExNWRiYWJiMThhNGQzODAzYjE3OTI6ZDRlMDRjMmU1MTdmNWQzMjA4NjhiYmI3OTQ4ZTZiMzk=";

  // State variables
  bytes32 public s_lastRequestId;
  bytes public s_lastResponse;
  bytes public s_lastError;
  uint256 public mailId;

  //Callback gas limit
  uint32 public gasLimit = 300000;

  uint256 constant READY_TO_ACTIVATE_TO_BENE = 7180118;

  uint256 constant READY_TO_ACTIVATE_LAYER2_TO_LAYER1 = 7180042;
  uint256 constant READY_TO_ACTIVATE_LAYER2_TO_LAYER2 = 7180010;

  uint256 constant READY_TO_ACTIVATE_LAYER3_TO_LAYER3 = 7179981;
  uint256 constant READY_TO_ACTIVATE_LAYER3_TO_LAYER12 = 7190049;

  // Custom error type
  error UnexpectedRequestID(bytes32 requestId);
  error OnlyRouterCanFulfill();

  // Event to log responses
  event Response(bytes32 indexed requestId, bytes response, bytes err);
  event RequestSent(bytes32 indexed id);
  event RequestFulfilled(bytes32 indexed id);

  event SendMail(string to, NotifyLib.NotifyType notifyType);

  modifier onlyRouter() {
    require(msg.sender == sendMailRouter, "Only router");
    _;
  }

  function initialize(address _router, uint64 _subscriptionId, bytes32 _donId, uint32 _gasLimit, address _sendMailRouter) public initializer {
    router = _router;
    subscriptionId = _subscriptionId;
    donID = _donId;
    gasLimit = _gasLimit;
    sendMailRouter = _sendMailRouter;
    __Ownable_init(msg.sender);
  }

  /**
   * @notice Callback function for fulfilling a request
   * @param requestId The ID of the request to fulfill
   * @param response The HTTP response data
   * @param err Any errors from the Functions request
   */
  function fulfillRequest(bytes32 requestId, bytes memory response, bytes memory err) internal {
    if (s_lastRequestId != requestId) {
      revert UnexpectedRequestID(requestId); // Check if request IDs match
    }
    // Update the contract's state variables with the response and any errors
    s_lastResponse = response;
    s_lastError = err;

    // Emit an event to log the response
    emit Response(requestId, s_lastResponse, s_lastError);
  }

  function handleOracleFulfillment(bytes32 requestId, bytes memory response, bytes memory err) external {
    require(msg.sender == router, "Only router can fulfill");
    fulfillRequest(requestId, response, err);
    emit RequestFulfilled(requestId);
  }

  function sendEmailReadyToActivateToLayer1(string[] memory beneName, string[] memory beneEmail, string memory contractName) external onlyRouter {
    for (uint256 i = 0; i < beneName.length; i++) {
      if (bytes(beneEmail[i]).length > 0) {
        _sendEmailReadyToActivateToLayer1(beneName[i], beneEmail[i], contractName);
        _emitSendMail(beneEmail[i], NotifyLib.NotifyType.ReadyToActivate);
      }
    }
  }

  function sendEmailReadyToActivateLayer2ToLayer1(
    string[] memory beneNameLayer1,
    string[] memory beneEmailLayer1,
    address beneAddressLayer2,
    string memory contractName,
    uint256 timeActiveLayer2
  ) external onlyRouter {
    for (uint256 i = 0; i < beneNameLayer1.length; i++) {
      if (bytes(beneEmailLayer1[i]).length > 0) {
        _sendEmailReadyToActivateLayer2ToLayer1(beneNameLayer1[i], beneEmailLayer1[i], beneAddressLayer2, contractName, timeActiveLayer2);
        _emitSendMail(beneEmailLayer1[i], NotifyLib.NotifyType.Layer2ReadyToActivate);
      }
    }
  }

  function sendEmailReadyToActivateLayer2ToLayer2(
    string memory beneName,
    string memory beneEmail,
    string memory contractName
  ) external onlyRouter returns (bytes32 requestId) {
    string memory subject = string.concat("You May Now Activate the [", contractName, "]");
    string memory params = string.concat("bene_name: '", beneName, "', contract_name: '", contractName, "'");
    string memory source = string.concat(
      _sendEmailToAddressBegin(beneEmail, subject, READY_TO_ACTIVATE_LAYER2_TO_LAYER2),
      params,
      _sendEmailToAddressEnd()
    );
    return _sendRequest(source);
  }

  function sendEmailReadyToActivateLayer3ToLayer12(
    string[] memory beneNames,
    string[] memory beneEmails,
    string memory contractName,
    uint256 activationDate,
    address layer3Addr
  ) external onlyRouter {
    for (uint256 i = 0; i < beneNames.length; i++) {
      if (bytes(beneEmails[i]).length > 0) {
        _sendEmailReadyToActivateLayer3ToLayer12(beneNames[i], beneEmails[i], contractName, activationDate, layer3Addr);
        _emitSendMail(beneEmails[i], NotifyLib.NotifyType.Layer3ReadyToActivate);
      }
    }
  }
  function sendEmailReadyToActivateLayer3ToLayer3(
    string memory beneName,
    string memory beneEmail,
    string memory contractName
  ) external onlyRouter returns (bytes32 requestId) {
    string memory subject = string.concat("You May Now Activate the [", contractName, "]");
    string memory params = string.concat("bene_name: '", beneName, "', contract_name: '", contractName, "'");
    string memory source = string.concat(
      _sendEmailToAddressBegin(beneEmail, subject, READY_TO_ACTIVATE_LAYER3_TO_LAYER3),
      params,
      _sendEmailToAddressEnd()
    );
    _emitSendMail(beneEmail, NotifyLib.NotifyType.Layer3ReadyToActivate);
    return _sendRequest(source);
  }

  // common function
  function _sendEmailToAddressBegin(string memory to, string memory subject, uint256 templateId) private pure returns (string memory) {
    string memory formatEmailTo = string.concat(
      "const emailURL = 'https://api.mailjet.com/v3.1/send';",
      "const authHeader = 'Basic ",
      authHeader,
      "';",
      "const emailData = { Messages: ",
      "[ { From: {Email: '[email protected]', Name: '10102 Platform',},",
      "To: [ {Email: '",
      to,
      "', Name:'',},],",
      "TemplateID: ",
      Strings.toString(templateId),
      ", TemplateLanguage: true,",
      "Subject: '",
      subject,
      "',",
      "Variables: {"
    );
    return formatEmailTo;
  }

  function _sendEmailToAddressEnd() private pure returns (string memory) {
    string memory formatEmailEnd = string.concat(
      "},},],};",
      "const response = await Functions.makeHttpRequest({",
      "  url: emailURL,",
      "  method: 'POST',",
      "  headers: { 'Content-Type': 'application/json', 'Authorization': authHeader },",
      "  data: emailData",
      "});",
      "if (response.error) throw Error(`Failed to send email: ${JSON.stringify(response)}`);",
      "return Functions.encodeString('Email sent!');"
    );
    return formatEmailEnd;
  }

  /**Ready to activate */
  function _sendEmailReadyToActivateToLayer1(
    string memory beneName,
    string memory beneEmail,
    string memory contractName
  ) internal returns (bytes32 requestId) {
    string memory subject = string.concat("[", contractName, "] Is Ready to Activate");
    string memory params = string.concat("bene_name: '", beneName, "',  contract_name: '", contractName, "'");
    string memory source = string.concat(_sendEmailToAddressBegin(beneEmail, subject, READY_TO_ACTIVATE_TO_BENE), params, _sendEmailToAddressEnd());
    return _sendRequest(source);
  }

  function _sendEmailReadyToActivateLayer2ToLayer1(
    string memory beneNameLayer1,
    string memory beneEmailLayer1,
    address beneAddressLayer2,
    string memory contractName,
    uint256 timeActiveLayer2
  ) internal returns (bytes32 requestId) {
    string memory subject = string.concat("[", contractName, "] Is Ready");

    string memory params = string.concat(
      "bene_name: '",
      beneNameLayer1,
      "',",
      "    contract_name: '",
      contractName,
      "',",
      "    date: new Date(",
      Strings.toString(timeActiveLayer2*1000), //unixtimestamp in miliseconds
      "), address: '",
      Strings.toHexString(beneAddressLayer2),
      "'"
    );

    string memory source = string.concat(
      _sendEmailToAddressBegin(beneEmailLayer1, subject, READY_TO_ACTIVATE_LAYER2_TO_LAYER1),
      params,
      _sendEmailToAddressEnd()
    );

    return _sendRequest(source);
  }

  function _sendEmailReadyToActivateLayer3ToLayer12(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    uint256 activationDate,
    address layer3Addr
  ) internal returns (bytes32 requestId) {
    string memory subject = string.concat('"', contractName, '" Is Ready');

    string memory activationDateStr = Strings.toString(activationDate*1000); //unix timestamp in miliseconds
    string memory layer3AddrStr = Strings.toHexString(layer3Addr);

    string memory params = string.concat(
      "bene_name: '",
      beneName,
      "', contract_name: '",
      contractName,
      "', activation_date: new Date(",
      activationDateStr,
      "), new_bene: '",
      layer3AddrStr,
      "'"
    );

    string memory source = string.concat(
      _sendEmailToAddressBegin(beneEmail, subject, READY_TO_ACTIVATE_LAYER3_TO_LAYER12),
      params,
      _sendEmailToAddressEnd()
    );

    return _sendRequest(source);
  }

  function _sendRequest(string memory source) internal returns (bytes32) {
    FunctionsRequest.Request memory req;
    req.initializeRequestForInlineJavaScript(source);
    s_lastRequestId = IFunctionsRouter(router).sendRequest(subscriptionId, req.encodeCBOR(), FunctionsRequest.REQUEST_DATA_VERSION, gasLimit, donID);
    return s_lastRequestId;
  }

  function _emitSendMail(string memory to, NotifyLib.NotifyType notifyType) internal {
    mailId++;
    emit SendMail(to, notifyType);
  }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../interfaces/IPremiumLegacy.sol";
import "../interfaces/IPremiumSetting.sol";
import "../interfaces/IPremiumSendMail.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "../libraries/NotifyLib.sol";

contract PremiumMailRouter is OwnableUpgradeable {
  address public mailBeforeActivation;
  address public mailActivated;
  address public mailReadyToActivate;
  address public premiumSetting;
  address public automationManager;
  uint256 public mailId;

  modifier onlySetting() {
    require(msg.sender == premiumSetting || msg.sender == owner(), "Only setting");
    _;
  }

  modifier onlyManager() {
    require(msg.sender == automationManager || msg.sender == owner(), "Only automation manager");
    _;
  }

  function initialize() external initializer {
    __Ownable_init(msg.sender);
  }

  function setParams(
    address _mailBeforeActivation,
    address _mailActivated,
    address _mailReadyToActivate,
    address _premiumSetting,
    address _automationManager
  ) external onlyOwner {
    mailBeforeActivation = _mailBeforeActivation;
    mailActivated = _mailActivated;
    mailReadyToActivate = _mailReadyToActivate;
    premiumSetting = _premiumSetting;
    automationManager = _automationManager;
  }

  //BEFORE ACTIVATION
  function sendEmailBeforeActivationToOwner(
    string memory ownerName,
    string memory contractName,
    uint256 lastTx,
    uint256 bufferTime,
    address[] memory listBene,
    string memory ownerEmail
  ) external onlyManager {
    IPremiumSendMail(mailBeforeActivation).sendEmailBeforeActivationToOwner(ownerName, contractName, lastTx, bufferTime, listBene, ownerEmail);
    mailId++;
  }

  function sendEmailBeforeActivationToBeneficiary(
    string[] memory beneNames,
    string memory contractName,
    uint256 timeCountdown,
    string[] memory beneEmails
  ) external onlyManager {
    IPremiumSendMail(mailBeforeActivation).sendEmailBeforeActivationToBeneficiary(beneNames, contractName, timeCountdown, beneEmails);
    mailId += beneEmails.length;
  }

  function sendEmailBeforeLayer2ToLayer1(
    string[] memory beneNames,
    string[] memory beneEmails,
    string memory contractName,
    uint256 x_days
  ) external onlyManager {
    IPremiumSendMail(mailBeforeActivation).sendEmailBeforeLayer2ToLayer1(beneNames, beneEmails, contractName, x_days);
  }

  function sendEmailBeforeLayer2ToLayer2(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    uint256 x_days
  ) external onlyManager {
    IPremiumSendMail(mailBeforeActivation).sendEmailBeforeLayer2ToLayer2(beneName, beneEmail, contractName, x_days);
    mailId++;
  }

  function sendEmailBeforeLayer3ToLayer12(
    string[] memory beneNames,
    string[] memory beneEmails,
    string memory contractName,
    uint256 x_days
  ) external onlyManager {
    IPremiumSendMail(mailBeforeActivation).sendEmailBeforeLayer3ToLayer12(beneNames, beneEmails, contractName, x_days);
    mailId += beneEmails.length;
  }

  function sendEmailBeforeLayer3ToLayer3(
    string memory beneName,
    string memory beneEmail,
    string memory contractName,
    uint256 x_day
  ) external onlyManager {
    IPremiumSendMail(mailBeforeActivation).sendEmailBeforeLayer3ToLayer3(beneName, beneEmail, contractName, x_day);
    mailId++;
  }

  //READY TO ACTIVATE
  function sendEmailReadyToActivateToLayer1(string[] memory beneNames, string[] memory beneEmails, string memory contractName) external onlyManager {
    IPremiumSendMail(mailReadyToActivate).sendEmailReadyToActivateToLayer1(beneNames, beneEmails, contractName);
  }

  function sendEmailReadyToActivateLayer2ToLayer1(
    string[] memory beneNamesLayer1,
    string[] memory beneEmailsLayer1,
    address beneAddressLayer2,
    string memory contractName,
    uint256 timeActiveLayer2
  ) external onlyManager {
    IPremiumSendMail(mailReadyToActivate).sendEmailReadyToActivateLayer2ToLayer1(
      beneNamesLayer1,
      beneEmailsLayer1,
      beneAddressLayer2,
      contractName,
      timeActiveLayer2
    );
    mailId += beneEmailsLayer1.length;
  }

  function sendEmailReadyToActivateLayer2ToLayer2(string memory beneName, string memory beneEmail, string memory contractName) external onlyManager {
    IPremiumSendMail(mailReadyToActivate).sendEmailReadyToActivateLayer2ToLayer2(beneName, beneEmail, contractName);
  }

  function sendEmailReadyToActivateLayer3ToLayer12(
    string[] memory beneNames,
    string[] memory beneEmails,
    string memory contractName,
    uint256 activationDate,
    address layer3Addr
  ) external onlyManager {
    IPremiumSendMail(mailReadyToActivate).sendEmailReadyToActivateLayer3ToLayer12(beneNames, beneEmails, contractName, activationDate, layer3Addr);
    mailId += beneEmails.length;
  }

  function sendEmailReadyToActivateLayer3ToLayer3(string memory beneName, string memory beneEmail, string memory contractName) external onlyManager {
    IPremiumSendMail(mailReadyToActivate).sendEmailReadyToActivateLayer3ToLayer3(beneName, beneEmail, contractName);
    mailId++;
  }

  //ACTIVATED
  function sendMailActivatedMultisig(
    string[] memory beneNames,
    string[] memory beneEmails,
    string memory contractName,
    address safeWallet
  ) external onlySetting {
    IPremiumSendMail(mailActivated).sendMailActivatedMultisig(beneNames, beneEmails, contractName, safeWallet);
    mailId += beneEmails.length;
  }

  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 onlySetting {
    IPremiumSendMail(mailActivated).sendEmailContractActivatedToOwner(
      toEmail,
      contractName,
      activatedByBene,
      timeActivated,
      safeWallet,
      _listAsset,
      _listBeneReceived,
      contractAddress,
      remaining
    );
    mailId++;
  }

  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 onlySetting {
   
    IPremiumSendMail(mailActivated).sendEmailActivatedToBene(
      beneName,
      beneEmail,
      contractName,
      listToken,
      listAmount,
      listAssetName,
      contractAddress,
      remaining
    );
    mailId++;
  }

  function sendMailOwnerResetToBene(string[] memory beneNames, string[] memory beneEmails, string memory contractName) external onlySetting {
    IPremiumSendMail(mailActivated).sendMailOwnerResetToBene(beneNames, beneEmails, contractName);
    mailId += beneEmails.length;
  }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {AutomationCompatibleInterface} from "@chainlink/contracts/src/v0.8/automation/interfaces/AutomationCompatibleInterface.sol";
import "@chainlink/contracts/src/v0.8/functions/v1_0_0/interfaces/IFunctionsRouter.sol";
import {FunctionsRequest} from "@chainlink/contracts/src/v0.8/functions/v1_0_0/libraries/FunctionsRequest.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "../interfaces/ISafeWallet.sol";
import "../interfaces/IPremiumLegacy.sol";
import {NotifyLib} from "../libraries/NotifyLib.sol";

// PUSH Comm Contract Interface
interface IPUSHCommInterface {
  function sendNotification(address _channel, address _recipient, bytes calldata _identity) external;
}

contract PremiumNotification is OwnableUpgradeable, AutomationCompatibleInterface {
  using FunctionsRequest for FunctionsRequest.Request;
  address public EPNS_COMM_ADDRESS = 0x0C34d54a09CFe75BCcd878A469206Ae77E0fe6e7; //fixed for Sepolia
  address public channel;
  address public enps_comm;

  //CHAINLINK FUNCTION
  // Router address - Hardcoded for Sepolia
  // Check to get the router address for your supported network https://docs.chain.link/chainlink-functions/supported-networks
  address public router = 0xb83E47C2bC239B3bf370bc41e1459A34b41238D0;
  // State variables to store the last request ID, response, and error
  bytes32 public s_lastRequestId;
  bytes public s_lastResponse;
  bytes public s_lastError;
  //Callback gas limit
  uint32 public gasLimit = 300000;

  // donID - Hardcoded for Sepolia
  // Check to get the donID for your supported network https://docs.chain.link/chainlink-functions/supported-networks
  bytes32 public donID = 0x66756e2d657468657265756d2d7365706f6c69612d3100000000000000000000;
  uint64 public subscriptionId;

  //Premium - call send push notification
  address public manager;
  address public premiumSetting;

  uint256 public notifyId; 

  address  [] public queueRecipient;
  bytes  [] public queuePayload;
  uint256 public indexNotifying; 

  event NotificationSent(
    address indexed legacy,
    NotifyLib.NotifyType notifyType,
    NotifyLib.RecipientType recipientType,
    address[] recipients,
    string body,
    uint256  notifyId
  );

  event Sent(address recipient, string title, string body, uint256 notifyId );

  //modifier
  modifier onlyManager() {
    require(msg.sender == manager || msg.sender == owner(), "Premium Notification: Only manager!");
    _;
  }

  modifier onlySetting() {
    require(msg.sender == premiumSetting || msg.sender == owner(), "Premium Notification: Only setting!");
    _;
  }

  function initialize() public initializer {
    __Ownable_init(msg.sender);
  }

  function setUpPush(address _enpsComm, address _channel, address _manager, address _premiumSetting) external onlyOwner {
    require(_enpsComm != address(0), "invalid address");
    require(_channel != address(0), "invalid address");
    require(_manager != address(0), "invalid address");

    channel = _channel;
    enps_comm = _enpsComm;
    manager = _manager;
    premiumSetting = _premiumSetting;
  }

  function sendPushNoti(address[] memory recipients, string calldata title, string calldata notification) external onlyOwner {
    _sendPushNotification(recipients, title, notification);
  }
  

  function notifyTransferActivation(uint8 layer, address legacy, string calldata contractName, bool remaining) external onlySetting {
    // send PUSH Protocol
    address creator = IPremiumLegacy(legacy).creator();
    string memory body ;
    if (!remaining) {
      body =  string.concat("You 've receive your inheritance from ", contractName, ".");
    }
    else {
      body =  string.concat("You 've receive part of your inheritance from ", contractName, ".");
    }
    
    (address[] memory beneficiaries, address layer2, address layer3) = IPremiumLegacy(legacy).getLegacyBeneficiaries();
    _sendIfNotEmpty(legacy, NotifyLib.NotifyType.ContractActivated, NotifyLib.RecipientType.Owner, _makeArray(creator));
    if (layer == 1) {
      _sendPushNotification(beneficiaries, contractName, body);
    } else if (layer == 2) {
      _sendPushNotification(_makeArray(layer2), contractName, body);
    } else if (layer == 3) {
      _sendPushNotification(_makeArray(layer3), contractName, body);
    }
  }

  function notifyMultisigActivation(address legacy) external onlySetting {
    (address[] memory beneficiaries,,) = IPremiumLegacy(legacy).getLegacyBeneficiaries();
    _sendIfNotEmpty(legacy, NotifyLib.NotifyType.ContractActivated, NotifyLib.RecipientType.Beneficiary, beneficiaries);
  }

  function notifyOwnerReset(address legacy) external onlySetting {
    uint8 layer = IPremiumLegacy(legacy).getLayer();
    (address[] memory beneficiaries, address layer2, address layer3) = IPremiumLegacy(legacy).getLegacyBeneficiaries();
    _sendIfNotEmpty(legacy, NotifyLib.NotifyType.OwnerReset, NotifyLib.RecipientType.Beneficiary, beneficiaries);
    if (layer >= 2) {
      _sendIfNotEmpty(legacy, NotifyLib.NotifyType.OwnerReset, NotifyLib.RecipientType.Secondline, _makeArray(layer2));
    }
    if (layer == 3) {
      _sendIfNotEmpty(legacy, NotifyLib.NotifyType.OwnerReset, NotifyLib.RecipientType.Thirdline, _makeArray(layer3));
    }
  }

  function handleLegacyNotify(address legacy, NotifyLib.NotifyType notifyType) external onlyManager {
    //send push notification
    //send email
    //prepare recipient
    (address[] memory beneficiaries, address layer2, address layer3) = IPremiumLegacy(legacy).getLegacyBeneficiaries();
    address creator = IPremiumLegacy(legacy).creator();
    address owner = IPremiumLegacy(legacy).getLegacyOwner();
    address[] memory owners; // owner and cosigner

    if (owner.code.length > 0) {
      owners = new address[](ISafeWallet(owner).getOwners().length);
      owners = ISafeWallet(owner).getOwners();
    } else {
      owners = new address[](1);
      owners[0] = creator;
    }

    // Send notifications if body is not empty
    _sendIfNotEmpty(legacy, notifyType, NotifyLib.RecipientType.Owner, owners);
    _sendIfNotEmpty(legacy, notifyType, NotifyLib.RecipientType.Beneficiary, beneficiaries);

    // // layer2 & layer3 wrapped in single-address arrays
    if (layer2 != address(0)) {
      _sendIfNotEmpty(legacy, notifyType, NotifyLib.RecipientType.Secondline, _makeArray(layer2));
    }

    if (layer3 != address(0)) {
      _sendIfNotEmpty(legacy, notifyType, NotifyLib.RecipientType.Thirdline, _makeArray(layer3));
    }
  }

  ///@dev send notification if body is not empty - define in NotifyLib.sol
  function _sendIfNotEmpty(
    address legacy,
    NotifyLib.NotifyType notifyType,
    NotifyLib.RecipientType recipientType,
    address[] memory recipients
  ) internal {
    string memory body = _getBody(legacy, notifyType, recipientType);
    string memory title = IPremiumLegacy(legacy).getLegacyName();
    if (bytes(body).length != 0) {
      _sendPushNotification(recipients, title, body);
      // emit NotificationSent(legacy, notifyType, recipientType, recipients, body, notifyId);
    }
  }

  //queue noti
  function _sendPushNotification(address[] memory recipients, string memory title, string memory body) internal {
    for (uint i = 0; i < recipients.length; i++) {
      queueRecipient.push(recipients[i]);
      queuePayload.push(_getPayload(title, body));
      emit Sent(recipients[i], title, body, notifyId);
    }
  }

  function _getPayload(string memory title, string memory body) internal returns (bytes memory) {
    bytes memory payload = bytes(
      string(
        // We are passing identity here: https://docs.epns.io/developers/developer-guides/sending-notifications/advanced/notification-payload-types/identity/payload-identity-implementations
        abi.encodePacked(
          "0", // this is notification identity: https://docs.epns.io/developers/developer-guides/sending-notifications/advanced/notification-payload-types/identity/payload-identity-implementations
          "+", // segregator
          "3", // this is payload type: https://docs.epns.io/developers/developer-guides/sending-notifications/advanced/notification-payload-types/payload (1, 3 or 4) = (Broadcast, targeted or subset)
          "+", // segregator
          title, // this is notification title
          "+", // segregator
          body // notification body
        )
      )
    );
    notifyId++;
    return payload;
  }

  function _getBody(address legacy, NotifyLib.NotifyType notifyType, NotifyLib.RecipientType recipient) internal view returns (string memory) {
    (uint256 triggerTimestamp, , ) = IPremiumLegacy(legacy).getTriggerActivationTimestamp();

    uint256 secondsUntilActivation = triggerTimestamp > block.timestamp ? triggerTimestamp - block.timestamp : 0;
    string memory contractName = IPremiumLegacy(legacy).getLegacyName(); // legacy contract must store legacy name
    string memory daysStr = _days(secondsUntilActivation);

    if (recipient == NotifyLib.RecipientType.Owner) {
      if (notifyType == NotifyLib.NotifyType.BeforeActivation) {
        return string.concat("Your contract ", contractName, " activates in ", daysStr, ". Mark yourself alive to delay activation.");
      }
      if (notifyType == NotifyLib.NotifyType.ContractActivated) {
        return string.concat(contractName, " has been activated.");
      }
    }

    if (recipient == NotifyLib.RecipientType.Beneficiary) {
      if (notifyType == NotifyLib.NotifyType.BeforeActivation) {
        return
          string.concat(
            daysStr,
            " until ",
            contractName,
            " can be activated. You will be able to claim your inheritance soon."
          );
      }
      if (notifyType == NotifyLib.NotifyType.ReadyToActivate) {
        return string.concat(contractName, " is ready to activate. Connect your wallet to activate and claim the funds. Gas fees apply.");
      }
      if (notifyType == NotifyLib.NotifyType.ContractActivated) {
        if (IPremiumLegacy(legacy).LEGACY_TYPE() == 1) {
          // multisig
          return
            string.concat(
              " You're now a co-signer on the Safe Wallet for ",
              contractName,
              ". You can approve or initiate transactions using Safe."
            );
        } else {
          return string.concat("You've received your inheritance from ", contractName, ".");
        }
      }
      if (notifyType == NotifyLib.NotifyType.BeforeLayer2) {
        return
          string.concat(
            daysStr,
            " left to activate ",
            contractName,
            ". After that, the second-line beneficiary will be able to claim the inheritance. Activate now."
          );
      }
      if (notifyType == NotifyLib.NotifyType.Layer2ReadyToActivate) {
        return
          string.concat(
            "The second-line activation for contract ",
            contractName,
            " is in effect, and the second-line beneficiary will be able to claim the funds."
          );
      }

      if (notifyType == NotifyLib.NotifyType.Layer3ReadyToActivate) {
        return
          string.concat(
            "The third-line activation for contract ",
            contractName,
            " is in effect, and the third-line beneficiary will be able to claim the funds."
          );
      }

      if (notifyType == NotifyLib.NotifyType.OwnerReset) {
        return
          string.concat(
            "The activation timeline of ",
            contractName,
            " has been reset by the owner. We will notify you later when it's time to activate."
          );
      }
    }

    if (recipient == NotifyLib.RecipientType.Secondline) {
      if (notifyType == NotifyLib.NotifyType.BeforeLayer2) {
        return
          string.concat(
            "You may be eligible to activate ",
            contractName,
            " in ",
            daysStr,
            ", pending first-line's inaction. Stay tuned for the activation link."
          );
      }

      if (notifyType == NotifyLib.NotifyType.Layer2ReadyToActivate) {
        return string.concat(contractName, " is ready to activate. Connect your wallet to activate and claim the funds. Gas fees apply.");
      }

      if (notifyType == NotifyLib.NotifyType.ContractActivated) {
        return string.concat("You 've receive your inheritance from ", contractName, ".");
      }

      if (notifyType == NotifyLib.NotifyType.BeforeLayer3) {
        return
          string.concat(
            daysStr,
            " left to activate ",
            contractName,
            ". After that, the third-line beneficiary can claim the inheritance. Activate now."
          );
      }

      if (notifyType == NotifyLib.NotifyType.Layer3ReadyToActivate) {
        return
          string.concat(
            "The third-line activation for contract ",
            contractName,
            " is in effect. and the third-line beneficiary will be able to claim the funds."
          );
      }

      if (notifyType == NotifyLib.NotifyType.OwnerReset) {
        return
          string.concat(
            "The activation timeline of ",
            contractName,
            " has been reset by the owner. We will notify you later when it's time to activate."
          );
      }
    }

    if (recipient == NotifyLib.RecipientType.Thirdline) {
      if (notifyType == NotifyLib.NotifyType.BeforeLayer3) {
        return
          string.concat(
            "You may be eligible to activate ",
            contractName,
            " in ",
            daysStr,
            ", pending second-line's inaction. Stay tuned for the activation link."
          );
      }
      if (notifyType == NotifyLib.NotifyType.Layer3ReadyToActivate) {
        return string.concat(contractName, " is ready to activate. Connect your wallet to activate and claim the funds. Gas fees apply.");
      }
      if (notifyType == NotifyLib.NotifyType.OwnerReset) {
        return
          string.concat(
            "The activation timeline of ",
            contractName,
            " has been reset by the owner. We will notify you later when it's time to activate."
          );
      }

      if (notifyType == NotifyLib.NotifyType.ContractActivated) {
        return string.concat("You 've receive your inheritance from ", contractName, ".");
      }
    }

    return "";
  }

  function _days(uint256 secondsTime) internal pure returns (string memory) {
    uint256 daysTime = secondsTime / 86400;
    return string(abi.encodePacked(Strings.toString(daysTime), " day", daysTime <= 1 ? "" : "s"));
  }

  function _makeArray(address addr) internal pure returns (address[] memory) {
    address[] memory arr = new address[](1);
    arr[0] = addr;
    return arr;
  }

  function checkUpkeep(bytes calldata checkData) external override view returns (bool upkeepNeeded, bytes memory performData) {
    if(indexNotifying < queueRecipient.length) return (true, "0x");
  }

  function performUpkeep(bytes calldata performData) external override {
    IPUSHCommInterface(enps_comm).sendNotification(
        channel,
        queueRecipient[indexNotifying], // to recipient, put address(this) in case you want Broadcast or Subset. For Targetted put the address to which you want to send
        queuePayload[indexNotifying]
    );
    indexNotifying++;

  }
}

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

import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../interfaces/IPremiumSetting.sol";

contract PremiumRegistry is OwnableUpgradeable, AccessControlUpgradeable {
  struct PremiumPlan {
    uint256 usdPrice; //x100 (two digits after the decimal point)
    uint256 duration;
    bool isActive; // false if plan is removed - Soft delete
  }

  ERC20 public usdt;
  ERC20 public usdc;

  AggregatorV3Interface public usdtUsdPriceFeed;
  AggregatorV3Interface public usdcUsdPriceFeed;
  AggregatorV3Interface public ethUsdPriceFeed;

  IPremiumSetting public premiumSetting;

  bytes32 public constant DEPOSITOR = keccak256("DEPOSITOR"); // deposit LINK to this contract
  bytes32 public constant OPERATOR = keccak256("OPERATOR");

  PremiumPlan[] public premiumPlans;

  address public payment;

  /* EVENTS */
  event PlanUpdated(uint256 plan, uint256 priceUSD, uint256 duration, string name, string description, string feature);
  event PlanSubcribed(address indexed user, uint256 plan, string paymentMethod, uint256 value);
  event PlanRemoved(uint256 plan);
  event PlanPriceDurationUpdated(uint256 plan, uint256 priceUSD, uint256 duration);

  /* MODIFIERS */
  modifier requirePrice(uint256 plan) {
    require(premiumPlans[plan].usdPrice > 0, "Price has not been set yet");
    _;
  }

  modifier requireDuration(uint256 plan) {
    require(premiumPlans[plan].duration > 0, "Duration has not been set yet");
    _;
  }

  modifier requireActive(uint256 plan) {
    require(premiumPlans[plan].isActive, "Plan has been removed");
    _;
  }

  function initialize(
    address _usdt,
    address _usdc,
    address _usdtUsdPriceFeed,
    address _usdcUsdPriceFeed,
    address _ethUsdPriceFeed,
    address _premiumSetting,
    address _payment
  ) public initializer {
    __Ownable_init(msg.sender);
    __AccessControl_init();
    _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    _grantRole(OPERATOR, msg.sender);
    require(_usdt != address(0), "invalid _usdt");
    require(_usdc != address(0), "invalid _usdc");
    require(_usdtUsdPriceFeed != address(0), "invalid _usdtUsdPriceFeed");
    require(_usdcUsdPriceFeed != address(0), "invalid _usdcUsdPriceFeed");
    require(_ethUsdPriceFeed != address(0), "invalid _ethUsdPriceFeed");
    require(_premiumSetting != address(0), "invalid _premiumSetting");
    require(_payment != address(0), "invalid _payment");

    usdt = ERC20(_usdt);
    usdc = ERC20(_usdc);

    usdtUsdPriceFeed = AggregatorV3Interface(_usdtUsdPriceFeed);
    usdcUsdPriceFeed = AggregatorV3Interface(_usdcUsdPriceFeed);
    ethUsdPriceFeed = AggregatorV3Interface(_ethUsdPriceFeed);

    premiumSetting = IPremiumSetting(_premiumSetting);
    payment = _payment;
  }



  /*ADMIN FUNCTION */
  function createPlans(
    uint256[] calldata durations,
    uint256[] calldata prices,
    string[] calldata names,
    string[] calldata descriptions,
    string[] calldata features
  ) external onlyRole(OPERATOR) {
    require(
      prices.length == durations.length 
      && durations.length == names.length 
      && names.length == descriptions.length
      && descriptions.length == features.length, "Length mismatch");

    for (uint256 i = 0; i < prices.length; i++) {
      require(prices[i] > 0, "Price must be > 0");
      require(durations[i] > 0, "Duration must be > 0");
      premiumPlans.push(PremiumPlan(prices[i], durations[i], true));
      emit PlanUpdated(premiumPlans.length-1, prices[i], durations[i], names[i], descriptions[i], features[i]);
    }
  }

  function updatePlans(
    uint256[] calldata plans,
    uint256[] calldata durations,
    uint256[] calldata prices,
    string[] calldata names,
    string[] calldata descriptions,
    string[] calldata features 
  ) external onlyRole(OPERATOR) {
    require( 
      plans.length == prices.length 
      &&prices.length == durations.length 
      && durations.length == names.length 
      && names.length == descriptions.length
      && descriptions.length == features.length, "Length mismatch");
    for (uint256 i = 0; i < prices.length; i++) {
      _updatePlan(plans[i], durations[i], prices[i]);
      emit PlanUpdated(plans[i], prices[i], durations[i], names[i], descriptions[i], features[i]);
    }
  }

  function updatePlansPriceAndDuration(
      uint256[] calldata plans,
      uint256[] calldata durations,
      uint256[] calldata prices
  ) external onlyRole(OPERATOR) {
    require(  plans.length == prices.length 
      &&prices.length == durations.length, "Length mismatch");
    for(uint i = 0 ; i < plans.length; i++) {
        _updatePlan(plans[i], durations[i], prices[i]);
        emit PlanPriceDurationUpdated(plans[i], prices[i], durations[i]);
    } 
  }


  function removePlans(uint256[] calldata plans) external onlyRole(OPERATOR) {
    for(uint256 i = 0 ; i < plans.length ; i++) {
      _removePlan(plans[i]);
    }
  }

  ///@notice dev only - to set an account premium
  function subrcribeByAdmin(address user, uint256 plan, string memory method) external onlyRole(OPERATOR) {
    premiumSetting.updatePremiumTime(user, getPlanDuration(plan));
    emit PlanSubcribed(user, plan, method, 0); 
  }

  /* USER FUNCTIONS */
  function subcribeWithUSDT(uint256 plan) external {
    //calculate price in usdt
    uint256 usdtAmount = getPlanPriceUSDT(plan);

    //trasfer token
    usdt.transferFrom(msg.sender, payment, usdtAmount);

    //update plan
    premiumSetting.updatePremiumTime(msg.sender, getPlanDuration(plan));

    emit PlanSubcribed(msg.sender, plan, "USDT", usdtAmount);
  }

  function subcribeWithUSDC(uint256 plan) external {
    //calculate price in usdt
    uint256 usdcAmount = getPlanPriceUSDC(plan);

    //trasfer token
    usdc.transferFrom(msg.sender, payment, usdcAmount);

    //update plan
    premiumSetting.updatePremiumTime(msg.sender, getPlanDuration(plan));
    emit PlanSubcribed(msg.sender, plan, "USDC", usdcAmount);
  }

  function subcribeWithETH(uint256 plan) external payable {
    //calculate price in ETH
    uint256 ethAmount = getPlanPriceETH(plan);
    require(msg.value >= ethAmount, "Insufficient ETH");

    //refund if needed
    if (msg.value > ethAmount) {
      payable(msg.sender).transfer(msg.value - ethAmount);
    }

    //transfer to payment
    (bool success, ) = payment.call{value: ethAmount}("");
    require(success, "Purchase failed");

    emit PlanSubcribed(msg.sender, plan, "ETH", ethAmount);

    //update plan
    premiumSetting.updatePremiumTime(msg.sender, getPlanDuration(plan));
  }

  /*INTERNAL FUNCTIONS*/
  function _updatePlan(uint256 plan,  uint256 duration, uint256 price) internal requireActive(plan) {
    require(price > 0, "Price must be > 0");
    require(duration > 0, "Duration must be > 0");
    require(plan < premiumPlans.length, "Invalid plan");
    PremiumPlan storage _plan = premiumPlans[plan];
    _plan.usdPrice = price;
    _plan.duration = duration;
  }

  function _removePlan(uint256 plan) internal requireActive(plan) {
    premiumPlans[plan].isActive = false;
    emit PlanRemoved(plan);
  }

  /*VIEW FUNCTIONS*/

  function getPlanDuration(uint256 plan) public view requireDuration(plan) requireActive(plan) returns (uint256) {
    return premiumPlans[plan].duration;
  }

  function getPlanPriceUSD(uint256 plan) public view requirePrice(plan) requireActive(plan) returns (uint256) {
    return premiumPlans[plan].usdPrice;
  }

  ///@dev priceUSD * 10**8 to match Chainlink FeedPrice decimals, 
  // and then divided by 100 (two digits after the decimal point)
  function getPlanPriceUSDT(uint256 plan) public view requirePrice(plan) requireActive(plan) returns (uint256) {
    return (getPlanPriceUSD(plan) * 10 ** 6 * (10 ** 6)) / getUSDTPrice();
  }

  ///@dev priceUSD * 10**8 to match Chainlink FeedPrice decimals
  // and then divided by 100 (two digits after the decimal point)
  function getPlanPriceUSDC(uint256 plan) public view requirePrice(plan) requireActive(plan) returns (uint256) {
    return (getPlanPriceUSD(plan) * 10 ** 6 * (10 ** 6)) / getUSDCPrice();
  }

  ///@dev  priceUSD * 10**8 to match Chainlink FeedPrice decimals
  // and then divided by 100 (two digits after the decimal point)
  function getPlanPriceETH(uint256 plan) public view requirePrice(plan) requireActive(plan) returns (uint256) {
    return (getPlanPriceUSD(plan) * 10 ** 6 * (10 ** 18)) / getETHPrice();
  }

  function getUSDCPrice() public view returns (uint256) {
    (, int256 answer, , , ) = usdcUsdPriceFeed.latestRoundData();
    require(answer > 0, "Invalid price");
    return uint256(answer);
  }

  function getUSDTPrice() public view returns (uint256) {
    (, int256 answer, , , ) = usdtUsdPriceFeed.latestRoundData();
    require(answer > 0, "Invalid price");
    return uint256(answer);
  }

  function getETHPrice() public view returns (uint256) {
    (, int256 answer, , , ) = ethUsdPriceFeed.latestRoundData();
    require(answer > 0, "Invalid price");
    return uint256(answer);
  }

  function getNextPlanId() public view returns (uint256) {
    return premiumPlans.length;
  }
}

File 115 of 123 : PremiumSetting.sol
//SPDX-License-Identifier: MIT
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 {
  address public premiumRegistry; // contract serves for register premium package  & payment
  mapping(address => uint) public premiumExpired; // timestamp that premium package ends

  address public transferLegacyContractRouter;
  address public transferLegacyEOAContractRouter;

  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 => UserConfig) public userConfigs;
  mapping(address => LegacyConfig) public legacyConfigs; //UNUSED - keep here for proxy uprgade - remove in new deployment
  mapping(address => LegacyConfig) public legacyCfgs;
  mapping(uint256 => address) private legacyCodeToAddress;
  mapping(address => uint256) private legacyAddressToCode;

  address public multisigLegacyContractRouter;
  IPremiumAutomationManager public premiumAutomationManager;
  address public premiumNotification;
  IPremiumSendMail public premiumSendMail;

  /* 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();
    _;
  }

  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]);
  }

  /* 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 (address(premiumAutomationManager) != address(0)) {
      premiumAutomationManager.addLegacyCronjob(user, legacyAddresses);
    }
  }

  ///@notice set private code for legacy of premium user
  function setPrivateCodeIfNeeded(address legacyAddress) public onlyRouter {
    _setPrivateCodeIfNeeded(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();
    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);
  }

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

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

import "@safe-global/safe-smart-account/contracts/base/GuardManager.sol";
import {ISafeWallet} from "./interfaces/ISafeWallet.sol";

contract SafeGuard is ITransactionGuard {
  /*Error */
  error SafeGuardIntialized();

  /*State */
  uint256 public lastTimestampTxs;

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

  /* Function */
  /**
   * @dev initialize last timestamp transaction
   */
  function initialize() external intialized {
    lastTimestampTxs = block.timestamp;
  }

  /**
   * @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 refybdReceiver
   * @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 {}

  /**
   * @dev check after execution
   * @param hash safe transaction hash
   * @param success true is success false otherwise
   */
  function checkAfterExecution(bytes32 hash, bool success) external {
    if (success) {
      lastTimestampTxs = block.timestamp;
    }
  }

  /**
   * @dev support interface
   * @param interfaceId interface id
   */
  function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {
    return type(ITransactionGuard).interfaceId == interfaceId;
  }
  /**
   * @dev get last timestamp transaction
   */
  function getLastTimestampTxs() external view returns (uint256) {
    return lastTimestampTxs;
  }
}

// SPDX-License-Identifier: MIT
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 = 10 minutes;
  uint256 private constant MAX_FUTURE_OFFSET = 5 minutes;

  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)))
    }

    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);
  }
}

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

import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ERC1155HolderUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol";
import {TimelockHelper} from "./TimelockHelper.sol";

contract TimelockERC1155 is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable, ERC1155HolderUpgradeable {
  // ──────────────── Struct ────────────────
  struct TimelockInfo {
    address[] tokenAddresses;
    uint256[] tokenIds;
    uint256[] amounts;
    uint256 unlockTime;
    address owner;
    address recipient;
    bool isSoftLock;
    bool isUnlocked;
    uint256 bufferTime;
    TimelockHelper.LockType lockType;
    TimelockHelper.LockStatus lockStatus;
    string name;
  }

  // ──────────────── Events ────────────────
  event TimelockCreated(
    uint256 indexed timelockId,
    address indexed owner,
    address indexed recipient,
    address[] tokenAddresses,
    uint256[] tokenIds,
    uint256[] amounts,
    uint256 unlockTime,
    uint256 bufferTime,
    TimelockHelper.LockType lockType,
    string name
  );

  event SoftTimelockUnlocked(uint256 indexed timelockId, uint256 newUnlockTime);
  event FundsWithdrawn(uint256 indexed timelockId, address indexed recipient);

  event TimelockGiftName(uint256 indexed timelockId, string giftName, address indexed recipient);

  event ChangeStatus(uint256 indexed timelockId, TimelockHelper.LockStatus newStatus);

  // ──────────────── State ────────────────
  mapping(uint256 => TimelockInfo) public timelocks;
  address public routerAddresses;

  function onlyRouter() private view {
    if (msg.sender != routerAddresses) revert TimelockHelper.NotAuthorized();
  }

  // ──────────────── Init ────────────────
  function initialize(address initialOwner, address _routerAddresses) public initializer {
    __Ownable_init(initialOwner);
    __ReentrancyGuard_init();
    __ERC1155Holder_init();
    routerAddresses = _routerAddresses;
  }

  function _storeTimelock(
    uint256 id,
    address owner,
    address recipient,
    address[] calldata tokens,
    uint256[] calldata ids,
    uint256[] calldata amounts,
    uint256 unlock,
    bool soft,
    uint256 buffer,
    TimelockHelper.LockType lockType,
    TimelockHelper.LockStatus lockStatus,
    string calldata name
  ) internal {
    timelocks[id] = TimelockInfo({
      tokenAddresses: tokens,
      tokenIds: ids,
      amounts: amounts,
      unlockTime: unlock,
      owner: owner,
      recipient: recipient,
      isSoftLock: soft,
      isUnlocked: false,
      bufferTime: buffer,
      lockType: lockType,
      lockStatus: lockStatus,
      name: name
    });

    emit TimelockCreated(id, owner, recipient, tokens, ids, amounts, unlock, buffer, lockType, name);
    emit ChangeStatus(id, lockStatus);
  }

  function getData(uint256 id) external view returns (address[] memory, uint256[] memory, uint256[] memory) {
    TimelockInfo memory lock = timelocks[id];
    return (lock.tokenAddresses, lock.tokenIds, lock.amounts);
  }

  function getStatus(uint256 id) external view returns (TimelockHelper.LockStatus, address) {
    TimelockInfo memory lock = timelocks[id];

    if (lock.owner == address(0)) return (TimelockHelper.LockStatus.Null, address(0));
    return (lock.lockStatus, lock.owner);
  }

  function changeStatus(uint256 id, TimelockHelper.LockStatus newStatus) external nonReentrant {
    onlyRouter();
    TimelockInfo storage lock = timelocks[id];
    if (lock.owner == address(0)) return;

    lock.lockStatus = newStatus;
    emit ChangeStatus(id, newStatus);
  }

  // ──────────────── Public Create ────────────────
  function createTimelock(
    uint256 timelockId,
    address[] calldata tokens,
    uint256[] calldata ids,
    uint256[] calldata amounts,
    uint256 duration,
    string calldata name,
    address caller,
    TimelockHelper.LockStatus lockStatus
  ) external nonReentrant {
    onlyRouter();
    _storeTimelock(
      timelockId,
      caller,
      caller,
      tokens,
      ids,
      amounts,
      block.timestamp + duration,
      false,
      0,
      TimelockHelper.LockType.Regular,
      lockStatus,
      name
    );
  }

  function createSoftTimelock(
    uint256 timelockId,
    address[] calldata tokens,
    uint256[] calldata ids,
    uint256[] calldata amounts,
    uint256 bufferTime,
    string calldata name,
    address caller,
    TimelockHelper.LockStatus lockStatus
  ) external nonReentrant {
    onlyRouter();
    _storeTimelock(timelockId, caller, caller, tokens, ids, amounts, 0, true, bufferTime, TimelockHelper.LockType.Soft, lockStatus, name);
  }

  function createTimelockedGift(
    uint256 timelockId,
    address[] calldata tokens,
    uint256[] calldata ids,
    uint256[] calldata amounts,
    uint256 duration,
    address recipient,
    string calldata name,
    string calldata giftName,
    address caller,
    TimelockHelper.LockStatus lockStatus
  ) external nonReentrant {
    onlyRouter();
    _storeTimelock(
      timelockId,
      caller,
      recipient,
      tokens,
      ids,
      amounts,
      block.timestamp + duration,
      false,
      0,
      TimelockHelper.LockType.Gift,
      lockStatus,
      name
    );
    emit TimelockGiftName(timelockId, giftName, recipient);
  }

  // ──────────────── Soft Unlock ────────────────
  function unlockSoftTimelock(uint256 timelockId, address caller) external nonReentrant {
    TimelockInfo storage lock = timelocks[timelockId];

    if (lock.owner == address(0)) return;
    if (lock.lockStatus != TimelockHelper.LockStatus.Live) revert TimelockHelper.TimelockNotLive();

    if (!lock.isSoftLock) revert TimelockHelper.NotSoftTimelock();
    if (lock.isUnlocked) revert TimelockHelper.AlreadyUnlocked();
    if (caller != lock.owner) revert TimelockHelper.NotOwner();

    lock.isUnlocked = true;
    lock.unlockTime = block.timestamp + lock.bufferTime;

    emit SoftTimelockUnlocked(timelockId, lock.unlockTime);
  }

  // ──────────────── Withdraw ────────────────
  function withdraw(uint256 timelockId, address caller) external nonReentrant {
    TimelockInfo storage lock = timelocks[timelockId];

    if (lock.owner == address(0)) return;

    if (lock.lockStatus != TimelockHelper.LockStatus.Live) revert TimelockHelper.TimelockNotLive();
    lock.lockStatus = TimelockHelper.LockStatus.Ended;
    emit ChangeStatus(timelockId, TimelockHelper.LockStatus.Ended);

    if (lock.tokenIds.length == 0) revert TimelockHelper.NoFundsToWithdraw();
    if (caller != lock.recipient) revert TimelockHelper.NotAuthorized();
    if (lock.isSoftLock && !lock.isUnlocked) revert TimelockHelper.NotSoftTimelock();
    if (block.timestamp < lock.unlockTime) revert TimelockHelper.StillLocked();

    address[] memory tokens = lock.tokenAddresses;
    uint256[] memory ids = lock.tokenIds;
    uint256[] memory amounts = lock.amounts;

    delete lock.tokenAddresses;
    delete lock.tokenIds;
    delete lock.amounts;

    for (uint256 i = 0; i < tokens.length; i++) {
      IERC1155(tokens[i]).safeTransferFrom(address(this), caller, ids[i], amounts[i], "");
    }

    emit FundsWithdrawn(timelockId, caller);
  }

  // ──────────────── View ────────────────
  function getTimelockDetails(uint256 timelockId) external view returns (TimelockInfo memory) {
    return timelocks[timelockId];
  }
}

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
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";

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

contract TimelockERC20 is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable {
  // ───────────── Constants ─────────────
  address internal constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

  // ───────────── Struct ─────────────
  struct TimelockInfo {
    address[] tokenAddresses;
    uint256[] amounts;
    uint256 unlockTime;
    address owner;
    address recipient;
    bool isSoftLock;
    bool isUnlocked;
    uint256 bufferTime;
    TimelockHelper.LockType lockType;
    TimelockHelper.LockStatus lockStatus;
    string name;
  }

  // ───────────── Events ─────────────
  event TimelockCreated(
    uint256 indexed timelockId,
    address indexed owner,
    address indexed recipient,
    address[] tokenAddresses,
    uint256[] amounts,
    uint256 unlockTime,
    uint256 bufferTime,
    TimelockHelper.LockType lockType,
    string name
  );

  event TimelockGiftName(uint256 indexed timelockId, string giftName, address indexed recipient);

  event SoftTimelockUnlocked(uint256 indexed timelockId, uint256 newUnlockTime);
  event FundsWithdrawn(uint256 indexed timelockId, address indexed recipient);

  event ChangeStatus(uint256 indexed timelockId, TimelockHelper.LockStatus newStatus);

  // ───────────── Storage ─────────────
  mapping(uint256 => TimelockInfo) public timelocks;
  address public routerAddresses;

  function onlyRouter() private view {
    if (msg.sender != routerAddresses) revert TimelockHelper.NotAuthorized();
  }

  // ───────────── Init ─────────────
  function initialize(address initialOwner, address _routerAddresses) public initializer {
    __Ownable_init(initialOwner);
    __ReentrancyGuard_init();
    routerAddresses = _routerAddresses;
  }

  function getData(uint256 id) external view returns (address[] memory, uint256[] memory) {
    TimelockInfo memory lock = timelocks[id];
    return (lock.tokenAddresses, lock.amounts);
  }

  function getStatus(uint256 id) external view returns (TimelockHelper.LockStatus, address) {
    TimelockInfo memory lock = timelocks[id];

    if (lock.owner == address(0)) return (TimelockHelper.LockStatus.Null, address(0));
    return (lock.lockStatus, lock.owner);
  }

  function changeStatus(uint256 id, TimelockHelper.LockStatus newStatus) external nonReentrant {
    onlyRouter();
    TimelockInfo storage lock = timelocks[id];

    if (lock.owner == address(0)) return;

    lock.lockStatus = newStatus;
    emit ChangeStatus(id, newStatus);
  }

  // ───────────── Create ─────────────
  function createTimelock(
    uint256 id,
    address[] calldata tokens,
    uint256[] calldata amounts,
    uint256 duration,
    string calldata name,
    address caller,
    TimelockHelper.LockStatus lockStatus
  ) external payable nonReentrant {
    onlyRouter();
    _createTimelock(id, tokens, amounts, caller, caller, block.timestamp + duration, false, 0, TimelockHelper.LockType.Regular, lockStatus, name);
  }

  function createSoftTimelock(
    uint256 id,
    address[] calldata tokens,
    uint256[] calldata amounts,
    uint256 bufferTime,
    string calldata name,
    address caller,
    TimelockHelper.LockStatus lockStatus
  ) external payable nonReentrant {
    onlyRouter();
    _createTimelock(id, tokens, amounts, caller, caller, 0, true, bufferTime, TimelockHelper.LockType.Soft, lockStatus, name);
  }

  function createTimelockedGift(
    uint256 id,
    address[] calldata tokens,
    uint256[] calldata amounts,
    uint256 duration,
    address recipient,
    string calldata name,
    string calldata giftName,
    address owner,
    TimelockHelper.LockStatus lockStatus
  ) external payable nonReentrant {
    onlyRouter();
    _createTimelock(id, tokens, amounts, owner, recipient, block.timestamp + duration, false, 0, TimelockHelper.LockType.Gift, lockStatus, name);
    emit TimelockGiftName(id, giftName, recipient);
  }

  function _createTimelock(
    uint256 id,
    address[] calldata tokens,
    uint256[] calldata amounts,
    address owner,
    address recipient,
    uint256 unlockTime,
    bool isSoft,
    uint256 buffer,
    TimelockHelper.LockType lockType,
    TimelockHelper.LockStatus lockStatus,
    string memory name
  ) internal {
    timelocks[id] = TimelockInfo({
      tokenAddresses: tokens,
      amounts: amounts,
      unlockTime: unlockTime,
      owner: owner,
      recipient: recipient,
      isSoftLock: isSoft,
      isUnlocked: false,
      bufferTime: buffer,
      lockType: lockType,
      lockStatus: lockStatus,
      name: name
    });

    emit TimelockCreated(id, owner, recipient, tokens, amounts, unlockTime, buffer, lockType, name);

    emit ChangeStatus(id, lockStatus);
  }

  // ───────────── Soft Unlock ─────────────
  function unlockSoftTimelock(uint256 id, address caller) external nonReentrant {
    TimelockInfo storage lock = timelocks[id];
    if (lock.owner == address(0)) return;
    if (lock.lockStatus != TimelockHelper.LockStatus.Live) revert TimelockHelper.TimelockNotLive();

    if (!lock.isSoftLock) revert TimelockHelper.NotSoftTimelock();
    if (lock.owner != caller) revert TimelockHelper.NotOwner();
    if (lock.isUnlocked) revert TimelockHelper.AlreadyUnlocked();

    lock.isUnlocked = true;
    lock.unlockTime = block.timestamp + lock.bufferTime;

    emit SoftTimelockUnlocked(id, lock.unlockTime);
  }

  // ───────────── Withdraw ─────────────
  function withdraw(uint256 id, address caller) external nonReentrant {
    TimelockInfo storage lock = timelocks[id];

    if (lock.owner == address(0)) return;

    if (lock.lockStatus != TimelockHelper.LockStatus.Live) revert TimelockHelper.TimelockNotLive();
    lock.lockStatus = TimelockHelper.LockStatus.Ended;
    emit ChangeStatus(id, TimelockHelper.LockStatus.Ended);

    if (caller != lock.recipient) revert TimelockHelper.NotAuthorized();
    if (lock.isSoftLock && !lock.isUnlocked) revert TimelockHelper.NotSoftTimelock();
    if (block.timestamp < lock.unlockTime) revert TimelockHelper.StillLocked();
    if (lock.tokenAddresses.length == 0) revert TimelockHelper.NoFundsToWithdraw();

    address[] memory tokens = lock.tokenAddresses;
    uint256[] memory amounts = lock.amounts;

    delete lock.tokenAddresses;
    delete lock.amounts;

    for (uint256 i = 0; i < tokens.length; i++) {
      if (tokens[i] == NATIVE_TOKEN) {
        (bool success, ) = lock.recipient.call{value: amounts[i]}("");
        if (!success) revert TimelockHelper.NativeTokenTransferFailed();
      } else {
        IERC20(tokens[i]).transfer(lock.recipient, amounts[i]);
      }
    }

    emit FundsWithdrawn(id, lock.recipient);
  }

  // ───────────── View ─────────────
  function getTimelockDetails(uint256 id) external view returns (TimelockInfo memory) {
    return timelocks[id];
  }

  // ───────────── Native Token Receive ─────────────
  receive() external payable {}
}

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

import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ERC721HolderUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {TimelockHelper} from "./TimelockHelper.sol";

contract TimelockERC721 is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable, ERC721HolderUpgradeable {
  // ───────────── Structs ─────────────
  struct TimelockInfo {
    address[] tokenAddresses;
    uint256[] tokenIds;
    address owner;
    address recipient;
    uint256 unlockTime;
    bool isSoftLock;
    bool isUnlocked;
    uint256 bufferTime;
    TimelockHelper.LockType lockType;
    TimelockHelper.LockStatus lockStatus;
    string name;
  }

  // ───────────── Events ─────────────
  event TimelockCreated(
    uint256 indexed timelockId,
    address indexed owner,
    address indexed recipient,
    address[] tokenAddresses,
    uint256[] tokenIds,
    uint256 unlockTime,
    uint256 bufferTime,
    TimelockHelper.LockType lockType,
    string name
  );

  event TimelockGiftName(uint256 indexed timelockId, string giftName, address indexed recipient);
  event SoftTimelockUnlocked(uint256 indexed timelockId, uint256 unlockTime);
  event TokensWithdrawn(uint256 indexed timelockId, address indexed recipient);

  event ChangeStatus(uint256 indexed timelockId, TimelockHelper.LockStatus newStatus);

  // ───────────── State ─────────────
  mapping(uint256 => TimelockInfo) public timelocks;
  address public routerAddresses;

  function onlyRouter() private view {
    if (msg.sender != routerAddresses) revert TimelockHelper.NotAuthorized();
  }

  // ───────────── Init ─────────────
  function initialize(address initialOwner, address _routerAddresses) public initializer {
    __Ownable_init(initialOwner);
    __ReentrancyGuard_init();
    __ERC721Holder_init();
    routerAddresses = _routerAddresses;
  }

  function _storeTimelock(
    uint256 timelockId,
    address owner,
    address recipient,
    address[] calldata tokens,
    uint256[] calldata ids,
    uint256 unlockTime,
    bool isSoft,
    uint256 buffer,
    TimelockHelper.LockType lockType,
    TimelockHelper.LockStatus lockStatus,
    string calldata name
  ) internal {
    timelocks[timelockId] = TimelockInfo({
      tokenAddresses: tokens,
      tokenIds: ids,
      owner: owner,
      recipient: recipient,
      unlockTime: unlockTime,
      isSoftLock: isSoft,
      isUnlocked: false,
      bufferTime: buffer,
      lockType: lockType,
      lockStatus: lockStatus,
      name: name
    });

    emit TimelockCreated(timelockId, owner, recipient, tokens, ids, unlockTime, buffer, lockType, name);

    emit ChangeStatus(timelockId, lockStatus);
  }

  function _transferTokensOut(address[] memory tokens, uint256[] memory ids, address to) internal {
    for (uint256 i = 0; i < tokens.length; i++) {
      IERC721(tokens[i]).safeTransferFrom(address(this), to, ids[i]);
    }
  }

  function getData(uint256 id) external view returns (address[] memory, uint256[] memory) {
    TimelockInfo memory lock = timelocks[id];
    return (lock.tokenAddresses, lock.tokenIds);
  }

  function getStatus(uint256 id) external view returns (TimelockHelper.LockStatus, address) {
    TimelockInfo memory lock = timelocks[id];

    if (lock.owner == address(0)) return (TimelockHelper.LockStatus.Null, address(0));
    return (lock.lockStatus, lock.owner);
  }

  function changeStatus(uint256 id, TimelockHelper.LockStatus newStatus) external nonReentrant {
    onlyRouter();
    TimelockInfo storage lock = timelocks[id];

    if (lock.owner == address(0)) return;

    lock.lockStatus = newStatus;
    emit ChangeStatus(id, newStatus);
  }

  // ───────────── Create ─────────────
  function createTimelock(
    uint256 timelockId,
    address[] calldata tokens,
    uint256[] calldata ids,
    uint256 duration,
    string calldata name,
    address caller,
    TimelockHelper.LockStatus lockStatus
  ) external nonReentrant {
    onlyRouter();
    _storeTimelock(timelockId, caller, caller, tokens, ids, block.timestamp + duration, false, 0, TimelockHelper.LockType.Regular, lockStatus, name);
  }

  function createSoftTimelock(
    uint256 timelockId,
    address[] calldata tokens,
    uint256[] calldata ids,
    uint256 bufferTime,
    string calldata name,
    address caller,
    TimelockHelper.LockStatus lockStatus
  ) external nonReentrant {
    onlyRouter();
    _storeTimelock(timelockId, caller, caller, tokens, ids, 0, true, bufferTime, TimelockHelper.LockType.Soft, lockStatus, name);
  }

  function createTimelockedGift(
    uint256 timelockId,
    address[] calldata tokens,
    uint256[] calldata ids,
    uint256 duration,
    address recipient,
    string calldata name,
    string calldata giftName,
    address caller,
    TimelockHelper.LockStatus lockStatus
  ) external nonReentrant {
    onlyRouter();
    _storeTimelock(timelockId, caller, recipient, tokens, ids, block.timestamp + duration, false, 0, TimelockHelper.LockType.Gift, lockStatus, name);
    emit TimelockGiftName(timelockId, giftName, recipient);
  }

  // ───────────── Soft Unlock ─────────────
  function unlockSoftTimelock(uint256 timelockId, address caller) external nonReentrant {
    TimelockInfo storage lock = timelocks[timelockId];
    if (lock.owner == address(0)) return;

    if (lock.lockStatus != TimelockHelper.LockStatus.Live) revert TimelockHelper.TimelockNotLive();

    if (caller != lock.owner) revert TimelockHelper.NotAuthorized();
    if (!lock.isSoftLock) revert TimelockHelper.NotSoftTimelock();
    if (lock.isUnlocked) revert TimelockHelper.AlreadyUnlocked();

    lock.isUnlocked = true;
    lock.unlockTime = block.timestamp + lock.bufferTime;

    emit SoftTimelockUnlocked(timelockId, lock.unlockTime);
  }

  // ───────────── Withdraw ─────────────
  function withdraw(uint256 timelockId, address caller) external nonReentrant {
    TimelockInfo storage lock = timelocks[timelockId];

    if (lock.owner == address(0)) return;

    if (lock.lockStatus != TimelockHelper.LockStatus.Live) revert TimelockHelper.TimelockNotLive();
    lock.lockStatus = TimelockHelper.LockStatus.Ended;
    emit ChangeStatus(timelockId, TimelockHelper.LockStatus.Ended);

    if (caller != lock.recipient) revert TimelockHelper.NotAuthorized();
    if (lock.isSoftLock && !lock.isUnlocked) revert TimelockHelper.NotSoftTimelock();
    if (block.timestamp < lock.unlockTime) revert TimelockHelper.StillLocked();
    if (lock.tokenIds.length == 0) revert TimelockHelper.NoTokensToLock();

    address[] memory tokens = lock.tokenAddresses;
    uint256[] memory ids = lock.tokenIds;

    delete lock.tokenAddresses;
    delete lock.tokenIds;

    _transferTokensOut(tokens, ids, caller);

    emit TokensWithdrawn(timelockId, caller);
  }

  // ───────────── View ─────────────
  function getTimelockDetails(uint256 timelockId) external view returns (TimelockInfo memory) {
    return timelocks[timelockId];
  }
}

File 121 of 123 : TimelockHelper.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

library TimelockHelper {
  // ───────────── Errors ─────────────
  error ZeroDuration();
  error NotOwner();
  error NotAuthorized();
  error AlreadyUnlocked();
  error StillLocked();
  error NoFundsToWithdraw();
  error NotSoftTimelock();
  error NativeTokenTransferFailed();
  error InvalidTokenType();
  error DuplicateTokenAddresses();
  error ZeroAmount();
  error MismatchedArrayLength();
  error DuplicateTokenAddress();
  error InsufficientNativeToken();
  error ZeroBufferTime();
  error InvalidTokenAmount();
  error InvalidRecipient();
  error NoTokensToLock();
  error TimelockNotLive();
  error InvalidStatus();
  error ExecTransactionFromModuleFailed();

  // ───────────── Enums ─────────────
  enum LockType {
    Regular,
    Soft,
    Gift
  }

  enum LockStatus {
    Null,
    Created,
    Live,
    Ended
  }
}

File 122 of 123 : TimeLockRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {TimelockERC20} from "./TimeLockERC20.sol";
import {TimelockERC721} from "./TimeLockERC721.sol";
import {TimelockERC1155} from "./TimeLockERC1155.sol";

import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";

import {ISafeWallet} from "../interfaces/ISafeWallet.sol";

import {Enum} from "../libraries/Enum.sol";
import {TimelockHelper} from "./TimelockHelper.sol";

contract TimeLockRouter is OwnableUpgradeable {
  struct TimelockERC20InputData {
    address tokenAddress;
    uint256 amount;
  }

  struct TimelockERC721InputData {
    address tokenAddress;
    uint256 id;
  }

  struct TimelockERC1155InputData {
    address tokenAddress;
    uint256 id;
    uint256 amount;
  }

  struct TimelockRegular {
    TimelockERC20InputData[] timelockERC20;
    TimelockERC721InputData[] timelockERC721;
    TimelockERC1155InputData[] timelockERC1155;
    uint256 duration;
    string name;
  }

  struct TimelockSoft {
    TimelockERC20InputData[] timelockERC20;
    TimelockERC721InputData[] timelockERC721;
    TimelockERC1155InputData[] timelockERC1155;
    uint256 bufferTime;
    string name;
  }

  struct TimelockGift {
    TimelockERC20InputData[] timelockERC20;
    TimelockERC721InputData[] timelockERC721;
    TimelockERC1155InputData[] timelockERC1155;
    uint256 duration;
    address recipient;
    string name;
    string giftName;
  }

  TimelockERC20 public timelockERC20Contract;
  TimelockERC721 public timelockERC721Contract;
  TimelockERC1155 public timelockERC1155Contract;

  uint256 public timelockCounter;
  address internal constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
  bytes4 private constant IERC721_ID = 0x80ac58cd;
  bytes4 private constant IERC1155_ID = 0xd9b67a26;

  // ───────────── Native Token Receive ─────────────
  receive() external payable {}

  function initialize(address initialOwner) external initializer {
    __Ownable_init(initialOwner);
  }

  function setTimelock(address payable _timelockERC20, address payable _timelockERC721, address payable _timelockERC1155) external onlyOwner {
    timelockERC20Contract = TimelockERC20(_timelockERC20);
    timelockERC721Contract = TimelockERC721(_timelockERC721);
    timelockERC1155Contract = TimelockERC1155(_timelockERC1155);
  }

  function createTimelock(TimelockRegular calldata timelockRegular) external payable {
    if (timelockRegular.duration == 0) revert TimelockHelper.ZeroDuration();

    timelockCounter++;

    if (timelockRegular.timelockERC20.length > 0) {
      _handleTimelockRegularERC20(
        timelockCounter,
        timelockRegular.timelockERC20,
        timelockRegular.duration,
        timelockRegular.name,
        msg.sender,
        TimelockHelper.LockStatus.Live
      );
    }
    if (timelockRegular.timelockERC721.length > 0) {
      _handleTimelockRegularERC721(
        timelockCounter,
        timelockRegular.timelockERC721,
        timelockRegular.duration,
        timelockRegular.name,
        msg.sender,
        TimelockHelper.LockStatus.Live
      );
    }
    if (timelockRegular.timelockERC1155.length > 0) {
      _handleTimelockRegularERC1155(
        timelockCounter,
        timelockRegular.timelockERC1155,
        timelockRegular.duration,
        timelockRegular.name,
        msg.sender,
        TimelockHelper.LockStatus.Live
      );
    }
  }

  function createTimelockWithSafe(TimelockRegular calldata timelockRegular, address safeAddress) external {
    if (timelockRegular.duration == 0) revert TimelockHelper.ZeroDuration();

    timelockCounter++;

    if (timelockRegular.timelockERC20.length > 0) {
      _handleTimelockRegularERC20(
        timelockCounter,
        timelockRegular.timelockERC20,
        timelockRegular.duration,
        timelockRegular.name,
        safeAddress,
        TimelockHelper.LockStatus.Created
      );
    }
    if (timelockRegular.timelockERC721.length > 0) {
      _handleTimelockRegularERC721(
        timelockCounter,
        timelockRegular.timelockERC721,
        timelockRegular.duration,
        timelockRegular.name,
        safeAddress,
        TimelockHelper.LockStatus.Created
      );
    }
    if (timelockRegular.timelockERC1155.length > 0) {
      _handleTimelockRegularERC1155(
        timelockCounter,
        timelockRegular.timelockERC1155,
        timelockRegular.duration,
        timelockRegular.name,
        safeAddress,
        TimelockHelper.LockStatus.Created
      );
    }
  }

  function getStatusOwner(uint256 id) public view returns (TimelockHelper.LockStatus, address) {
    (TimelockHelper.LockStatus status, address owner) = timelockERC20Contract.getStatus(id);
    if (status == TimelockHelper.LockStatus.Null) {
      (status, owner) = timelockERC721Contract.getStatus(id);
    }
    if (status == TimelockHelper.LockStatus.Null) {
      (status, owner) = timelockERC1155Contract.getStatus(id);
    }
    return (status, owner);
  }

  function makeLiveBySafe(uint256 id) external {
    (TimelockHelper.LockStatus status, address safe) = getStatusOwner(id);
    if (status != TimelockHelper.LockStatus.Created) revert TimelockHelper.InvalidStatus();
    if (safe != msg.sender) revert TimelockHelper.NotOwner();

    // transfer
    _handleSafeTransferERC20(id, safe);
    _handleSafeTransferERC721(id, safe);
    _handleSafeTransferERC1155(id, safe);

    timelockERC20Contract.changeStatus(id, TimelockHelper.LockStatus.Live);
    timelockERC721Contract.changeStatus(id, TimelockHelper.LockStatus.Live);
    timelockERC1155Contract.changeStatus(id, TimelockHelper.LockStatus.Live);
  }

  function _handleSafeTransferERC20(uint256 id, address safe) internal {
    (address[] memory tokens, uint256[] memory amounts) = TimelockERC20(timelockERC20Contract).getData(id);
    if (tokens.length == 0) return;

    for (uint256 i = 0; i < tokens.length; i++) {
      if (tokens[i] == NATIVE_TOKEN) {
        bool transferEthSuccess = ISafeWallet(safe).execTransactionFromModule(address(timelockERC20Contract), amounts[i], "", Enum.Operation.Call);
        if (!transferEthSuccess) revert TimelockHelper.ExecTransactionFromModuleFailed();
      } else {
        bytes memory transferErc20Data = abi.encodeWithSignature("transfer(address,uint256)", address(timelockERC20Contract), amounts[i]);
        bool transferErc20Success = ISafeWallet(safe).execTransactionFromModule(tokens[i], 0, transferErc20Data, Enum.Operation.Call);
        if (!transferErc20Success) revert TimelockHelper.ExecTransactionFromModuleFailed();
      }
    }
  }

  function _handleSafeTransferERC721(uint256 id, address safe) internal {
    (address[] memory tokens, uint256[] memory ids) = TimelockERC721(timelockERC721Contract).getData(id);
    if (tokens.length == 0) return;

    for (uint256 i = 0; i < tokens.length; i++) {
      bytes memory transferErc721Data = abi.encodeWithSignature(
        "transferFrom(address,address,uint256)",
        safe,
        address(timelockERC721Contract),
        ids[i]
      );
      bool transferErc721Success = ISafeWallet(safe).execTransactionFromModule(tokens[i], 0, transferErc721Data, Enum.Operation.Call);
      if (!transferErc721Success) revert TimelockHelper.ExecTransactionFromModuleFailed();
    }
  }

  function _handleSafeTransferERC1155(uint256 id, address safe) internal {
    (address[] memory tokens, uint256[] memory ids, uint256[] memory amounts) = TimelockERC1155(timelockERC1155Contract).getData(id);
    if (tokens.length == 0) return;

    for (uint256 i = 0; i < tokens.length; i++) {
      bytes memory transferErc1155Data = abi.encodeWithSignature(
        "safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)",
        safe,
        address(timelockERC1155Contract),
        ids,
        amounts,
        ""
      );
      bool transferErc1155Success = ISafeWallet(safe).execTransactionFromModule(tokens[i], 0, transferErc1155Data, Enum.Operation.Call);
      if (!transferErc1155Success) revert TimelockHelper.ExecTransactionFromModuleFailed();
    }
  }

  function createSoftTimelock(TimelockSoft calldata timelockSoft) external payable {
    if (timelockSoft.bufferTime == 0) revert TimelockHelper.ZeroBufferTime();

    timelockCounter++;

    if (timelockSoft.timelockERC20.length > 0) {
      _handleTimelockSoftERC20(
        timelockCounter,
        timelockSoft.timelockERC20,
        timelockSoft.bufferTime,
        timelockSoft.name,
        msg.sender,
        TimelockHelper.LockStatus.Live
      );
    }
    if (timelockSoft.timelockERC721.length > 0) {
      _handleTimelockSoftERC721(
        timelockCounter,
        timelockSoft.timelockERC721,
        timelockSoft.bufferTime,
        timelockSoft.name,
        msg.sender,
        TimelockHelper.LockStatus.Live
      );
    }

    if (timelockSoft.timelockERC1155.length > 0) {
      _handleTimelockSoftERC1155(
        timelockCounter,
        timelockSoft.timelockERC1155,
        timelockSoft.bufferTime,
        timelockSoft.name,
        msg.sender,
        TimelockHelper.LockStatus.Live
      );
    }
  }

  function createSoftTimelockWithSafe(TimelockSoft calldata timelockSoft, address safeAddress) external payable {
    if (timelockSoft.bufferTime == 0) revert TimelockHelper.ZeroBufferTime();

    timelockCounter++;

    if (timelockSoft.timelockERC20.length > 0) {
      _handleTimelockSoftERC20(
        timelockCounter,
        timelockSoft.timelockERC20,
        timelockSoft.bufferTime,
        timelockSoft.name,
        safeAddress,
        TimelockHelper.LockStatus.Created
      );
    }
    if (timelockSoft.timelockERC721.length > 0) {
      _handleTimelockSoftERC721(
        timelockCounter,
        timelockSoft.timelockERC721,
        timelockSoft.bufferTime,
        timelockSoft.name,
        safeAddress,
        TimelockHelper.LockStatus.Created
      );
    }

    if (timelockSoft.timelockERC1155.length > 0) {
      _handleTimelockSoftERC1155(
        timelockCounter,
        timelockSoft.timelockERC1155,
        timelockSoft.bufferTime,
        timelockSoft.name,
        safeAddress,
        TimelockHelper.LockStatus.Created
      );
    }
  }

  function createTimelockedGift(TimelockGift calldata timelockGift) external payable {
    if (timelockGift.duration == 0) revert TimelockHelper.ZeroDuration();
    if (timelockGift.recipient == address(0)) revert TimelockHelper.InvalidRecipient();

    timelockCounter++;

    if (timelockGift.timelockERC20.length > 0) {
      _handleTimelockGiftERC20(
        timelockCounter,
        timelockGift.timelockERC20,
        timelockGift.duration,
        timelockGift.recipient,
        timelockGift.name,
        timelockGift.giftName,
        msg.sender,
        TimelockHelper.LockStatus.Live
      );
    }
    if (timelockGift.timelockERC721.length > 0) {
      _handleTimelockGiftERC721(
        timelockCounter,
        timelockGift.timelockERC721,
        timelockGift.duration,
        timelockGift.recipient,
        timelockGift.name,
        timelockGift.giftName,
        msg.sender,
        TimelockHelper.LockStatus.Live
      );
    }
    if (timelockGift.timelockERC1155.length > 0) {
      _handleTimelockGiftERC1155(
        timelockCounter,
        timelockGift.timelockERC1155,
        timelockGift.duration,
        timelockGift.recipient,
        timelockGift.name,
        timelockGift.giftName,
        msg.sender,
        TimelockHelper.LockStatus.Live
      );
    }
  }

  function createTimelockedGiftWithSafe(TimelockGift calldata timelockGift, address safeAddress) external payable {
    if (timelockGift.duration == 0) revert TimelockHelper.ZeroDuration();
    if (timelockGift.recipient == address(0)) revert TimelockHelper.InvalidRecipient();

    timelockCounter++;

    if (timelockGift.timelockERC20.length > 0) {
      _handleTimelockGiftERC20(
        timelockCounter,
        timelockGift.timelockERC20,
        timelockGift.duration,
        timelockGift.recipient,
        timelockGift.name,
        timelockGift.giftName,
        safeAddress,
        TimelockHelper.LockStatus.Created
      );
    }
    if (timelockGift.timelockERC721.length > 0) {
      _handleTimelockGiftERC721(
        timelockCounter,
        timelockGift.timelockERC721,
        timelockGift.duration,
        timelockGift.recipient,
        timelockGift.name,
        timelockGift.giftName,
        safeAddress,
        TimelockHelper.LockStatus.Created
      );
    }
    if (timelockGift.timelockERC1155.length > 0) {
      _handleTimelockGiftERC1155(
        timelockCounter,
        timelockGift.timelockERC1155,
        timelockGift.duration,
        timelockGift.recipient,
        timelockGift.name,
        timelockGift.giftName,
        safeAddress,
        TimelockHelper.LockStatus.Created
      );
    }
  }

  function unlockSoftTimelock(uint256 id) external {
    timelockERC20Contract.unlockSoftTimelock(id, msg.sender);
    timelockERC721Contract.unlockSoftTimelock(id, msg.sender);
    timelockERC1155Contract.unlockSoftTimelock(id, msg.sender);
  }

  function withdraw(uint256 id) external {
    timelockERC20Contract.withdraw(id, msg.sender);
    timelockERC721Contract.withdraw(id, msg.sender);
    timelockERC1155Contract.withdraw(id, msg.sender);
  }

  // ───────────── private ─────────────
  // ********** Regular **********

  // regular ERC20

  function _makeListERC20(TimelockERC20InputData[] calldata timelockERC20) private pure returns (address[] memory tokens, uint256[] memory amounts) {
    tokens = new address[](timelockERC20.length);
    amounts = new uint256[](timelockERC20.length);
    for (uint256 i = 0; i < timelockERC20.length; i++) {
      tokens[i] = timelockERC20[i].tokenAddress;
      amounts[i] = timelockERC20[i].amount;
    }
  }

  function _handleTimelockRegularERC20(
    uint256 timelockId,
    TimelockERC20InputData[] calldata timelockERC20,
    uint256 duration,
    string calldata name,
    address owner,
    TimelockHelper.LockStatus lockStatus
  ) private {
    (address[] memory tokens, uint256[] memory amounts) = _makeListERC20(timelockERC20);
    uint256 requiredNativeAmount = _validateERC20Input(tokens, amounts);
    if (lockStatus == TimelockHelper.LockStatus.Live) {
      _transferERC20TokensIn(tokens, amounts, requiredNativeAmount);
    }
    timelockERC20Contract.createTimelock{value: msg.value}(timelockId, tokens, amounts, duration, name, owner, lockStatus);
  }

  function _handleTimelockSoftERC20(
    uint256 timelockId,
    TimelockERC20InputData[] calldata timelockERC20,
    uint256 bufferTime,
    string calldata name,
    address owner,
    TimelockHelper.LockStatus lockStatus
  ) private {
    (address[] memory tokens, uint256[] memory amounts) = _makeListERC20(timelockERC20);
    uint256 requiredNativeAmount = _validateERC20Input(tokens, amounts);
    if (lockStatus == TimelockHelper.LockStatus.Live) {
      _transferERC20TokensIn(tokens, amounts, requiredNativeAmount);
    }
    timelockERC20Contract.createSoftTimelock{value: msg.value}(timelockId, tokens, amounts, bufferTime, name, owner, lockStatus);
  }

  function _handleTimelockGiftERC20(
    uint256 timelockId,
    TimelockERC20InputData[] calldata timelockERC20,
    uint256 duration,
    address recipient,
    string calldata name,
    string calldata giftName,
    address owner,
    TimelockHelper.LockStatus lockStatus
  ) private {
    (address[] memory tokens, uint256[] memory amounts) = _makeListERC20(timelockERC20);
    uint256 requiredNativeAmount = _validateERC20Input(tokens, amounts);
    if (lockStatus == TimelockHelper.LockStatus.Live) {
      _transferERC20TokensIn(tokens, amounts, requiredNativeAmount);
    }

    timelockERC20Contract.createTimelockedGift{value: msg.value}(timelockId, tokens, amounts, duration, recipient, name, giftName, owner, lockStatus);
  }

  function _transferERC20TokensIn(address[] memory tokens, uint256[] memory amounts, uint256 requiredNativeAmount) private {
    if (requiredNativeAmount != msg.value) {
      revert TimelockHelper.InsufficientNativeToken();
    }

    for (uint256 i = 0; i < tokens.length; i++) {
      if (tokens[i] != NATIVE_TOKEN) {
        IERC20(tokens[i]).transferFrom(msg.sender, address(timelockERC20Contract), amounts[i]);
      }
    }
  }

  function _validateERC20Input(address[] memory tokens, uint256[] memory amounts) private pure returns (uint256) {
    if (tokens.length == 0 || tokens.length != amounts.length) revert TimelockHelper.MismatchedArrayLength();

    uint256 requiredNativeAmount = 0;
    for (uint256 i = 0; i < tokens.length; i++) {
      if (amounts[i] == 0) revert TimelockHelper.InvalidTokenAmount();
      if (tokens[i] == NATIVE_TOKEN) {
        requiredNativeAmount = amounts[i];
      }
    }

    // ───── Check for duplicate token addresses ─────
    for (uint256 i = 0; i < tokens.length; i++) {
      for (uint256 j = i + 1; j < tokens.length; j++) {
        if (tokens[i] == tokens[j]) revert TimelockHelper.DuplicateTokenAddress();
      }
    }

    return requiredNativeAmount;
  }

  // regular ERC721

  function _makeListERC721(TimelockERC721InputData[] calldata timelockERC721) private pure returns (address[] memory tokens, uint256[] memory ids) {
    tokens = new address[](timelockERC721.length);
    ids = new uint256[](timelockERC721.length);
    for (uint256 i = 0; i < timelockERC721.length; i++) {
      tokens[i] = timelockERC721[i].tokenAddress;
      ids[i] = timelockERC721[i].id;
    }
  }

  function _handleTimelockRegularERC721(
    uint256 timelockId,
    TimelockERC721InputData[] calldata timelockERC721,
    uint256 duration,
    string calldata name,
    address owner,
    TimelockHelper.LockStatus lockStatus
  ) private {
    (address[] memory tokens, uint256[] memory ids) = _makeListERC721(timelockERC721);
    _validateERC721Input(tokens, ids);
    if (lockStatus == TimelockHelper.LockStatus.Live) {
      _transferERC721TokensIn(tokens, ids);
    }
    timelockERC721Contract.createTimelock(timelockId, tokens, ids, duration, name, owner, lockStatus);
  }

  function _handleTimelockSoftERC721(
    uint256 timelockId,
    TimelockERC721InputData[] calldata timelockERC721,
    uint256 bufferTime,
    string calldata name,
    address owner,
    TimelockHelper.LockStatus lockStatus
  ) private {
    (address[] memory tokens, uint256[] memory ids) = _makeListERC721(timelockERC721);

    _validateERC721Input(tokens, ids);
    if (lockStatus == TimelockHelper.LockStatus.Live) {
      _transferERC721TokensIn(tokens, ids);
    }
    timelockERC721Contract.createSoftTimelock(timelockId, tokens, ids, bufferTime, name, owner, lockStatus);
  }

  function _handleTimelockGiftERC721(
    uint256 timelockId,
    TimelockERC721InputData[] calldata timelockERC721,
    uint256 duration,
    address recipient,
    string calldata name,
    string calldata giftName,
    address owner,
    TimelockHelper.LockStatus lockStatus
  ) private {
    (address[] memory tokens, uint256[] memory ids) = _makeListERC721(timelockERC721);

    _validateERC721Input(tokens, ids);
    if (lockStatus == TimelockHelper.LockStatus.Live) {
      _transferERC721TokensIn(tokens, ids);
    }

    timelockERC721Contract.createTimelockedGift(timelockId, tokens, ids, duration, recipient, name, giftName, owner, lockStatus);
  }

  function _transferERC721TokensIn(address[] memory tokens, uint256[] memory ids) private {
    for (uint256 i = 0; i < tokens.length; i++) {
      IERC721(tokens[i]).safeTransferFrom(msg.sender, address(timelockERC721Contract), ids[i]);
    }
  }

  function _validateERC721(address token) private view {
    if (!IERC165(token).supportsInterface(IERC721_ID)) revert TimelockHelper.InvalidTokenType();
  }

  function _validateERC721Input(address[] memory tokens, uint256[] memory ids) private view {
    if (tokens.length == 0 || tokens.length != ids.length) revert TimelockHelper.MismatchedArrayLength();
    for (uint256 i = 0; i < tokens.length; i++) {
      _validateERC721(tokens[i]);
      for (uint256 j = i + 1; j < tokens.length; j++) {
        if (tokens[i] == tokens[j] && ids[i] == ids[j]) revert TimelockHelper.DuplicateTokenAddresses();
      }
    }
  }

  // regular ERC1155

  function _makeListERC1155(
    TimelockERC1155InputData[] calldata timelockERC1155
  ) private pure returns (address[] memory tokens, uint256[] memory ids, uint256[] memory amounts) {
    tokens = new address[](timelockERC1155.length);
    ids = new uint256[](timelockERC1155.length);
    amounts = new uint256[](timelockERC1155.length);
    for (uint256 i = 0; i < timelockERC1155.length; i++) {
      tokens[i] = timelockERC1155[i].tokenAddress;
      ids[i] = timelockERC1155[i].id;
      amounts[i] = timelockERC1155[i].amount;
    }
  }

  function _handleTimelockRegularERC1155(
    uint256 timelockId,
    TimelockERC1155InputData[] calldata timelockERC1155,
    uint256 duration,
    string calldata name,
    address owner,
    TimelockHelper.LockStatus lockStatus
  ) private {
    (address[] memory tokens, uint256[] memory ids, uint256[] memory amounts) = _makeListERC1155(timelockERC1155);

    _validateERC1155Input(tokens, ids, amounts);
    if (lockStatus == TimelockHelper.LockStatus.Live) {
      _transferERC1155TokensIn(tokens, ids, amounts);
    }
    timelockERC1155Contract.createTimelock(timelockId, tokens, ids, amounts, duration, name, owner, lockStatus);
  }

  function _handleTimelockSoftERC1155(
    uint256 timelockId,
    TimelockERC1155InputData[] calldata timelockERC1155,
    uint256 bufferTime,
    string calldata name,
    address owner,
    TimelockHelper.LockStatus lockStatus
  ) private {
    (address[] memory tokens, uint256[] memory ids, uint256[] memory amounts) = _makeListERC1155(timelockERC1155);

    for (uint256 i = 0; i < timelockERC1155.length; i++) {
      tokens[i] = timelockERC1155[i].tokenAddress;
      ids[i] = timelockERC1155[i].id;
      amounts[i] = timelockERC1155[i].amount;
    }

    _validateERC1155Input(tokens, ids, amounts);
    if (lockStatus == TimelockHelper.LockStatus.Live) {
      _transferERC1155TokensIn(tokens, ids, amounts);
    }
    timelockERC1155Contract.createSoftTimelock(timelockId, tokens, ids, amounts, bufferTime, name, owner, lockStatus);
  }

  function _handleTimelockGiftERC1155(
    uint256 timelockId,
    TimelockERC1155InputData[] calldata timelockERC1155,
    uint256 duration,
    address recipient,
    string calldata name,
    string calldata giftName,
    address owner,
    TimelockHelper.LockStatus lockStatus
  ) private {
    (address[] memory tokens, uint256[] memory ids, uint256[] memory amounts) = _makeListERC1155(timelockERC1155);

    _validateERC1155Input(tokens, ids, amounts);
    if (lockStatus == TimelockHelper.LockStatus.Live) {
      _transferERC1155TokensIn(tokens, ids, amounts);
    }

    timelockERC1155Contract.createTimelockedGift(timelockId, tokens, ids, amounts, duration, recipient, name, giftName, owner, lockStatus);
  }

  function _transferERC1155TokensIn(address[] memory tokens, uint256[] memory ids, uint256[] memory amounts) private {
    for (uint256 i = 0; i < tokens.length; i++) {
      IERC1155(tokens[i]).safeTransferFrom(msg.sender, address(timelockERC1155Contract), ids[i], amounts[i], "");
    }
  }

  function _validateERC1155(address token) private view {
    if (!IERC165(token).supportsInterface(IERC1155_ID)) revert TimelockHelper.InvalidTokenType();
  }

  function _validateERC1155Input(address[] memory tokens, uint256[] memory ids, uint256[] memory amounts) private view {
    if (tokens.length == 0 || tokens.length != ids.length || ids.length != amounts.length) revert TimelockHelper.MismatchedArrayLength();
    for (uint256 i = 0; i < amounts.length; i++) {
      if (amounts[i] == 0) revert TimelockHelper.ZeroAmount();
    }
    for (uint256 i = 0; i < tokens.length; i++) {
      _validateERC1155(tokens[i]);
      for (uint256 j = i + 1; j < tokens.length; j++) {
        if (tokens[i] == tokens[j] && ids[i] == ids[j]) revert TimelockHelper.DuplicateTokenAddresses();
      }
    }
  }
}

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

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Burnable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";

contract Token is ERC20, ERC20Burnable, AccessControl, ERC20Permit {
  bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");

  constructor(address defaultAdmin, address minter, string memory name, string memory symbol) ERC20(name, symbol) ERC20Permit(name) {
    _grantRole(DEFAULT_ADMIN_ROLE, defaultAdmin);
    _grantRole(MINTER_ROLE, minter);
  }

  function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
    _mint(to, amount);
  }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "viaIR": true,
  "evmVersion": "paris",
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "metadata": {
    "useLiteralContent": true
  }
}

Contract ABI

API
[{"inputs":[],"name":"EmptySource","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NoInlineSecrets","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"OnlyRouterCanFulfill","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"length","type":"uint256"}],"name":"StringsInsufficientHexLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"requestId","type":"bytes32"}],"name":"UnexpectedRequestID","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"RequestFulfilled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"RequestSent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"requestId","type":"bytes32"},{"indexed":false,"internalType":"bytes","name":"response","type":"bytes"},{"indexed":false,"internalType":"bytes","name":"err","type":"bytes"}],"name":"Response","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"to","type":"string"},{"indexed":false,"internalType":"enum NotifyLib.NotifyType","name":"notifyType","type":"uint8"}],"name":"SendMail","type":"event"},{"inputs":[{"internalType":"string","name":"beneName","type":"string"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"timeCountdown","type":"uint256"},{"internalType":"string","name":"beneEmail","type":"string"}],"name":"_sendEmailBeforeActivationToBeneficiary","outputs":[{"internalType":"bytes32","name":"requestId","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"ownerName","type":"string"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"lastTx","type":"uint256"},{"internalType":"uint256","name":"bufferTime","type":"uint256"},{"internalType":"address[]","name":"listBene","type":"address[]"},{"internalType":"string","name":"ownerEmail","type":"string"}],"name":"_sendEmailBeforeActivationToOwner","outputs":[{"internalType":"bytes32","name":"requestId","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"beneName","type":"string"},{"internalType":"string","name":"beneEmail","type":"string"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"x_days","type":"uint256"}],"name":"_sendEmailBeforeLayer2ToLayer1","outputs":[{"internalType":"bytes32","name":"requestId","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"beneName","type":"string"},{"internalType":"string","name":"beneEmail","type":"string"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"x_days","type":"uint256"}],"name":"_sendEmailBeforeLayer2ToLayer2","outputs":[{"internalType":"bytes32","name":"requestId","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"beneName","type":"string"},{"internalType":"string","name":"beneEmail","type":"string"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"x_day","type":"uint256"}],"name":"_sendEmailBeforeLayer3ToLayer12","outputs":[{"internalType":"bytes32","name":"requestId","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"beneName","type":"string"},{"internalType":"string","name":"beneEmail","type":"string"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"x_day","type":"uint256"}],"name":"_sendEmailBeforeLayer3ToLayer3","outputs":[{"internalType":"bytes32","name":"requestId","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"donID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gasLimit","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"requestId","type":"bytes32"},{"internalType":"bytes","name":"response","type":"bytes"},{"internalType":"bytes","name":"err","type":"bytes"}],"name":"handleOracleFulfillment","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_router","type":"address"},{"internalType":"uint64","name":"_subscriptionId","type":"uint64"},{"internalType":"bytes32","name":"_donId","type":"bytes32"},{"internalType":"uint32","name":"_gasLimit","type":"uint32"},{"internalType":"address","name":"_sendMailRouter","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"mailId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"router","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"s_lastError","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"s_lastRequestId","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"s_lastResponse","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string[]","name":"beneNames","type":"string[]"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"timeCountdown","type":"uint256"},{"internalType":"string[]","name":"beneEmails","type":"string[]"}],"name":"sendEmailBeforeActivationToBeneficiary","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"ownerName","type":"string"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"lastTx","type":"uint256"},{"internalType":"uint256","name":"bufferTime","type":"uint256"},{"internalType":"address[]","name":"listBene","type":"address[]"},{"internalType":"string","name":"ownerEmail","type":"string"}],"name":"sendEmailBeforeActivationToOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string[]","name":"beneNames","type":"string[]"},{"internalType":"string[]","name":"beneEmails","type":"string[]"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"x_days","type":"uint256"}],"name":"sendEmailBeforeLayer2ToLayer1","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"beneName","type":"string"},{"internalType":"string","name":"beneEmail","type":"string"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"x_days","type":"uint256"}],"name":"sendEmailBeforeLayer2ToLayer2","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string[]","name":"beneNames","type":"string[]"},{"internalType":"string[]","name":"beneEmails","type":"string[]"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"x_day","type":"uint256"}],"name":"sendEmailBeforeLayer3ToLayer12","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"beneName","type":"string"},{"internalType":"string","name":"beneEmail","type":"string"},{"internalType":"string","name":"contractName","type":"string"},{"internalType":"uint256","name":"x_day","type":"uint256"}],"name":"sendEmailBeforeLayer3ToLayer3","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sendMailRouter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"subscriptionId","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]

6080806040523461007257600080546001600160a01b03191673b83e47c2bc239b3bf370bc41e1459a34b41238d01790557f66756e2d657468657265756d2d7365706f6c69612d31000000000000000000006001556007805463ffffffff1916620493e01790556139de90816100788239f35b600080fdfe6080604052600436101561001257600080fd5b60003560e01c806309c1ba2e146101b75780630ca76175146101b257806313bac909146101ad57806313f195c0146101a8578063202a4b3f146101a35780633944ea3a1461019e57806340761ad61461019957806341a8af3c146101945780634776258a1461018f578063485786bd1461018a5780634b0795a8146101855780635953951b146101805780635b5dc0f61461017b578063688f16f2146101765780636c8ae395146101715780636e74336b1461016c578063715018a6146101675780637dad97d11461016257806385de98021461015d5780638da5cb5b1461015857806390de99b714610153578063b1e217491461014e578063eab3252b14610149578063f2fde38b14610144578063f68016b71461013f5763f887ea401461013a57600080fd5b610f76565b610f52565b610f29565b610ea0565b610e82565b610e43565b610e0d565b610cb6565b610c98565b610c2d565b610c0f565b610b86565b610a60565b6109a5565b610986565b6107d0565b6107b4565b610798565b61077c565b61073f565b61066c565b6105ab565b61058f565b6104b3565b6102b7565b346101de5760003660031901126101de5760206001600160401b0360025416604051908152f35b600080fd5b634e487b7160e01b600052604160045260246000fd5b604081019081106001600160401b0382111761021457604052565b6101e3565b608081019081106001600160401b0382111761021457604052565b90601f801991011681019081106001600160401b0382111761021457604052565b6001600160401b03811161021457601f01601f191660200190565b81601f820112156101de5780359061028782610255565b926102956040519485610234565b828452602083830101116101de57816000926020809301838601378301015290565b346101de5760603660031901126101de576001600160401b0360048035906024358381116101de576102ec9036908301610270565b906044358481116101de576103049036908301610270565b9060009460018060a01b03865416330361046f5784600354036104575783519081116102145761033d8161033884546105d6565b611100565b602080601f83116001146103d6575081906103729588926103cb575b50508160011b916000199060031b1c19161790556111be565b807f7873807bf6ddc50401cd3d29bbe0decee23fd4d68d273f4b5eb83cded4d2f172604051806103a181611327565b0390a27f85e1543bf2f84fe80c6badbce3648c8539ad1df4d2b3d822938ca0538be727e68280a280f35b015190503880610359565b91929394601f1984166103f9600460005260008051602061392983398151915290565b9389905b82821061043f5750509160019391856103729897969410610426575b505050811b0190556111be565b015160001960f88460031b161c19169055388080610419565b806001869782949787015181550196019401906103fd565b60405163d068bf5b60e01b8152808301869052602490fd5b60405162461bcd60e51b8152602081840152601760248201527f4f6e6c7920726f757465722063616e2066756c66696c6c0000000000000000006044820152606490fd5b346101de5760803660031901126101de576001600160401b036004358181116101de576104e4903690600401610270565b906024358181116101de576104fd903690600401610270565b6064359182116101de5760209261051b610525933690600401610270565b916044359161202c565b604051908152f35b60806003198201126101de576001600160401b03916004358381116101de578261055991600401610270565b926024358181116101de578361057191600401610270565b926044359182116101de5761058891600401610270565b9060643590565b346101de5760206105256105a23661052d565b9291909161268e565b346101de5760003660031901126101de576002546040805191901c6001600160a01b03168152602090f35b90600182811c92168015610606575b60208310146105f057565b634e487b7160e01b600052602260045260246000fd5b91607f16916105e5565b60005b8381106106235750506000910152565b8181015183820152602001610613565b9060209161064c81518092818552858086019101610610565b601f01601f1916010190565b906020610669928181520190610633565b90565b346101de5760008060031936011261073c57604051908060045461068f816105d6565b8085529160019180831690811561071257506001146106c9575b6106c5856106b981870382610234565b60405191829182610658565b0390f35b9250600483526000805160206139298339815191525b8284106106fa5750505081016020016106b9826106c56106a9565b805460208587018101919091529093019281016106df565b8695506106c5969350602092506106b994915060ff191682840152151560051b82010192936106a9565b80fd5b346101de5761077a6107746107533661052d565b9180949361076f60018060a01b0360025460401c1633146113d7565b61231f565b50613830565b005b346101de57602061052561078f3661052d565b9291909161231f565b346101de5760206105256107ab3661052d565b929190916127e7565b346101de5760206105256107c73661052d565b9291909161215a565b346101de5760008060031936011261073c5760405190806005546107f3816105d6565b80855291600191808316908115610712575060011461081c576106c5856106b981870382610234565b9250600583526000805160206138c98339815191525b82841061084d5750505081016020016106b9826106c56106a9565b80546020858701810191909152909301928101610832565b6001600160401b0381116102145760051b60200190565b600435906001600160a01b03821682036101de57565b608435906001600160a01b03821682036101de57565b60c06003198201126101de576001600160401b03916004358381116101de57826108d491600401610270565b926024358181116101de57836108ec91600401610270565b9260443592606435926084358181116101de57836023820112156101de57806004013561091881610865565b916109266040519384610234565b81835260209160248385019160051b830101918783116101de57602401905b82821061096757505050509260a4359182116101de5761066991600401610270565b81356001600160a01b03811681036101de578152908301908301610945565b346101de576020610525610999366108a8565b94939093929192611710565b346101de5761077a6109da6109b93661052d565b918094936109d560018060a01b0360025460401c1633146113d7565b6127e7565b5061386c565b9080601f830112156101de578135906109f882610865565b92610a066040519485610234565b828452602092838086019160051b830101928084116101de57848301915b848310610a345750505050505090565b82356001600160401b0381116101de578691610a5584848094890101610270565b815201920191610a24565b346101de5760803660031901126101de576001600160401b036004358181116101de57610a919036906004016109e0565b6024358281116101de57610aa9903690600401610270565b604435926064359081116101de57610ac59036906004016109e0565b92610ade60018060a01b0360025460401c1633146113d7565b60005b835181101561077a5780610af8610b039287611451565b5151610b0857611427565b610ae1565b610b29610b158287611451565b518486610b22858b611451565b519261202c565b50610b3d610b378288611451565b516137dd565b611427565b60806003198201126101de576001600160401b03916004358381116101de5782610b6e916004016109e0565b926024358181116101de5783610571916004016109e0565b346101de57610b9436610b42565b90610bb060018060a09695961b0360025460401c1633146113d7565b60005b835181101561077a5780610bca610bd59287611451565b5151610bda57611427565b610bb3565b610bfb8484610be98489611451565b51610bf4858b611451565b519061268e565b50610b3d610c098288611451565b5161386c565b346101de5760003660031901126101de576020600154604051908152f35b346101de5760008060031936011261073c57610c47610f9f565b6000805160206138e983398151915280546001600160a01b0319811690915581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b346101de5760003660031901126101de576020600654604051908152f35b346101de5760a03660031901126101de57610ccf61087c565b6024356001600160401b039182821682036101de5760643563ffffffff811681036101de57610cfc610892565b91600080516020613969833981519152549460ff8660401c1615951680159081610e05575b6001149081610dfb575b159081610df2575b50610de057600080516020613969833981519152805467ffffffffffffffff19166001179055610d6c9385610dbb575b6044359161104c565b610d7257005b600080516020613969833981519152805460ff60401b19169055604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a1005b600080516020613969833981519152805460ff60401b1916600160401b179055610d63565b60405163f92ee8a960e01b8152600490fd5b90501538610d33565b303b159150610d2b565b869150610d21565b346101de5760003660031901126101de576000805160206138e9833981519152546040516001600160a01b039091168152602090f35b346101de5761077a610e7c610e57366108a8565b9594938694610e7760018060a09795971b0360025460401c1633146113d7565b611710565b506137dd565b346101de5760003660031901126101de576020600354604051908152f35b346101de57610eae36610b42565b90610eca60018060a09695961b0360025460401c1633146113d7565b60005b835181101561077a5780610ee4610eef9287611451565b5151610ef457611427565b610ecd565b610f158484610f038489611451565b51610f0e858b611451565b519061215a565b50610b3d610f238288611451565b51613830565b346101de5760203660031901126101de5761077a610f4561087c565b610f4d610f9f565b610fd8565b346101de5760003660031901126101de57602063ffffffff60075416604051908152f35b346101de5760003660031901126101de576000546040516001600160a01b039091168152602090f35b6000805160206138e9833981519152546001600160a01b03163303610fc057565b60405163118cdaa760e01b8152336004820152602490fd5b6001600160a01b03908116908115611033576000805160206138e983398151915280546001600160a01b031981168417909155167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a3565b604051631e4fbdf760e01b815260006004820152602490fd5b6001600160401b03929363ffffffff9195929560018060a01b03166bffffffffffffffffffffffff60a01b6000541617600055600254946001551663ffffffff196007541617600755600160401b600160e01b039060401b1692169063ffffffff60e01b1617176002556110be6110d1565b6110c66110d1565b6110cf33610fd8565b565b60ff6000805160206139698339815191525460401c16156110ee57565b604051631afcd79f60e31b8152600490fd5b601f811161110c575050565b60009060048252600080516020613929833981519152906020601f850160051c83019410611155575b601f0160051c01915b82811061114a57505050565b81815560010161113e565b9092508290611135565b601f811161116b575050565b600090600582526000805160206138c9833981519152906020601f850160051c830194106111b4575b601f0160051c01915b8281106111a957505050565b81815560010161119d565b9092508290611194565b9081516001600160401b038111610214576111e3816111de6005546105d6565b61115f565b602080601f831160011461121f5750819293600092611214575b50508160011b916000199060031b1c191617600555565b0151905038806111fd565b90601f1983169461124060056000526000805160206138c983398151915290565b926000905b87821061127d575050836001959610611264575b505050811b01600555565b015160001960f88460031b161c19169055388080611259565b80600185968294968601518155019501930190611245565b600554600092916112a5826105d6565b8082529160019081811690811561130a57506001146112c357505050565b9192935060056000526000805160206138c9833981519152916000925b8484106112f257505060209250010190565b805460208585018101919091529093019281016112e0565b915050602093945060ff929192191683830152151560051b010190565b604081526000600454611339816105d6565b9081604085015260019081811690816000146113b2575060011461136b575b5050816020610669938303910152611295565b6004600090815292506000805160206139298339815191525b82841061139c57505050810160600161066938611358565b8054606085870101526020909301928101611384565b9050610669949350606092915060ff191682840152151560051b820101909138611358565b156113de57565b60405162461bcd60e51b815260206004820152600b60248201526a27b7363c903937baba32b960a91b6044820152606490fd5b634e487b7160e01b600052601160045260246000fd5b60001981146114365760010190565b611411565b634e487b7160e01b600052603260045260246000fd5b80518210156114655760209160051b010190565b61143b565b9061147d60209282815194859201610610565b0190565b6040519061148e826101f9565b60078252666c6973743a205b60c81b6020830152565b60226110cf9193929360405194816114c6879351809260208087019101610610565b820190602760f81b918260208201526114e9825180936020602185019101610610565b01906021820152036002810185520183610234565b60001981019190821161143657565b601f1981019190821161143657565b906110cf60216040518461153a829651809260208086019101610610565b8101600b60fa1b6020820152036001810185520183610234565b906110cf602160405184611572829651809260208086019101610610565b8101605d60f81b6020820152036001810185520183610234565b906103e89182810292818404149015171561143657565b908160011b918083046002149015171561143657565b919360726110cf946116ae9397966040519889966c6f776e65725f6e616d653a202760981b60208901526115f7815180926020602d8c019101610610565b870172272c20636f6e74726163745f6e616d653a202760681b602d820152611629825180936020604085019101610610565b017404e5840d8c2e6e8bee8f07440dccaee4088c2e8ca5605b1b604082015261165c825180936020605585019101610610565b0173292c202061637469766174655f646174653a202760601b605582015261168e825180936020606985019101610610565b016116a760698201680819185e4a1cca49cb60ba1b9052565b019061146a565b03601f198101845283610234565b6110cf9193929360405194859183516116dd81602096878088019101610610565b83016116f182518093878085019101610610565b0161170482518093868085019101610610565b01038085520183610234565b9294909591604051906b52656d696e646572202d205b60a01b60208301526117756040838a51611748818d6020602c86019101610610565b8101732e902732b0b934b7339020b1ba34bb30ba34b7b760611b602c820152036020810185520183610234565b61177d611481565b946000955b87518710156117f0576117b7906117b16117ac61179f8a8c611451565b516001600160a01b031690565b611a84565b906114a4565b95866117c389516114fe565b82106117da575b506117d490611427565b95611782565b6117d49197506117e99061151c565b96906117ca565b61184897506118339394965097611839959961182d6201518061182661182161181b6106699e611554565b9761158c565b611941565b9304611941565b926115b9565b92611bdb565b90611842611e62565b916116bc565b612929565b60405190606082018281106001600160401b0382111761021457604052602a8252604082602036910137565b60405190611886826101f9565b6007825260203681840137565b9061189d82610255565b6118aa6040519182610234565b82815280926118bb601f1991610255565b0190602036910137565b626d8f486118d1611879565b90602782015b6000190190600a906f181899199a1a9b1b9c1cb0b131b232b360811b8282061a83530490816118d757505090565b626d8f296118d1611879565b626d8f176118d1611879565b626d8ef36118d1611879565b626d8ede6118d1611879565b626d8ed46118d1611879565b806000917a184f03e93ff9f4daa797ed6e38ed64bf6a1f01000000000000000080821015611a76575b506d04ee2d6d415b85acef810000000080831015611a67575b50662386f26fc1000080831015611a58575b506305f5e10080831015611a49575b5061271080831015611a3a575b506064821015611a2a575b600a80921015611a20575b6001908160216119d8828701611893565b95860101905b6119ea575b5050505090565b600019019083906f181899199a1a9b1b9c1cb0b131b232b360811b8282061a835304918215611a1b579190826119de565b6119e3565b91600101916119c7565b91906064600291049101916119bc565b600491939204910191386119b1565b600891939204910191386119a4565b60109193920491019138611995565b60209193920491019138611983565b60409350810491503861196a565b6001600160a01b031680611a9661184d565b916030611aa284611b41565b536078611aae84611b4e565b5360295b60018111611ae45750611ac3575090565b60405163e22e27eb60e01b8152600481019190915260146024820152604490fd5b90600f811690601082101561146557611b21916f181899199a1a9b1b9c1cb0b131b232b360811b901a611b178487611b5e565b5360041c91611b6f565b611ab2565b906020820180921161143657565b9190820180921161143657565b8051156114655760200190565b8051600110156114655760210190565b908151811015611465570160200190565b8015611436576000190190565b7f5b207b2046726f6d3a207b456d61696c3a20277468616f2e6e677579656e334081527f736f746174656b2e636f6d272c204e616d653a2027313031303220506c6174666020820152661bdc9b49cb1f4b60ca1b604082015260470190565b9060405190611be982610219565b60588252600080516020613989833981519152602083019081526000805160206139098339815191526040840152600080516020613949833981519152606084015292611c346118c5565b90604051948594602086016000805160206138a983398151915290526040860174696c6a65742e636f6d2f76332e312f73656e64273b60581b90526055860179031b7b739ba1030baba342432b0b232b9101e9013a130b9b4b1960351b9052519081606f8701611ca392610610565b8401606f8101611cb79061273b60f01b9052565b7f636f6e737420656d61696c44617461203d207b204d657373616765733a2000006071820152608f01611ce990611b7c565b6e546f3a205b207b456d61696c3a202760881b8152600f01611d0a9161146a565b6e09cb0813985b594e89c9cb1f4b174b608a1b81526b02a32b6b83630ba32a4a21d160a51b600f820152601b01611d409161146a565b780b0815195b5c1b185d1953185b99dd5859d94e881d1c9d594b603a1b8152695375626a6563743a202760b01b6019820152602301611d7e9161146a565b6109cb60f21b81526b5661726961626c65733a207b60a01b60028201520360111981018252600e016106699082610234565b9060405190611dbe82610219565b60588252600080516020613989833981519152602083019081526000805160206139098339815191526040840152600080516020613949833981519152606084015292611c34611905565b9060405190611e1782610219565b60588252600080516020613989833981519152602083019081526000805160206139098339815191526040840152600080516020613949833981519152606084015292611c34611911565b604051677d2c7d2c5d2c7d3b60c01b60208201527f636f6e737420726573706f6e7365203d2061776169742046756e6374696f6e736028820152712e6d616b654874747052657175657374287b60701b60488201526f08081d5c9b0e88195b585a5b1554930b60821b605a8201527008081b595d1a1bd90e8809d413d4d509cb607a1b606a8201527f2020686561646572733a207b2027436f6e74656e742d54797065273a20276170607b8201527f706c69636174696f6e2f6a736f6e272c2027417574686f72697a6174696f6e27609b8201526e0e88185d5d1a12195859195c881f4b608a1b60bb820152702020646174613a20656d61696c4461746160781b60ca820152627d293b60e81b60db8201527f69662028726573706f6e73652e6572726f7229207468726f77204572726f722860de8201527f604661696c656420746f2073656e6420656d61696c3a20247b4a534f4e2e737460fe8201527472696e6769667928726573706f6e7365297d60293b60581b61011e8201527f72657475726e2046756e6374696f6e732e656e636f6465537472696e672827456101338201526c6d61696c2073656e742127293b60981b610153820152906110cf8261016081016116ae565b611848926106699461215560586118399461210c96604051956c476574205265616479202d205b60981b60208801526120b0825191611821604d8a602087019561207a81602d840189610610565b81017f5d2057696c6c20426520526561647920746f20416374697661746520536f6f6e602d82015203602d81018c52018a610234565b91604051998a946b62656e655f6e616d653a202760a01b60208701526120e0815180926020602c8a019101610610565b85019172272c20636f6e74726163745f6e616d653a202760681b602c840152518093603f840190610610565b017f272c2020785f6461795f6265666f72655f6163746976653a2000000000000000603f8201526121468251809360208785019101610610565b01036038810187520185610234565b611db0565b6118489261066994926122ac605a61183994604051947f52656d696e646572202d205365636f6e642d4c696e652041637469766174696f6020870152686e20666f72202d205b60b81b60408701526121ee8151986118216056898c6121c8602088019e8f6049850190610610565b81016c5d20417070726f616368696e6760981b604982015203603681018b520189610234565b906040519889936b62656e655f6e616d653a202760a01b602086015261221e815180926020602c89019101610610565b840161225a6109cb60f21b9384602c8401527320202020636f6e74726163745f6e616d653a202760601b602e8401525180936042840190610610565b019060428201526c20202020785f646179733a202760981b604482015261228b825180936020605185019101610610565b01680819185e4a1cca49cb60ba1b605182015203603a810187520185610234565b611e09565b906110cf604760405180947f596f75204d617920536f6f6e20426520456c696769626c6520746f204163746960208301526576617465205b60d01b6040830152612305815180926020604686019101610610565b8101605d60f81b6046820152036027810185520183610234565b90919261232b846122b1565b9061233590611941565b9260409485519485916020958684016b62656e655f6e616d653a202760a01b90528051908188602c870192019161236b92610610565b8301602c810173272c2020636f6e74726163745f6e616d653a202760601b905281519182888b840192019161239f92610610565b018781016b272c20785f646179733a202760a01b90528151918287604c84019201916123ca92610610565b01604c810167206461792873292760c01b9052036034810185526054016123f19085610234565b8451906123fd82610219565b6058825260008051602061398983398151915284830190815260008051602061390983398151915287840152600080516020613949833981519152606084015261244561191d565b92875197889687016000805160206138a98339815191529052860174696c6a65742e636f6d2f76332e312f73656e64273b60581b90526055860179031b7b739ba1030baba342432b0b232b9101e9013a130b9b4b1960351b9052519081606f87016124af92610610565b8401606f81016124c39061273b60f01b9052565b7f636f6e737420656d61696c44617461203d207b204d657373616765733a2000006071820152608f016124f590611b7c565b6e546f3a205b207b456d61696c3a202760881b8152600f016125169161146a565b6e09cb0813985b594e89c9cb1f4b174b608a1b81526b02a32b6b83630ba32a4a21d160a51b600f820152601b0161254c9161146a565b780b0815195b5c1b185d1953185b99dd5859d94e881d1c9d594b603a1b8152695375626a6563743a202760b01b601982015260230161258a9161146a565b6109cb60f21b81526b5661726961626c65733a207b60a01b60028201520360111981018352600e016125bc9083610234565b6125c4611e62565b906125ce926116bc565b61066990612929565b6056906110cf9294936040519586926b62656e655f6e616d653a202760a01b602085015261260f815180926020602c88019101610610565b830173272c2020636f6e74726163745f6e616d653a202760601b602c820152612642825180936020604085019101610610565b016c272c2020785f646179733a202760981b604082015261266d825180936020604d85019101610610565b01680819185e4a1cca49cb60ba1b604d820152036036810185520183610234565b92919092604091825193602085017f52656d696e646572202d2054686972642d4c696e652041637469766174696f6e90528385016520666f72205b60d01b9052848251604682018160208601916126e492610610565b8101604681016c5d20417070726f616368696e6760981b9052036033810186526053016127119086610234565b61271a90611941565b90612724926125d7565b9181519361273185610219565b60588552600080516020613989833981519152602086019081526000805160206139098339815191528487015260008051602061394983398151915260608701529061277b611929565b918451968795602087016000805160206138a98339815191529052860174696c6a65742e636f6d2f76332e312f73656e64273b60581b90526055860179031b7b739ba1030baba342432b0b232b9101e9013a130b9b4b1960351b9052519081606f87016124af92610610565b9092916127f3816122b1565b926127fd90611941565b90612807926125d7565b906040519061281582610219565b60588252600080516020613989833981519152602083019081526000805160206139098339815191526040840152600080516020613949833981519152606084015293612860611935565b90604051958694602086016000805160206138a983398151915290526040860174696c6a65742e636f6d2f76332e312f73656e64273b60581b90526055860179031b7b739ba1030baba342432b0b232b9101e9013a130b9b4b1960351b9052519081606f87016124af92610610565b908160209103126101de575190565b9061290b6080936001600160401b0363ffffffff939897969816845260a0602085015260a0840190610633565b95600160408401521660608201520152565b6040513d6000823e3d90fd5b60405160e081018181106001600160401b038211176102145760405261297b60009283835283602084015283604084015260608084015260606080840152606060a0840152606060c084015282612d43565b81546020906129a090612994906001600160a01b031681565b6001600160a01b031690565b6129bb6129b56002546001600160401b031690565b93612b75565b906129cb60075463ffffffff1690565b9185600154956129f16040519788968795869463230e93b160e11b8652600486016128de565b03925af1908115612a4057612a0c9291612a12575b50600355565b60035490565b612a33915060203d8111612a39575b612a2b8183610234565b8101906128cf565b38612a06565b503d612a21565b61291d565b60405190612a52826101f9565b600c82526b31b7b232a637b1b0ba34b7b760a11b6020830152565b634e487b7160e01b600052602160045260246000fd5b60031115612a8d57565b612a6d565b60405190612a9f826101f9565b60088252676c616e677561676560c01b6020830152565b60011115612a8d57565b60405190612acd826101f9565b6006825265736f7572636560d01b6020830152565b60405190612aef826101f9565b60048252636172677360e01b6020830152565b60405190612b0f826101f9565b600f82526e39b2b1b932ba39a637b1b0ba34b7b760891b6020830152565b60405190612b3a826101f9565b60078252667365637265747360c81b6020830152565b60405190612b5d826101f9565b600982526862797465734172677360b81b6020830152565b612b7d612d86565b90612b8f612b89612a45565b8361349e565b612bac8151612b9d81612a83565b612ba681612a83565b83612e28565b612bb7612b89612a92565b612bd16040820151612bc881612ab6565b612ba681612ab6565b612bdc612b89612ac0565b612bea60608201518361349e565b60a08101805151612cea575b506080810190815151612c6a575b60c0915001805151612c17575b50515190565b91612c23612b89612b50565b612c2c82613522565b60005b83518051821015612c575790610b3d612c4b82612c5294611451565b51856133e9565b612c2f565b50509150612c64816135ae565b38612c11565b602081018051612c7981612a83565b612c8281612a83565b15612cd85760c092612cbb612cd392612ca2612c9c612b02565b8861349e565b51612cac81612a83565b612cb581612a83565b86612e28565b612ccc612cc6612b2d565b8661349e565b51846133e9565b612c04565b60405163a80d31f760e01b8152600490fd5b92612cfc612cf6612ae2565b8461349e565b612d0583613522565b60005b84518051821015612d305790610b3d612d2482612d2b94611451565b518661349e565b612d08565b50509250612d3d826135ae565b38612bf6565b815115612d5a576000808252604082015260600152565b6040516322ce3edd60e01b8152600490fd5b60405190612d79826101f9565b6000602083606081520152565b604051612d92816101f9565b612d9a612d6c565b8082526020820160008152612dad612d6c565b5061010060208301526040518092526000825261012082019182106101de576000916040525290565b90612ddf612d6c565b50601f811680612e0e575b50806020830152604051908183526000825281016020019081106101de5760405290565b602003602081116114365781018091116114365738612dea565b90815191612e34612d6c565b508251516001810190818111611436576020850151811015612e8d575b60c260206110cf9651928301015380518211612e85575b505060405191602083015260208252612e80826101f9565b6133e9565b523880612e68565b8160011b948286046002148315171561143657602081612ebf6110cf98612eb860c295519184612dd6565b5082613331565b5096505050612e51565b612ed1612d6c565b508051516001810190818111611436576020830151811015612f0a575b605b60208451928301015380518211612f0657505090565b5290565b8160011b8281046002148315171561143657612f3390612f2c85519186612dd6565b5084613331565b50612eee565b612f41612d6c565b508051516001810190818111611436576020830151811015612f76575b605a60208451928301015380518211612f0657505090565b8160011b8281046002148315171561143657612f9890612f2c85519186612dd6565b50612f5e565b612fa6612d6c565b508051516001810190818111611436576020830151811015612fdb575b605960208451928301015380518211612f0657505090565b8160011b8281046002148315171561143657612ffd90612f2c85519186612dd6565b50612fc3565b61300b612d6c565b508051516001810190818111611436576020830151811015613040575b605860208451928301015380518211612f0657505090565b8160011b828104600214831517156114365761306290612f2c85519186612dd6565b50613028565b613070612d6c565b5080515160018101908181116114365760208301518110156130a5575b607b60208451928301015380518211612f0657505090565b8160011b82810460021483151715611436576130c790612f2c85519186612dd6565b5061308d565b6130d5612d6c565b50805151600181019081811161143657602083015181101561310a575b607a60208451928301015380518211612f0657505090565b8160011b828104600214831517156114365761312c90612f2c85519186612dd6565b506130f2565b61313a612d6c565b50805151600181019081811161143657602083015181101561316f575b607960208451928301015380518211612f0657505090565b8160011b828104600214831517156114365761319190612f2c85519186612dd6565b50613157565b61319f612d6c565b5080515160018101908181116114365760208301518110156131d4575b607860208451928301015380518211612f0657505090565b8160011b82810460021483151715611436576131f690612f2c85519186612dd6565b506131bc565b90613205612d6c565b508151516001810191828211611436576020840151821015613238575b60208451928301015380518211612f0657505090565b8260011b83810460021484151715611436576132619061325a86519187612dd6565b5085613331565b50613222565b9061327482519183612dd6565b5061327d612d6c565b50805190613289612d6c565b5061329781518311156133e2565b825151926132a58385611b34565b91602092828480940151821161331a575b5183815197820101968211613312575b505001915b818110156132ec5760001991036101000a0190811990511690825116179052565b919261330761330161330d9286518152611b26565b94611b26565b9261150d565b6132cb565b5238806132c6565b61332c613326836115a3565b82613267565b6132b6565b9061333a612d6c565b508051613345612d6c565b5061335382518211156133e2565b825151916133618284611b34565b60209182918287015181116133cb575b8651838151978201019682116133c3575b505001915b818110156133a95760001991036101000a019081199051169082511617905290565b91926133076133016133be9286518152611b26565b613387565b523880613382565b6133dd6133d7826115a3565b88613267565b613371565b156101de57565b81516134209291906001600160401b0381169060178211613423576134189150604060ff8451921617906131fc565b505b51613331565b50565b5060ff8111613448576134429061343a8351613003565b508251613777565b5061341a565b61ffff8111613467576134429061345f8351612f9e565b508251613710565b63ffffffff811161348857613442906134808351612f39565b5082516136a7565b613442906134968351612ec9565b50825161363b565b81516134209291906001600160401b03811690601782116134cd576134189150606060ff8451921617906131fc565b5060ff81116134e4576134429061343a8351613197565b61ffff81116134fb576134429061345f8351613132565b63ffffffff8111613514576134429061348083516130cd565b613442906134968351613068565b80519061352d612d6c565b50815151600181019081811161143657602084015181101561357b575b609f6020809551928301015380518211613573575b505001805190600182018092116114365752565b52388061355f565b8160011b9382850460021483151715611436576020816135a48297612eb8609f95519184612dd6565b509550505061354a565b8051906135b9612d6c565b508151516001810190818111611436576020840151811015613608575b60ff6020809551928301015380518211613600575b50500180516000198101919082116114365752565b5238806135eb565b8160011b9382850460021483151715611436576020816136318297612eb860ff95519184612dd6565b50955050506135d6565b90613644612d6c565b508151518060080191826008116114365760208401518311613686575b6008845192830101906001600160401b031982511617905280518211612f0657505090565b8260011b83810460021484151715611436576136a29085613267565b613661565b906136b0612d6c565b5081515180600401918260041161143657602084015183116136ef575b60048451928301019063ffffffff1982511617905280518211612f0657505090565b8260011b838104600214841517156114365761370b9085613267565b6136cd565b90613719612d6c565b508151518060020191826002116114365760208401518311613756575b60028451928301019061ffff1982511617905280518211612f0657505090565b8260011b83810460021484151715611436576137729085613267565b613736565b90613780612d6c565b5081515180600101918260011161143657602084015183116137bc575b60018451928301019060ff1982511617905280518211612f0657505090565b8260011b83810460021484151715611436576137d89085613267565b61379d565b6138247fe945c25e663b7f927fca5b167e9d99e30aac67d2f2c39fac12b6618f57481e929161380d600654611427565b600655604051918291604083526040830190610633565b600160208301520390a1565b6138607fe945c25e663b7f927fca5b167e9d99e30aac67d2f2c39fac12b6618f57481e929161380d600654611427565b600260208301520390a1565b61389c7fe945c25e663b7f927fca5b167e9d99e30aac67d2f2c39fac12b6618f57481e929161380d600654611427565b600360208301520390a156fe636f6e737420656d61696c55524c203d202768747470733a2f2f6170692e6d61036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db09016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c1993004f44417a596a45334f5449365a44526c4d44526a4d6d55314d54646d4e57517a8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b4d6a41344e6a6869596d49334f5451345a545a694d7a6b3d0000000000000000f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a004f474e6c595749324e47466d5a5445784e57526959574a694d5468684e47517aa2646970667358221220fc8b1bfaf64db7bd92c765e12a0472c28297594116caa9bb1752d2569016e90364736f6c63430008140033

Deployed Bytecode

0x6080604052600436101561001257600080fd5b60003560e01c806309c1ba2e146101b75780630ca76175146101b257806313bac909146101ad57806313f195c0146101a8578063202a4b3f146101a35780633944ea3a1461019e57806340761ad61461019957806341a8af3c146101945780634776258a1461018f578063485786bd1461018a5780634b0795a8146101855780635953951b146101805780635b5dc0f61461017b578063688f16f2146101765780636c8ae395146101715780636e74336b1461016c578063715018a6146101675780637dad97d11461016257806385de98021461015d5780638da5cb5b1461015857806390de99b714610153578063b1e217491461014e578063eab3252b14610149578063f2fde38b14610144578063f68016b71461013f5763f887ea401461013a57600080fd5b610f76565b610f52565b610f29565b610ea0565b610e82565b610e43565b610e0d565b610cb6565b610c98565b610c2d565b610c0f565b610b86565b610a60565b6109a5565b610986565b6107d0565b6107b4565b610798565b61077c565b61073f565b61066c565b6105ab565b61058f565b6104b3565b6102b7565b346101de5760003660031901126101de5760206001600160401b0360025416604051908152f35b600080fd5b634e487b7160e01b600052604160045260246000fd5b604081019081106001600160401b0382111761021457604052565b6101e3565b608081019081106001600160401b0382111761021457604052565b90601f801991011681019081106001600160401b0382111761021457604052565b6001600160401b03811161021457601f01601f191660200190565b81601f820112156101de5780359061028782610255565b926102956040519485610234565b828452602083830101116101de57816000926020809301838601378301015290565b346101de5760603660031901126101de576001600160401b0360048035906024358381116101de576102ec9036908301610270565b906044358481116101de576103049036908301610270565b9060009460018060a01b03865416330361046f5784600354036104575783519081116102145761033d8161033884546105d6565b611100565b602080601f83116001146103d6575081906103729588926103cb575b50508160011b916000199060031b1c19161790556111be565b807f7873807bf6ddc50401cd3d29bbe0decee23fd4d68d273f4b5eb83cded4d2f172604051806103a181611327565b0390a27f85e1543bf2f84fe80c6badbce3648c8539ad1df4d2b3d822938ca0538be727e68280a280f35b015190503880610359565b91929394601f1984166103f9600460005260008051602061392983398151915290565b9389905b82821061043f5750509160019391856103729897969410610426575b505050811b0190556111be565b015160001960f88460031b161c19169055388080610419565b806001869782949787015181550196019401906103fd565b60405163d068bf5b60e01b8152808301869052602490fd5b60405162461bcd60e51b8152602081840152601760248201527f4f6e6c7920726f757465722063616e2066756c66696c6c0000000000000000006044820152606490fd5b346101de5760803660031901126101de576001600160401b036004358181116101de576104e4903690600401610270565b906024358181116101de576104fd903690600401610270565b6064359182116101de5760209261051b610525933690600401610270565b916044359161202c565b604051908152f35b60806003198201126101de576001600160401b03916004358381116101de578261055991600401610270565b926024358181116101de578361057191600401610270565b926044359182116101de5761058891600401610270565b9060643590565b346101de5760206105256105a23661052d565b9291909161268e565b346101de5760003660031901126101de576002546040805191901c6001600160a01b03168152602090f35b90600182811c92168015610606575b60208310146105f057565b634e487b7160e01b600052602260045260246000fd5b91607f16916105e5565b60005b8381106106235750506000910152565b8181015183820152602001610613565b9060209161064c81518092818552858086019101610610565b601f01601f1916010190565b906020610669928181520190610633565b90565b346101de5760008060031936011261073c57604051908060045461068f816105d6565b8085529160019180831690811561071257506001146106c9575b6106c5856106b981870382610234565b60405191829182610658565b0390f35b9250600483526000805160206139298339815191525b8284106106fa5750505081016020016106b9826106c56106a9565b805460208587018101919091529093019281016106df565b8695506106c5969350602092506106b994915060ff191682840152151560051b82010192936106a9565b80fd5b346101de5761077a6107746107533661052d565b9180949361076f60018060a01b0360025460401c1633146113d7565b61231f565b50613830565b005b346101de57602061052561078f3661052d565b9291909161231f565b346101de5760206105256107ab3661052d565b929190916127e7565b346101de5760206105256107c73661052d565b9291909161215a565b346101de5760008060031936011261073c5760405190806005546107f3816105d6565b80855291600191808316908115610712575060011461081c576106c5856106b981870382610234565b9250600583526000805160206138c98339815191525b82841061084d5750505081016020016106b9826106c56106a9565b80546020858701810191909152909301928101610832565b6001600160401b0381116102145760051b60200190565b600435906001600160a01b03821682036101de57565b608435906001600160a01b03821682036101de57565b60c06003198201126101de576001600160401b03916004358381116101de57826108d491600401610270565b926024358181116101de57836108ec91600401610270565b9260443592606435926084358181116101de57836023820112156101de57806004013561091881610865565b916109266040519384610234565b81835260209160248385019160051b830101918783116101de57602401905b82821061096757505050509260a4359182116101de5761066991600401610270565b81356001600160a01b03811681036101de578152908301908301610945565b346101de576020610525610999366108a8565b94939093929192611710565b346101de5761077a6109da6109b93661052d565b918094936109d560018060a01b0360025460401c1633146113d7565b6127e7565b5061386c565b9080601f830112156101de578135906109f882610865565b92610a066040519485610234565b828452602092838086019160051b830101928084116101de57848301915b848310610a345750505050505090565b82356001600160401b0381116101de578691610a5584848094890101610270565b815201920191610a24565b346101de5760803660031901126101de576001600160401b036004358181116101de57610a919036906004016109e0565b6024358281116101de57610aa9903690600401610270565b604435926064359081116101de57610ac59036906004016109e0565b92610ade60018060a01b0360025460401c1633146113d7565b60005b835181101561077a5780610af8610b039287611451565b5151610b0857611427565b610ae1565b610b29610b158287611451565b518486610b22858b611451565b519261202c565b50610b3d610b378288611451565b516137dd565b611427565b60806003198201126101de576001600160401b03916004358381116101de5782610b6e916004016109e0565b926024358181116101de5783610571916004016109e0565b346101de57610b9436610b42565b90610bb060018060a09695961b0360025460401c1633146113d7565b60005b835181101561077a5780610bca610bd59287611451565b5151610bda57611427565b610bb3565b610bfb8484610be98489611451565b51610bf4858b611451565b519061268e565b50610b3d610c098288611451565b5161386c565b346101de5760003660031901126101de576020600154604051908152f35b346101de5760008060031936011261073c57610c47610f9f565b6000805160206138e983398151915280546001600160a01b0319811690915581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b346101de5760003660031901126101de576020600654604051908152f35b346101de5760a03660031901126101de57610ccf61087c565b6024356001600160401b039182821682036101de5760643563ffffffff811681036101de57610cfc610892565b91600080516020613969833981519152549460ff8660401c1615951680159081610e05575b6001149081610dfb575b159081610df2575b50610de057600080516020613969833981519152805467ffffffffffffffff19166001179055610d6c9385610dbb575b6044359161104c565b610d7257005b600080516020613969833981519152805460ff60401b19169055604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a1005b600080516020613969833981519152805460ff60401b1916600160401b179055610d63565b60405163f92ee8a960e01b8152600490fd5b90501538610d33565b303b159150610d2b565b869150610d21565b346101de5760003660031901126101de576000805160206138e9833981519152546040516001600160a01b039091168152602090f35b346101de5761077a610e7c610e57366108a8565b9594938694610e7760018060a09795971b0360025460401c1633146113d7565b611710565b506137dd565b346101de5760003660031901126101de576020600354604051908152f35b346101de57610eae36610b42565b90610eca60018060a09695961b0360025460401c1633146113d7565b60005b835181101561077a5780610ee4610eef9287611451565b5151610ef457611427565b610ecd565b610f158484610f038489611451565b51610f0e858b611451565b519061215a565b50610b3d610f238288611451565b51613830565b346101de5760203660031901126101de5761077a610f4561087c565b610f4d610f9f565b610fd8565b346101de5760003660031901126101de57602063ffffffff60075416604051908152f35b346101de5760003660031901126101de576000546040516001600160a01b039091168152602090f35b6000805160206138e9833981519152546001600160a01b03163303610fc057565b60405163118cdaa760e01b8152336004820152602490fd5b6001600160a01b03908116908115611033576000805160206138e983398151915280546001600160a01b031981168417909155167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a3565b604051631e4fbdf760e01b815260006004820152602490fd5b6001600160401b03929363ffffffff9195929560018060a01b03166bffffffffffffffffffffffff60a01b6000541617600055600254946001551663ffffffff196007541617600755600160401b600160e01b039060401b1692169063ffffffff60e01b1617176002556110be6110d1565b6110c66110d1565b6110cf33610fd8565b565b60ff6000805160206139698339815191525460401c16156110ee57565b604051631afcd79f60e31b8152600490fd5b601f811161110c575050565b60009060048252600080516020613929833981519152906020601f850160051c83019410611155575b601f0160051c01915b82811061114a57505050565b81815560010161113e565b9092508290611135565b601f811161116b575050565b600090600582526000805160206138c9833981519152906020601f850160051c830194106111b4575b601f0160051c01915b8281106111a957505050565b81815560010161119d565b9092508290611194565b9081516001600160401b038111610214576111e3816111de6005546105d6565b61115f565b602080601f831160011461121f5750819293600092611214575b50508160011b916000199060031b1c191617600555565b0151905038806111fd565b90601f1983169461124060056000526000805160206138c983398151915290565b926000905b87821061127d575050836001959610611264575b505050811b01600555565b015160001960f88460031b161c19169055388080611259565b80600185968294968601518155019501930190611245565b600554600092916112a5826105d6565b8082529160019081811690811561130a57506001146112c357505050565b9192935060056000526000805160206138c9833981519152916000925b8484106112f257505060209250010190565b805460208585018101919091529093019281016112e0565b915050602093945060ff929192191683830152151560051b010190565b604081526000600454611339816105d6565b9081604085015260019081811690816000146113b2575060011461136b575b5050816020610669938303910152611295565b6004600090815292506000805160206139298339815191525b82841061139c57505050810160600161066938611358565b8054606085870101526020909301928101611384565b9050610669949350606092915060ff191682840152151560051b820101909138611358565b156113de57565b60405162461bcd60e51b815260206004820152600b60248201526a27b7363c903937baba32b960a91b6044820152606490fd5b634e487b7160e01b600052601160045260246000fd5b60001981146114365760010190565b611411565b634e487b7160e01b600052603260045260246000fd5b80518210156114655760209160051b010190565b61143b565b9061147d60209282815194859201610610565b0190565b6040519061148e826101f9565b60078252666c6973743a205b60c81b6020830152565b60226110cf9193929360405194816114c6879351809260208087019101610610565b820190602760f81b918260208201526114e9825180936020602185019101610610565b01906021820152036002810185520183610234565b60001981019190821161143657565b601f1981019190821161143657565b906110cf60216040518461153a829651809260208086019101610610565b8101600b60fa1b6020820152036001810185520183610234565b906110cf602160405184611572829651809260208086019101610610565b8101605d60f81b6020820152036001810185520183610234565b906103e89182810292818404149015171561143657565b908160011b918083046002149015171561143657565b919360726110cf946116ae9397966040519889966c6f776e65725f6e616d653a202760981b60208901526115f7815180926020602d8c019101610610565b870172272c20636f6e74726163745f6e616d653a202760681b602d820152611629825180936020604085019101610610565b017404e5840d8c2e6e8bee8f07440dccaee4088c2e8ca5605b1b604082015261165c825180936020605585019101610610565b0173292c202061637469766174655f646174653a202760601b605582015261168e825180936020606985019101610610565b016116a760698201680819185e4a1cca49cb60ba1b9052565b019061146a565b03601f198101845283610234565b6110cf9193929360405194859183516116dd81602096878088019101610610565b83016116f182518093878085019101610610565b0161170482518093868085019101610610565b01038085520183610234565b9294909591604051906b52656d696e646572202d205b60a01b60208301526117756040838a51611748818d6020602c86019101610610565b8101732e902732b0b934b7339020b1ba34bb30ba34b7b760611b602c820152036020810185520183610234565b61177d611481565b946000955b87518710156117f0576117b7906117b16117ac61179f8a8c611451565b516001600160a01b031690565b611a84565b906114a4565b95866117c389516114fe565b82106117da575b506117d490611427565b95611782565b6117d49197506117e99061151c565b96906117ca565b61184897506118339394965097611839959961182d6201518061182661182161181b6106699e611554565b9761158c565b611941565b9304611941565b926115b9565b92611bdb565b90611842611e62565b916116bc565b612929565b60405190606082018281106001600160401b0382111761021457604052602a8252604082602036910137565b60405190611886826101f9565b6007825260203681840137565b9061189d82610255565b6118aa6040519182610234565b82815280926118bb601f1991610255565b0190602036910137565b626d8f486118d1611879565b90602782015b6000190190600a906f181899199a1a9b1b9c1cb0b131b232b360811b8282061a83530490816118d757505090565b626d8f296118d1611879565b626d8f176118d1611879565b626d8ef36118d1611879565b626d8ede6118d1611879565b626d8ed46118d1611879565b806000917a184f03e93ff9f4daa797ed6e38ed64bf6a1f01000000000000000080821015611a76575b506d04ee2d6d415b85acef810000000080831015611a67575b50662386f26fc1000080831015611a58575b506305f5e10080831015611a49575b5061271080831015611a3a575b506064821015611a2a575b600a80921015611a20575b6001908160216119d8828701611893565b95860101905b6119ea575b5050505090565b600019019083906f181899199a1a9b1b9c1cb0b131b232b360811b8282061a835304918215611a1b579190826119de565b6119e3565b91600101916119c7565b91906064600291049101916119bc565b600491939204910191386119b1565b600891939204910191386119a4565b60109193920491019138611995565b60209193920491019138611983565b60409350810491503861196a565b6001600160a01b031680611a9661184d565b916030611aa284611b41565b536078611aae84611b4e565b5360295b60018111611ae45750611ac3575090565b60405163e22e27eb60e01b8152600481019190915260146024820152604490fd5b90600f811690601082101561146557611b21916f181899199a1a9b1b9c1cb0b131b232b360811b901a611b178487611b5e565b5360041c91611b6f565b611ab2565b906020820180921161143657565b9190820180921161143657565b8051156114655760200190565b8051600110156114655760210190565b908151811015611465570160200190565b8015611436576000190190565b7f5b207b2046726f6d3a207b456d61696c3a20277468616f2e6e677579656e334081527f736f746174656b2e636f6d272c204e616d653a2027313031303220506c6174666020820152661bdc9b49cb1f4b60ca1b604082015260470190565b9060405190611be982610219565b60588252600080516020613989833981519152602083019081526000805160206139098339815191526040840152600080516020613949833981519152606084015292611c346118c5565b90604051948594602086016000805160206138a983398151915290526040860174696c6a65742e636f6d2f76332e312f73656e64273b60581b90526055860179031b7b739ba1030baba342432b0b232b9101e9013a130b9b4b1960351b9052519081606f8701611ca392610610565b8401606f8101611cb79061273b60f01b9052565b7f636f6e737420656d61696c44617461203d207b204d657373616765733a2000006071820152608f01611ce990611b7c565b6e546f3a205b207b456d61696c3a202760881b8152600f01611d0a9161146a565b6e09cb0813985b594e89c9cb1f4b174b608a1b81526b02a32b6b83630ba32a4a21d160a51b600f820152601b01611d409161146a565b780b0815195b5c1b185d1953185b99dd5859d94e881d1c9d594b603a1b8152695375626a6563743a202760b01b6019820152602301611d7e9161146a565b6109cb60f21b81526b5661726961626c65733a207b60a01b60028201520360111981018252600e016106699082610234565b9060405190611dbe82610219565b60588252600080516020613989833981519152602083019081526000805160206139098339815191526040840152600080516020613949833981519152606084015292611c34611905565b9060405190611e1782610219565b60588252600080516020613989833981519152602083019081526000805160206139098339815191526040840152600080516020613949833981519152606084015292611c34611911565b604051677d2c7d2c5d2c7d3b60c01b60208201527f636f6e737420726573706f6e7365203d2061776169742046756e6374696f6e736028820152712e6d616b654874747052657175657374287b60701b60488201526f08081d5c9b0e88195b585a5b1554930b60821b605a8201527008081b595d1a1bd90e8809d413d4d509cb607a1b606a8201527f2020686561646572733a207b2027436f6e74656e742d54797065273a20276170607b8201527f706c69636174696f6e2f6a736f6e272c2027417574686f72697a6174696f6e27609b8201526e0e88185d5d1a12195859195c881f4b608a1b60bb820152702020646174613a20656d61696c4461746160781b60ca820152627d293b60e81b60db8201527f69662028726573706f6e73652e6572726f7229207468726f77204572726f722860de8201527f604661696c656420746f2073656e6420656d61696c3a20247b4a534f4e2e737460fe8201527472696e6769667928726573706f6e7365297d60293b60581b61011e8201527f72657475726e2046756e6374696f6e732e656e636f6465537472696e672827456101338201526c6d61696c2073656e742127293b60981b610153820152906110cf8261016081016116ae565b611848926106699461215560586118399461210c96604051956c476574205265616479202d205b60981b60208801526120b0825191611821604d8a602087019561207a81602d840189610610565b81017f5d2057696c6c20426520526561647920746f20416374697661746520536f6f6e602d82015203602d81018c52018a610234565b91604051998a946b62656e655f6e616d653a202760a01b60208701526120e0815180926020602c8a019101610610565b85019172272c20636f6e74726163745f6e616d653a202760681b602c840152518093603f840190610610565b017f272c2020785f6461795f6265666f72655f6163746976653a2000000000000000603f8201526121468251809360208785019101610610565b01036038810187520185610234565b611db0565b6118489261066994926122ac605a61183994604051947f52656d696e646572202d205365636f6e642d4c696e652041637469766174696f6020870152686e20666f72202d205b60b81b60408701526121ee8151986118216056898c6121c8602088019e8f6049850190610610565b81016c5d20417070726f616368696e6760981b604982015203603681018b520189610234565b906040519889936b62656e655f6e616d653a202760a01b602086015261221e815180926020602c89019101610610565b840161225a6109cb60f21b9384602c8401527320202020636f6e74726163745f6e616d653a202760601b602e8401525180936042840190610610565b019060428201526c20202020785f646179733a202760981b604482015261228b825180936020605185019101610610565b01680819185e4a1cca49cb60ba1b605182015203603a810187520185610234565b611e09565b906110cf604760405180947f596f75204d617920536f6f6e20426520456c696769626c6520746f204163746960208301526576617465205b60d01b6040830152612305815180926020604686019101610610565b8101605d60f81b6046820152036027810185520183610234565b90919261232b846122b1565b9061233590611941565b9260409485519485916020958684016b62656e655f6e616d653a202760a01b90528051908188602c870192019161236b92610610565b8301602c810173272c2020636f6e74726163745f6e616d653a202760601b905281519182888b840192019161239f92610610565b018781016b272c20785f646179733a202760a01b90528151918287604c84019201916123ca92610610565b01604c810167206461792873292760c01b9052036034810185526054016123f19085610234565b8451906123fd82610219565b6058825260008051602061398983398151915284830190815260008051602061390983398151915287840152600080516020613949833981519152606084015261244561191d565b92875197889687016000805160206138a98339815191529052860174696c6a65742e636f6d2f76332e312f73656e64273b60581b90526055860179031b7b739ba1030baba342432b0b232b9101e9013a130b9b4b1960351b9052519081606f87016124af92610610565b8401606f81016124c39061273b60f01b9052565b7f636f6e737420656d61696c44617461203d207b204d657373616765733a2000006071820152608f016124f590611b7c565b6e546f3a205b207b456d61696c3a202760881b8152600f016125169161146a565b6e09cb0813985b594e89c9cb1f4b174b608a1b81526b02a32b6b83630ba32a4a21d160a51b600f820152601b0161254c9161146a565b780b0815195b5c1b185d1953185b99dd5859d94e881d1c9d594b603a1b8152695375626a6563743a202760b01b601982015260230161258a9161146a565b6109cb60f21b81526b5661726961626c65733a207b60a01b60028201520360111981018352600e016125bc9083610234565b6125c4611e62565b906125ce926116bc565b61066990612929565b6056906110cf9294936040519586926b62656e655f6e616d653a202760a01b602085015261260f815180926020602c88019101610610565b830173272c2020636f6e74726163745f6e616d653a202760601b602c820152612642825180936020604085019101610610565b016c272c2020785f646179733a202760981b604082015261266d825180936020604d85019101610610565b01680819185e4a1cca49cb60ba1b604d820152036036810185520183610234565b92919092604091825193602085017f52656d696e646572202d2054686972642d4c696e652041637469766174696f6e90528385016520666f72205b60d01b9052848251604682018160208601916126e492610610565b8101604681016c5d20417070726f616368696e6760981b9052036033810186526053016127119086610234565b61271a90611941565b90612724926125d7565b9181519361273185610219565b60588552600080516020613989833981519152602086019081526000805160206139098339815191528487015260008051602061394983398151915260608701529061277b611929565b918451968795602087016000805160206138a98339815191529052860174696c6a65742e636f6d2f76332e312f73656e64273b60581b90526055860179031b7b739ba1030baba342432b0b232b9101e9013a130b9b4b1960351b9052519081606f87016124af92610610565b9092916127f3816122b1565b926127fd90611941565b90612807926125d7565b906040519061281582610219565b60588252600080516020613989833981519152602083019081526000805160206139098339815191526040840152600080516020613949833981519152606084015293612860611935565b90604051958694602086016000805160206138a983398151915290526040860174696c6a65742e636f6d2f76332e312f73656e64273b60581b90526055860179031b7b739ba1030baba342432b0b232b9101e9013a130b9b4b1960351b9052519081606f87016124af92610610565b908160209103126101de575190565b9061290b6080936001600160401b0363ffffffff939897969816845260a0602085015260a0840190610633565b95600160408401521660608201520152565b6040513d6000823e3d90fd5b60405160e081018181106001600160401b038211176102145760405261297b60009283835283602084015283604084015260608084015260606080840152606060a0840152606060c084015282612d43565b81546020906129a090612994906001600160a01b031681565b6001600160a01b031690565b6129bb6129b56002546001600160401b031690565b93612b75565b906129cb60075463ffffffff1690565b9185600154956129f16040519788968795869463230e93b160e11b8652600486016128de565b03925af1908115612a4057612a0c9291612a12575b50600355565b60035490565b612a33915060203d8111612a39575b612a2b8183610234565b8101906128cf565b38612a06565b503d612a21565b61291d565b60405190612a52826101f9565b600c82526b31b7b232a637b1b0ba34b7b760a11b6020830152565b634e487b7160e01b600052602160045260246000fd5b60031115612a8d57565b612a6d565b60405190612a9f826101f9565b60088252676c616e677561676560c01b6020830152565b60011115612a8d57565b60405190612acd826101f9565b6006825265736f7572636560d01b6020830152565b60405190612aef826101f9565b60048252636172677360e01b6020830152565b60405190612b0f826101f9565b600f82526e39b2b1b932ba39a637b1b0ba34b7b760891b6020830152565b60405190612b3a826101f9565b60078252667365637265747360c81b6020830152565b60405190612b5d826101f9565b600982526862797465734172677360b81b6020830152565b612b7d612d86565b90612b8f612b89612a45565b8361349e565b612bac8151612b9d81612a83565b612ba681612a83565b83612e28565b612bb7612b89612a92565b612bd16040820151612bc881612ab6565b612ba681612ab6565b612bdc612b89612ac0565b612bea60608201518361349e565b60a08101805151612cea575b506080810190815151612c6a575b60c0915001805151612c17575b50515190565b91612c23612b89612b50565b612c2c82613522565b60005b83518051821015612c575790610b3d612c4b82612c5294611451565b51856133e9565b612c2f565b50509150612c64816135ae565b38612c11565b602081018051612c7981612a83565b612c8281612a83565b15612cd85760c092612cbb612cd392612ca2612c9c612b02565b8861349e565b51612cac81612a83565b612cb581612a83565b86612e28565b612ccc612cc6612b2d565b8661349e565b51846133e9565b612c04565b60405163a80d31f760e01b8152600490fd5b92612cfc612cf6612ae2565b8461349e565b612d0583613522565b60005b84518051821015612d305790610b3d612d2482612d2b94611451565b518661349e565b612d08565b50509250612d3d826135ae565b38612bf6565b815115612d5a576000808252604082015260600152565b6040516322ce3edd60e01b8152600490fd5b60405190612d79826101f9565b6000602083606081520152565b604051612d92816101f9565b612d9a612d6c565b8082526020820160008152612dad612d6c565b5061010060208301526040518092526000825261012082019182106101de576000916040525290565b90612ddf612d6c565b50601f811680612e0e575b50806020830152604051908183526000825281016020019081106101de5760405290565b602003602081116114365781018091116114365738612dea565b90815191612e34612d6c565b508251516001810190818111611436576020850151811015612e8d575b60c260206110cf9651928301015380518211612e85575b505060405191602083015260208252612e80826101f9565b6133e9565b523880612e68565b8160011b948286046002148315171561143657602081612ebf6110cf98612eb860c295519184612dd6565b5082613331565b5096505050612e51565b612ed1612d6c565b508051516001810190818111611436576020830151811015612f0a575b605b60208451928301015380518211612f0657505090565b5290565b8160011b8281046002148315171561143657612f3390612f2c85519186612dd6565b5084613331565b50612eee565b612f41612d6c565b508051516001810190818111611436576020830151811015612f76575b605a60208451928301015380518211612f0657505090565b8160011b8281046002148315171561143657612f9890612f2c85519186612dd6565b50612f5e565b612fa6612d6c565b508051516001810190818111611436576020830151811015612fdb575b605960208451928301015380518211612f0657505090565b8160011b8281046002148315171561143657612ffd90612f2c85519186612dd6565b50612fc3565b61300b612d6c565b508051516001810190818111611436576020830151811015613040575b605860208451928301015380518211612f0657505090565b8160011b828104600214831517156114365761306290612f2c85519186612dd6565b50613028565b613070612d6c565b5080515160018101908181116114365760208301518110156130a5575b607b60208451928301015380518211612f0657505090565b8160011b82810460021483151715611436576130c790612f2c85519186612dd6565b5061308d565b6130d5612d6c565b50805151600181019081811161143657602083015181101561310a575b607a60208451928301015380518211612f0657505090565b8160011b828104600214831517156114365761312c90612f2c85519186612dd6565b506130f2565b61313a612d6c565b50805151600181019081811161143657602083015181101561316f575b607960208451928301015380518211612f0657505090565b8160011b828104600214831517156114365761319190612f2c85519186612dd6565b50613157565b61319f612d6c565b5080515160018101908181116114365760208301518110156131d4575b607860208451928301015380518211612f0657505090565b8160011b82810460021483151715611436576131f690612f2c85519186612dd6565b506131bc565b90613205612d6c565b508151516001810191828211611436576020840151821015613238575b60208451928301015380518211612f0657505090565b8260011b83810460021484151715611436576132619061325a86519187612dd6565b5085613331565b50613222565b9061327482519183612dd6565b5061327d612d6c565b50805190613289612d6c565b5061329781518311156133e2565b825151926132a58385611b34565b91602092828480940151821161331a575b5183815197820101968211613312575b505001915b818110156132ec5760001991036101000a0190811990511690825116179052565b919261330761330161330d9286518152611b26565b94611b26565b9261150d565b6132cb565b5238806132c6565b61332c613326836115a3565b82613267565b6132b6565b9061333a612d6c565b508051613345612d6c565b5061335382518211156133e2565b825151916133618284611b34565b60209182918287015181116133cb575b8651838151978201019682116133c3575b505001915b818110156133a95760001991036101000a019081199051169082511617905290565b91926133076133016133be9286518152611b26565b613387565b523880613382565b6133dd6133d7826115a3565b88613267565b613371565b156101de57565b81516134209291906001600160401b0381169060178211613423576134189150604060ff8451921617906131fc565b505b51613331565b50565b5060ff8111613448576134429061343a8351613003565b508251613777565b5061341a565b61ffff8111613467576134429061345f8351612f9e565b508251613710565b63ffffffff811161348857613442906134808351612f39565b5082516136a7565b613442906134968351612ec9565b50825161363b565b81516134209291906001600160401b03811690601782116134cd576134189150606060ff8451921617906131fc565b5060ff81116134e4576134429061343a8351613197565b61ffff81116134fb576134429061345f8351613132565b63ffffffff8111613514576134429061348083516130cd565b613442906134968351613068565b80519061352d612d6c565b50815151600181019081811161143657602084015181101561357b575b609f6020809551928301015380518211613573575b505001805190600182018092116114365752565b52388061355f565b8160011b9382850460021483151715611436576020816135a48297612eb8609f95519184612dd6565b509550505061354a565b8051906135b9612d6c565b508151516001810190818111611436576020840151811015613608575b60ff6020809551928301015380518211613600575b50500180516000198101919082116114365752565b5238806135eb565b8160011b9382850460021483151715611436576020816136318297612eb860ff95519184612dd6565b50955050506135d6565b90613644612d6c565b508151518060080191826008116114365760208401518311613686575b6008845192830101906001600160401b031982511617905280518211612f0657505090565b8260011b83810460021484151715611436576136a29085613267565b613661565b906136b0612d6c565b5081515180600401918260041161143657602084015183116136ef575b60048451928301019063ffffffff1982511617905280518211612f0657505090565b8260011b838104600214841517156114365761370b9085613267565b6136cd565b90613719612d6c565b508151518060020191826002116114365760208401518311613756575b60028451928301019061ffff1982511617905280518211612f0657505090565b8260011b83810460021484151715611436576137729085613267565b613736565b90613780612d6c565b5081515180600101918260011161143657602084015183116137bc575b60018451928301019060ff1982511617905280518211612f0657505090565b8260011b83810460021484151715611436576137d89085613267565b61379d565b6138247fe945c25e663b7f927fca5b167e9d99e30aac67d2f2c39fac12b6618f57481e929161380d600654611427565b600655604051918291604083526040830190610633565b600160208301520390a1565b6138607fe945c25e663b7f927fca5b167e9d99e30aac67d2f2c39fac12b6618f57481e929161380d600654611427565b600260208301520390a1565b61389c7fe945c25e663b7f927fca5b167e9d99e30aac67d2f2c39fac12b6618f57481e929161380d600654611427565b600360208301520390a156fe636f6e737420656d61696c55524c203d202768747470733a2f2f6170692e6d61036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db09016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c1993004f44417a596a45334f5449365a44526c4d44526a4d6d55314d54646d4e57517a8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b4d6a41344e6a6869596d49334f5451345a545a694d7a6b3d0000000000000000f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a004f474e6c595749324e47466d5a5445784e57526959574a694d5468684e47517aa2646970667358221220fc8b1bfaf64db7bd92c765e12a0472c28297594116caa9bb1752d2569016e90364736f6c63430008140033

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
0xDF3a52358fA9aA82A0BC364a41376b42D0404D13
Loading...
Loading
Loading...
Loading

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.