Skip to content
Verified contractExactMIT

MultisigWallet

Address0x591aa9dff01b8144dc17cb416001d9ac84b951cd
Balance

0 ETH

 

Transactions

17

 

Compiler

solc 0.8.24

 

Same code

2 more contracts

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 9,999,999 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
21,182,290
Creation transaction
0x251d9fae71…5ad1d98b03

lib/multisig/src/MultisigWallet.sol

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

import "./EIP712.sol";
import "./Constants.sol";
import "./DataTypes.sol";
import "./Errors.sol";
import "@limitbreak/tm-core-lib/src/utils/security/TstorishReentrancyGuard.sol";

/**
 * @title  MultisigWallet
 * @author Limit Break, Inc.
 * @notice The MultisigWallet contract is designed to allow authorized signers to
 *         execute transactions when the number of signatures meets or exceeds the 
 *         wallet's threshold for execution.
 * 
 * @dev    A MultisigWallet's signer set has three components:
 *         - Signers - List of addresses that may sign a transaction or signer set replacement
 *         - Guardians - List of addresses, one of which *MUST* sign a signer set replacement
 *         - Threshold - The minimum number of signers required to execute a transaction
 * 
 * @dev    Signer set replacement is implemented through EIP-712 signatures that 
 *         *DO NOT* use the `chainId` in the domain separator. This is to allow a 
 *         signer set chain on one chain to be applied across all chains that the 
 *         wallet is deployed to and for a "new chain" to "catch up" to the current
 *         signer set without having to re-sign the changes with the initial signers.
 */
contract MultisigWallet is EIP712, TstorishReentrancyGuard {
    using EnumerableSet for EnumerableSet.AddressSet;

    /// @dev Current signer set data
    SignerSet private signerSet;
    /// @dev Current wallet nonce, transactions must be signed with the current nonce to execute
    uint256 public currentNonce;
    /// @dev Mapping of cross chain nonce buckets to their current nonce
    mapping (uint256 => uint256) public crossChainNonceBuckets;
    /// @dev Mapping of selectors to return values for adding support of token protocols that use basic transfer checks on addresses with code
    mapping (bytes4 => FallbackReturn) public fallbackReturns;

    /// @dev Emitted when a batch transaction is executed
    event BatchTransactionExecuted(bytes32 indexed batchTxHash, bytes[] results);
    /// @dev Emitted when a fallback return is updated
    event FallbackReturnUpdated(bytes4 indexed selector, bool enabled, bytes returnData);
    /// @dev Emitted when the signer set is replaced
    event SignerSetReplaced(uint32 newSignerSetId, uint32 newThreshold, address[] newSignerAddresses, address[] newGuardianAddresses);
    /// @dev Emitted when a transaction is executed
    event TransactionExecuted(bytes32 indexed txHash, bytes result);


    /**
     * @dev Construct the multisig wallet with the supplied list of initial signers and signature threshold.
     * 
     * @dev Throws when the number of signers is less than the threshold.
     * @dev Throws when the signers are not supplied in ascending order.
     * 
     * @param threshold                 Number of signatures required to execute a transaction.
     * @param signers                   List of initial signers.
     * @param guardians                 List of initial guardians.
     * @param fallbackReturnSelectors   Array of function selectors to return a value for in the fallback.
     * @param fallbackReturnData        Array of data to return for each function signature in the fallback.
     */
    constructor(
        uint256 threshold,
        address[] memory signers,
        address[] memory guardians,
        bytes4[] memory fallbackReturnSelectors,
        bytes[] memory fallbackReturnData
    ) TstorishReentrancyGuard() EIP712("MultisigWallet", "1") {
        _setSignerSet(signers, threshold);
        _setGuardianSet(guardians);

        uint256 fallbackReturnSelectorsLength = fallbackReturnSelectors.length;
        if (fallbackReturnSelectorsLength != fallbackReturnData.length) {
            revert MultisigWallet__InvalidArrayLengths();
        }

        for (uint256 i; i < fallbackReturnSelectorsLength; ++i) {
            bytes4 fallbackReturnSelector = fallbackReturnSelectors[i];
            bytes memory fallbackReturn = fallbackReturnData[i];
            fallbackReturns[fallbackReturnSelector] = FallbackReturn({
                enabled: true,
                returnData: fallbackReturn
            });
            emit FallbackReturnUpdated(fallbackReturnSelector, true, fallbackReturn);
        }

        fallbackReturns[SELECTOR_ON_ERC1155_RECEIVED] = FallbackReturn({
            enabled: true,
            returnData: RETURN_DATA_ON_ERC1155_RECEIVED
        });
        emit FallbackReturnUpdated(SELECTOR_ON_ERC1155_RECEIVED, true, RETURN_DATA_ON_ERC1155_RECEIVED);
        fallbackReturns[SELECTOR_ON_ERC1155_BATCH_RECEIVED] = FallbackReturn({
            enabled: true,
            returnData: RETURN_DATA_ON_ERC1155_BATCH_RECEIVED
        });
        emit FallbackReturnUpdated(SELECTOR_ON_ERC1155_BATCH_RECEIVED, true, RETURN_DATA_ON_ERC1155_BATCH_RECEIVED);
        fallbackReturns[SELECTOR_ON_ERC721_RECEIVED] = FallbackReturn({
            enabled: true,
            returnData: RETURN_DATA_ON_ERC721_RECEIVED
        });
        emit FallbackReturnUpdated(SELECTOR_ON_ERC721_RECEIVED, true, RETURN_DATA_ON_ERC721_RECEIVED);
    }

    /**
     * @notice Executes a transaction from the multisig wallet when properly signed.
     * 
     * @dev    Throws when there are not enough signatures supplied for the current threshold.
     * @dev    Throws when the recovered address for a signature is not in the current signer set.
     * @dev    Throws when signatures are supplied where the signer order is not ascending.
     * @dev    Throws when the call from the multisig to the `to` address reverts.
     * 
     * @dev    <h4>Postconditions:</h4>
     * @dev    1. This contract's native token balance has increased by `msg.value`.
     * @dev    2. `currentNonce` is incremented by one.
     * @dev    3. This contract's native token balance is decreased by `value`.
     * @dev    4. A call is made to `to` with a message value of `value` and calldata of `data`.
     * @dev    5. A `TransactionExecuted` event has been emitted.  The EIP712 transaction hash and call return data is logged in the event.
     * 
     * @param to          Address to call.
     * @param value       Value to send to the `to` address.
     * @param data        Calldata to send to the `to` address.
     * @param signatures  Array of signature values from the multisig signers.
     */
    function executeTransaction(
        address to,
        uint256 value,
        bytes calldata data,
        SignatureECDSA[] calldata signatures
    ) external payable nonReentrant {
        unchecked {
            bytes32 txHash = _getTransactionHash(
                currentNonce++,
                to,
                value,
                data
            );
            _checkSignatures(txHash, signatures);

            (bool success, bytes memory result) = to.call{value: value}(data);
            if (success) {
                emit TransactionExecuted(txHash, result);
            } else {
                revert MultisigWallet__CallReverted(result);
            }
        }
    }

    /**
     * @notice Executes a batch of transactions from the multisig wallet when properly signed.
     * 
     * @dev    Throws when the batch array lengths are zero or do not match.
     * @dev    Throws when there are not enough signatures supplied for the current threshold.
     * @dev    Throws when the recovered address for a signature is not in the current signer set.
     * @dev    Throws when signatures are supplied where the signer order is not ascending.
     * @dev    Throws when the call from the multisig to the `to` address reverts.
     * 
     * @dev    <h4>Postconditions:</h4>
     * @dev    1. This contract's native token balance has increased by `msg.value`.
     * @dev    2. `currentNonce` is incremented by the number of transactions in the batch.
     * @dev    3. This contract's native token balance is decreased by the sum of values in `transactions`.
     * @dev    4. Calls are made to each address in `transactions` with the corresponding `data` and `value`.
     * @dev    5. A `BatchTransactionExecuted` event has been emitted.  The EIP712 transaction hash and call return data is logged in the event.
     * 
     * @param transactions  Array of transactions to execute.
     * @param signatures    Array of signature values from the multisig signers.
     */
    function executeBatchTransaction(
        BatchedTransaction[] calldata transactions,
        SignatureECDSA[] calldata signatures
    ) external payable nonReentrant {
        if (transactions.length == 0) {
            revert MultisigWallet__InvalidArrayLengths();
        }

        unchecked {
            uint256 cachedNonce = currentNonce;
            bytes32[] memory txHashes = new bytes32[](transactions.length);
            bytes[] memory txResults = new bytes[](transactions.length);

            address to;
            uint256 value;
            bytes calldata data;
            BatchedTransaction calldata transaction;
            for (uint256 i; i < transactions.length; ++i) {
                transaction = transactions[i];
                to = transaction.to;
                value = transaction.value;
                data = transaction.data;

                bytes32 txHash = _getTransactionHashForBatch(
                    cachedNonce++,
                    to,
                    value,
                    data
                );
                txHashes[i] = txHash;

                (bool success, bytes memory result) = to.call{value: value}(data);
                if (success) {
                    txResults[i] = result;
                } else {
                    revert MultisigWallet__CallReverted(result);
                }
            }

            currentNonce = cachedNonce;
            bytes32 batchTxHash = _getBatchTransactionHashFromTxHashes(txHashes);

            _checkSignatures(batchTxHash, signatures);
            emit BatchTransactionExecuted(batchTxHash, txResults);
        }
    }

    /**
     * @notice Executes a transaction from the multisig wallet when properly signed.
     * 
     * @dev    Cross chain transactions are signed with a domain separator that does not include
     *         the chainId so that they may be replayed across all chains the multisig wallet is
     *         deployed to.
     * 
     * @dev    Throws when the cross chain nonce has already been consumed.
     * @dev    Throws when there are not enough signatures supplied for the current threshold.
     * @dev    Throws when the recovered address for a signature is not in the current signer set.
     * @dev    Throws when signatures are supplied where the signer order is not ascending.
     * @dev    Throws when a call from the multisig reverts.
     * 
     * @dev    <h4>Postconditions:</h4>
     * @dev    1. This contract's native token balance has increased by `msg.value`.
     * @dev    2. Each nonce in `transactions` is consumed in the `consumedCrossChainNonces` mapping.
     * @dev    3. This contract's native token balance is decreased by the sum of values in `transactions`.
     * @dev    4. Calls are made to each address in `transactions` with the corresponding `data` and `value`.
     * @dev    5. A `TransactionExecuted` event has been emitted for each transaction.
     *            The EIP712 transaction hash and call return data is logged in the event.
     * 
     * @param transactions  Array of cross chain transactions to execute.     
     * @param signatures    Array of signature values from the multisig signers.
     */
    function executeCrossChainTransactions(
        CrossChainTransaction[] calldata transactions,
        SignatureECDSA[][] calldata signatures
    ) external payable nonReentrant {
        if (transactions.length == 0 || transactions.length != signatures.length) {
            revert MultisigWallet__InvalidArrayLengths();
        }

        unchecked {
            CrossChainTransaction calldata transaction;
            SignatureECDSA[] calldata txSignatures;
            uint256 bucket;
            address to;
            uint256 value;
            bytes calldata data;

            for (uint256 i; i < transactions.length; ++i) {
                transaction = transactions[i];
                txSignatures = signatures[i];
                bucket = transaction.bucket;
                to = transaction.to;
                value = transaction.value;
                data = transaction.data;

                if (to.code.length == 0) {
                    revert MultisigWallet__ToHasNoCode();
                }

                bytes32 txHash = _getCrossChainTransactionHash(
                    bucket,
                    crossChainNonceBuckets[bucket]++,
                    to,
                    value,
                    data
                );
                _checkSignatures(txHash, txSignatures);

                (bool success, bytes memory result) = to.call{value: value}(data);
                if (success) {
                    emit TransactionExecuted(txHash, result);
                } else {
                    revert MultisigWallet__CallReverted(result);
                }
            }
        }
    }

    /**
     * @notice Updates the signer set with a new list of signers.
     * 
     * @dev    Throws when there are not enough signatures supplied for the current threshold.
     * @dev    Throws when the recovered address for a signature is not in the current signer set.
     * @dev    Throws when signatures are supplied where the signer order is not ascending.
     * @dev    Throws when the number of new signers is less than the new threshold.
     * @dev    Throws when the new signers are not supplied in ascending order.
     * @dev    Throws when the recovered address for the guardian signature is not in the current guardian set.
     * 
     * @dev    <h4>Postconditions:</h4>
     * @dev    1. The new signers, guardians and threshold are stored.
     * @dev    2. A `SignerSetReplaced` event has been emitted.
     * 
     * @param threshold          Number of signers required to execute a transaction.
     * @param signers            Array of signer addresses allowed to sign a transaction.
     * @param guardians          Array of guardian addresses allowed to sign the next signer set update.
     * @param signatures         Array of signature values from the multisig signers.
     * @param guardianSignature  Signature from a guardian authorizing this signer set change.
     */
    function setSignerSet(
        uint256 threshold,
        address[] calldata signers,
        address[] calldata guardians,
        SignatureECDSA[] calldata signatures,
        SignatureECDSA calldata guardianSignature
    ) external {
        uint32 currentSignerSetId = signerSet.id;
        bytes32 signerSetHash = _getSignerSetHash(currentSignerSetId, threshold, signers, guardians);
        _checkSignatures(signerSetHash, signatures);
        _checkGuardianSignature(signerSetHash, guardianSignature);
        _setSignerSet(signers, threshold);
        _setGuardianSet(guardians);
        unchecked {
            signerSet.id = ++currentSignerSetId;
        }
        emit SignerSetReplaced(currentSignerSetId, uint32(threshold), signers, guardians);
    }

    /**
     * @notice Executes a batch of signer set updates.
     * 
     * @dev    Primary use case for this function is to bring a multisig wallet up to the current
     * @dev    signing set from a primary chain when the wallet is deployed on a new chain.
     * 
     * @dev    Throws when the batch array lengths are zero or do not match.
     * @dev    Throws when there are not enough signatures supplied for the current threshold.
     * @dev    Throws when the recovered address for a signature is not in the current signer set.
     * @dev    Throws when signatures are supplied where the signer order is not ascending.
     * @dev    Throws when the number of new signers is less than the new threshold.
     * @dev    Throws when the new signers are not supplied in ascending order.
     * @dev    Throws when the recovered address for the guardian signature is not in the current guardian set.
     * 
     * @dev    <h4>Postconditions:</h4>
     * @dev    1. The new signers, guardians and threshold are stored.
     * @dev    2. A `SignerSetReplaced` event has been emitted.
     * 
     * @param batchThreshold          Array of number of signers required to execute a transaction.
     * @param batchSigners            Array of signer addresses allowed to sign a transaction.
     * @param batchGuardians          Array of guardian addresses allowed to sign the next signer set update.
     * @param batchSignatures         Array of signature values from the multisig signers.
     * @param batchGuardianSignature  Array of signatures from a guardian authorizing this signer set change.
     */
    function batchSetSignerSet(
        uint256[] calldata batchThreshold,
        address[][] calldata batchSigners,
        address[][] calldata batchGuardians,
        SignatureECDSA[][] calldata batchSignatures,
        SignatureECDSA[] calldata batchGuardianSignature
    ) external {
        if (
            batchThreshold.length == 0 ||
            batchThreshold.length != batchSigners.length ||
            batchSigners.length != batchGuardians.length ||
            batchGuardians.length != batchSignatures.length ||
            batchSignatures.length != batchGuardianSignature.length
        ) {
            revert MultisigWallet__InvalidArrayLengths();
        }

        unchecked {
            uint32 currentSignerSetId = signerSet.id;
            for (uint256 i; i < batchThreshold.length; ++i) {
                bytes32 signerSetHash = _getSignerSetHash(currentSignerSetId, batchThreshold[i], batchSigners[i], batchGuardians[i]);
                _checkSignatures(signerSetHash, batchSignatures[i]);
                _checkGuardianSignature(signerSetHash, batchGuardianSignature[i]);
                _setSignerSet(batchSigners[i], batchThreshold[i]);
                _setGuardianSet(batchGuardians[i]);
                ++currentSignerSetId;
            }
            signerSet.id = currentSignerSetId;

            uint256 lastIndex = batchThreshold.length - 1;
            emit SignerSetReplaced(
                currentSignerSetId,
                uint32(batchThreshold[lastIndex]),
                batchSigners[lastIndex],
                batchGuardians[lastIndex]
            );
        }
    }

    /**
     * @notice Sets a generic return value in bytes for a given function selector that is handled by the fallback.
     * 
     * @dev    This function must be called through `executeTransaction` or `executeBatchTransaction`.
     * 
     * @param selector    Function selector to supply return data for.
     * @param enabled     True if the fallback should handle the function, false otherwise.
     * @param returnData  Bytes of return data to return when the fallback handles a call for the selector.
     */
    function setFallbackReturnData(bytes4 selector, bool enabled, bytes calldata returnData) external {
        if (msg.sender != address(this)) {
            revert MultisigWallet__CallerMustBeWallet();
        }

        fallbackReturns[selector] = FallbackReturn({
            enabled: enabled,
            returnData: returnData
        });

        emit FallbackReturnUpdated(selector, enabled, returnData);
    }

    /**
     * @notice Computes the EIP712 hash value that must be signed for a transaction by the multisig signers to execute.
     * 
     * @dev    Uses a supplied nonce value so that transactions may be queued for signing and execution.
     * 
     * @param nonce  The value the nonce should be when the transaction is executed.
     * @param to     Address to call.
     * @param value  Value to send to the `to` address.
     * @param data   Calldata to send to the `to` address.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function getTransactionHash(
        uint256 nonce,
        address to,
        uint256 value,
        bytes calldata data
    ) external view returns (bytes32 hash) {
        hash = _getTransactionHash(nonce, to, value, data);
    }

    /**
     * @notice Computes the EIP712 hash value that must be signed for a transaction by the multisig signers to execute.
     * 
     * @dev    Uses the current nonce value for determining the transaction hash. 
     * 
     * @param to     Address to call.
     * @param value  Value to send to the `to` address.
     * @param data   Calldata to send to the `to` address.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function getTransactionHashWithCurrentNonce(
        address to,
        uint256 value,
        bytes calldata data
    ) external view returns (bytes32 hash) {
        hash = _getTransactionHash(currentNonce, to, value, data);
    }

    /**
     * @notice Computes the EIP712 hash value that must be signed for a transaction by the multisig signers to execute.
     * 
     * @dev    Uses a supplied nonce value so that transactions may be queued for signing and execution.
     * 
     * @param nonce       The value the nonce should be when the transaction is executed.
     * @param transactions  Array of transactions to execute.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function getBatchTransactionHash(
        uint256 nonce,
        BatchedTransaction[] calldata transactions
    ) external view returns (bytes32 hash) {
        hash = _getBatchTransactionHash(nonce, transactions);
    }

    /**
     * @notice Computes the EIP712 hash value that must be signed for a transaction by the multisig signers to execute.
     * 
     * @dev    Uses the current nonce value for determining the transaction hash. 
     * 
     * @param transactions  Array of transactions to execute.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function getBatchTransactionHashWithCurrentNonce(
        BatchedTransaction[] calldata transactions
    ) external view returns (bytes32 hash) {
        hash = _getBatchTransactionHash(currentNonce, transactions);
    }

    /**
     * @notice Computes the EIP712 hash value that must be signed for a cross chain transaction by the multisig signers to execute.
     * 
     * @param nonce       The value the nonce should be when the transaction is executed.
     * @param transaction  The cross chain transaction to get the EIP712 hash for.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function getCrossChainTransactionHash(
        uint256 nonce,
        CrossChainTransaction calldata transaction
    ) external view returns (bytes32 hash) {
        hash = _getCrossChainTransactionHash(
            transaction.bucket,
            nonce,
            transaction.to,
            transaction.value,
            transaction.data
        );
    }

    /**
     * @notice Computes the EIP712 hash value that must be signed for a cross chain transaction by the multisig signers to execute.
     * 
     * @param transaction  The cross chain transaction to get the EIP712 hash for.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function getCrossChainTransactionHashWithCurrentNonce(
        CrossChainTransaction calldata transaction
    ) external view returns (bytes32 hash) {
        hash = _getCrossChainTransactionHash(
            transaction.bucket,
            crossChainNonceBuckets[transaction.bucket],
            transaction.to,
            transaction.value,
            transaction.data
        );
    }

    /**
     * @notice Computes the EIP712 hash value that must be signed to update the signer set.
     * 
     * @param threshold   Number of signers required to execute a transaction.
     * @param signers     Array of signer addresses allowed to sign a transaction.
     * @param guardians   Array of guardian addresses allowed to sign the next signer set update.
     * 
     * @return hash       The computed EIP712 hash to be signed.
     */
    function getSignerSetHash(
        uint256 threshold,
        address[] calldata signers,
        address[] calldata guardians
    ) external view returns (bytes32 hash) {
        hash = _getSignerSetHash(signerSet.id, threshold, signers, guardians);
    }

    /**
     * @notice Checks the signatures for a EIP712 hash to ensure signatures are valid to execute a transaction.
     * 
     * @dev    Throws when there are not enough signatures supplied for the current threshold.
     * @dev    Throws when the recovered address for a signature is not in the current signer set.
     * @dev    Throws when signatures are supplied where the signer order is not ascending.
     * 
     * @param hash        Hash value of the message that was signed by the signers.
     * @param signatures  Array of signature values from the multisig signers.
     * 
     * @return True if signatures are valid for the current signer set and threshold, throws otherwise.
     */
    function checkSignaturesForExecuteTransaction(
        bytes32 hash,
        SignatureECDSA[] calldata signatures
    ) external view returns (bool) {
        _checkSignatures(hash, signatures);

        return true;
    }

    /**
     * @notice Checks the signatures for a EIP712 hash to ensure signatures are valid to update the signer set.
     * 
     * @dev    Throws when there are not enough signatures supplied for the current threshold.
     * @dev    Throws when the recovered address for a signature is not in the current signer set.
     * @dev    Throws when signatures are supplied where the signer order is not ascending.
     * @dev    Throws when the recovered guardian address for the guardian signature is not in the current guardian set.
     * 
     * @param hash        Hash value of the message that was signed by the signers.
     * @param signatures  Array of signature values from the multisig signers.
     * 
     * @return True if signatures are valid for the current signer set, threshold and guardians, throws otherwise.
     */
    function checkSignaturesForSetSignerSet(
        bytes32 hash,
        SignatureECDSA[] calldata signatures,
        SignatureECDSA calldata guardianSignature
    ) external view returns (bool) {
        _checkSignatures(hash, signatures);
        _checkGuardianSignature(hash, guardianSignature);

        return true;
    }

    /**
     * @notice Returns the current signer set id.
     * 
     * @return currentSignerSetId The id of the current signer set.
     */
    function getCurrentSignerSetId() external view returns (uint32 currentSignerSetId) {
        currentSignerSetId = signerSet.id;
    }

    /**
     * @notice Returns the threshold for the current signer set.
     * 
     * @return threshold The number of valid signatures required to execute a transaction.
     */
    function getThreshold() external view returns (uint256 threshold) {
        threshold = signerSet.threshold;
    }

    /**
     * @notice Returns if an address is a valid signer in the current signer set.
     * 
     * @return addressIsSigner True if the signer is in the current signer set, false otherwise.
     */
    function isSigner(address signer) external view returns (bool addressIsSigner) {
        addressIsSigner = signerSet.signers.contains(signer);
    }

    /**
     * @notice Returns an address array of all addresses in the current signer set.
     * 
     * @return signers  Array of signers in the current signer set.
     */
    function getSigners() external view returns (address[] memory signers) {
        signers = signerSet.signers.values();
    }

    /**
     * @notice Returns an address array of all addresses in the current guardian set.
     * 
     * @return guardians  Array of guardians in the current signer set.
     */
    function getGuardians() external view returns (address[] memory guardians) {
        guardians = signerSet.guardians.values();
    }

    /**
     * @notice Returns the chain specific domain separator hash for signing transactions to execute.
     * 
     * @return chainDomainSeparatorHash  The hash of the chain specific domain separator.
     */
    function chainDomainSeparator() external view returns (bytes32 chainDomainSeparatorHash) {
        chainDomainSeparatorHash = _chainDomainSeparator();
    }

    /**
     * @notice Returns the domain separator without chainId hash for signing transactions to update signer sets.
     * 
     * @return chainlessDomainSeparatorHash  The hash of the domain separator without chainId.
     */
    function chainlessDomainSeparator() external view returns (bytes32 chainlessDomainSeparatorHash) {
        chainlessDomainSeparatorHash = _chainlessDomainSeparator();
    }

    /**
     * @dev Internal function to store a new set of signers and threshold. Called during contract construction
     * @dev and when `setSignerSet` is executed by the current signers.
     * 
     * @param signers    Array of signer addresses allowed to sign a transaction.
     * @param threshold  Number of signers required to execute a transaction.
     */
    function _setSignerSet(address[] memory signers, uint256 threshold) internal {
        if (threshold == 0 || signers.length < threshold || threshold > type(uint32).max) {
            revert MultisigWallet__InvalidSignerSet();
        }

        EnumerableSet.AddressSet storage signerSetSigners = signerSet.signers;
        uint256 currentSignerSetLength = signerSetSigners.length();
        if (currentSignerSetLength > 0) {
            unchecked {
                uint256 index = currentSignerSetLength - 1;
                while (true) {
                    signerSetSigners.remove(signerSetSigners.at(index));
                    if (index == 0) break;
                    --index;
                }
            }
        }

        address previousSigner;
        for (uint256 i; i < signers.length; i++) {
            address signer = signers[i];
            if (signer <= previousSigner) {
                revert MultisigWallet__InvalidSignerSet();
            }
            signerSetSigners.add(signer);
            previousSigner = signer;
        }
        signerSet.threshold = uint32(threshold);
    }

    /**
     * @dev Internal function to store a new set of guardians. Called during contract construction
     * @dev and when `setSignerSet` is executed by the current signers.
     * 
     * @param guardians  Array of guardian addresses allowed to authorize a signer set change.
     */
    function _setGuardianSet(address[] memory guardians) internal {
        if (guardians.length < MINIMUM_GUARDIANS) {
            revert MultisigWallet__InvalidGuardianSet();
        }

        EnumerableSet.AddressSet storage signerSetGuardians = signerSet.guardians;
        uint256 currentGuardianSetLength = signerSetGuardians.length();
        if (currentGuardianSetLength > 0) {
            unchecked {
                uint256 index = currentGuardianSetLength - 1;
                while (true) {
                    signerSetGuardians.remove(signerSetGuardians.at(index));
                    if (index == 0) break;
                    --index;
                }
            }
        }

        address previousGuardian;
        for (uint256 i; i < guardians.length; i++) {
            address guardian = guardians[i];
            if (guardian <= previousGuardian) {
                revert MultisigWallet__InvalidGuardianSet();
            }
            signerSetGuardians.add(guardian);
            previousGuardian = guardian;
        }
    }

    /**
     * @dev Internal function to compute the EIP712 signature hash to be signed for a transaction.
     * 
     * @param nonce  The value the nonce should be when the transaction is executed.
     * @param to     Address to call.
     * @param value  Value to send to the `to` address.
     * @param data   Calldata to send to the `to` address.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function _getTransactionHash(
        uint256 nonce,
        address to,
        uint256 value,
        bytes calldata data
    ) internal view returns (bytes32 hash) {
        hash = _hashChainTypedData(
            keccak256(
                abi.encode(
                    TRANSACTION_TYPEHASH,
                    nonce,
                    to,
                    value,
                    keccak256(data)
                )
            )
        );
    }

    /**
     * @dev Internal function to compute the EIP712 signature hash to be signed for a cross chain transaction.
     * 
     * @param bucket The bucket the nonce is in.
     * @param nonce  The nonce value of the cross chain transaction.
     * @param to     Address to call.
     * @param value  Value to send to the `to` address.
     * @param data   Calldata to send to the `to` address.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function _getCrossChainTransactionHash(
        uint256 bucket,
        uint256 nonce,
        address to,
        uint256 value,
        bytes calldata data
    ) internal view returns (bytes32 hash) {
        hash = _hashChainlessTypedData(
            keccak256(
                abi.encode(
                    CROSS_CHAIN_TRANSACTION_TYPEHASH,
                    bucket,
                    nonce,
                    to,
                    value,
                    keccak256(data)
                )
            )
        );
    }

    /**
     * @dev Internal function to compute the hash of a transaction that is included in a batch.
     * 
     * @param nonce  The value the nonce should be when the transaction is executed.
     * @param to     Address to call.
     * @param value  Value to send to the `to` address.
     * @param data   Calldata to send to the `to` address.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function _getTransactionHashForBatch(
        uint256 nonce,
        address to,
        uint256 value,
        bytes calldata data
    ) internal pure returns (bytes32 hash) {
        hash = keccak256(
            abi.encode(
                TRANSACTION_TYPEHASH,
                nonce,
                to,
                value,
                keccak256(data)
            )
        );
    }

    /**
     * @dev Internal function to compute the EIP712 signature hash to be signed for a batch transaction.
     * 
     * @param txHashes  Array of transaction hashes for each transaction in the batch.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function _getBatchTransactionHashFromTxHashes(
        bytes32[] memory txHashes
    ) internal view returns (bytes32 hash) {
        hash = _hashChainTypedData(
            keccak256(
                abi.encode(
                    BATCH_TRANSACTION_TYPEHASH,
                    _getBytes32ArrayHashed(txHashes)
                )
            )
        );
    }

    /**
     * @dev Internal function to compute the EIP712 signature hash to be signed for a batch transaction.
     * 
     * @param nonce       The value the nonce should be when the transaction is executed.
     * @param transactions  Array of transactions to execute.
     * 
     * @return hash  The computed EIP712 hash to be signed.
     */
    function _getBatchTransactionHash(
        uint256 nonce,
        BatchedTransaction[] calldata transactions
    ) internal view returns (bytes32 hash) {
        unchecked {
            uint256 cachedNonce = nonce;
            bytes32[] memory txHashes = new bytes32[](transactions.length);
            BatchedTransaction calldata transaction;
            for (uint256 i; i < transactions.length; ++i) {
                transaction = transactions[i];
                bytes32 txHash = _getTransactionHashForBatch(
                    cachedNonce++,
                    transaction.to,
                    transaction.value,
                    transaction.data
                );
                txHashes[i] = txHash;
            }

            hash = _getBatchTransactionHashFromTxHashes(txHashes);
        }
    }

    /**
     * @dev Internal function to compute the EIP712 signature hash to be signed for a signer set update.
     * 
     * @param signerSetId  The current signer set id 
     * @param threshold    Number of signers required to execute a transaction.
     * @param signers      Array of signer addresses allowed to sign a transaction.
     * @param guardians    Array of guardian addresses allowed to authorize a signer set change.
     * 
     * @return hash       The computed EIP712 hash to be signed.
     */
    function _getSignerSetHash(
        uint32 signerSetId,
        uint256 threshold,
        address[] calldata signers,
        address[] calldata guardians
    ) internal view returns (bytes32 hash) {
        hash = _hashChainlessTypedData(
            keccak256(
                abi.encode(
                    SIGNER_SET_TYPEHASH,
                    signerSetId,
                    threshold,
                    _getAddressBytesHashed(signers),
                    _getAddressBytesHashed(guardians)
                )
            )
        );
    }

    /**
     * @dev Internal function to hash an array of addresses for EIP712 signatures.
     * 
     * @param addresses  Array of addresses to hash.
     * 
     * @return addressesHash  Hash of the address values.
     */
    function _getAddressBytesHashed(address[] calldata addresses) internal pure returns (bytes32 addressesHash) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            let len := mul(addresses.length, 0x20)
            mstore(0x40, add(ptr, len))
            calldatacopy(ptr, addresses.offset, add(addresses.offset, len))
            addressesHash := keccak256(ptr, len)
        }
    }

    /**
     * @dev Internal function to hash an array of bytes32 values for EIP712 signatures.
     * 
     * @param hashes  Array of bytes32 hashes to hash.
     * 
     * @return hashesHash  Hash of the bytes32 values.
     */
    function _getBytes32ArrayHashed(bytes32[] memory hashes) internal pure returns (bytes32 hashesHash) {
        assembly ("memory-safe") {
            let ptr := add(hashes, 0x20)
            let len := mul(mload(hashes), 0x20)
            hashesHash := keccak256(ptr, len)
        }
    }

    /**
     * @dev Internal function to check that the provided signatures are signed by the signers in
     * @dev the signer set and meet the signer set threshold for executing a transaction.
     * 
     * @dev Throws when the number of signatures is less than the signer set threshold.
     * @dev Throws when a signatures v value is greater than type(uint8).max.
     * @dev Throws when a signer is not in the signer set.
     * 
     * @param hash        Hash value of the message that was signed by the signers.
     * @param signatures  Array of signature values from the multisig signers.
     */
    function _checkSignatures(bytes32 hash, SignatureECDSA[] calldata signatures) internal view {
        uint256 requiredSignatures = signerSet.threshold;

        if (requiredSignatures > signatures.length) {
            revert MultisigWallet__NotEnoughSignatures();
        }

        EnumerableSet.AddressSet storage signers = signerSet.signers;
        SignatureECDSA calldata signature;
        address previousSigner;
        for (uint256 i; i < requiredSignatures; ++i) {
            signature = signatures[i];
            if (signature.v > type(uint8).max) {
                revert MultisigWallet__InvalidV();
            }

            address signer = ecrecover(hash, uint8(signature.v), signature.r, signature.s);
            if (signer <= previousSigner || !signers.contains(signer)) {
                revert MultisigWallet__InvalidSignatures();
            }
            previousSigner = signer;
        }
    }

    /**
     * @dev Internal function to check that the provided signature is signed by a guardian in
     * @dev the current signer set.
     * 
     * @dev Throws when the signature v value is greater than type(uint8).max.
     * @dev Throws when the signer is not in the guardian set.
     * 
     * @param hash       Hash value of the message that was signed by the signers.
     * @param signature  Signature value from a guardian.
     */
    function _checkGuardianSignature(bytes32 hash, SignatureECDSA calldata signature) internal view {
        if (signature.v > type(uint8).max) {
            revert MultisigWallet__InvalidV();
        }

        address signer = ecrecover(hash, uint8(signature.v), signature.r, signature.s);
        if (!signerSet.guardians.contains(signer)) {
            revert MultisigWallet__InvalidSignatures();
        }
    }

    /// @dev Receive function allows native funds to be deposited
    receive() external payable { }

    /// @dev Fallback function allows native funds to be deposited with calldata
    fallback() external payable {
        if (msg.data.length > 3) {
            FallbackReturn storage fallbackReturn = fallbackReturns[msg.sig];
            if (fallbackReturn.enabled) {
                bytes memory returnData = fallbackReturn.returnData;
                assembly ("memory-safe") {
                    return(add(returnData, 0x20), mload(returnData))
                }
            }
        }
        if (msg.value == 0) {
            revert MultisigWallet__FallbackNotHandled();
        }
    }
}

@limitbreak/tm-core-lib/src/utils/security/TstorishReentrancyGuard.sol

pragma solidity ^0.8.24;

import "../misc/Tstorish.sol";

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 */
abstract contract TstorishReentrancyGuard is Tstorish {

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

    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

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

    constructor() Tstorish() {
        if (!_tstoreInitialSupport) {
            _setTstorish(REENTRANCY_GUARD_STORAGE, 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 (_getTstorish(REENTRANCY_GUARD_STORAGE) == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _setTstorish(REENTRANCY_GUARD_STORAGE, ENTERED);
    }

    function _nonReentrantAfter() private {
        _setTstorish(REENTRANCY_GUARD_STORAGE, NOT_ENTERED);
    }

    function _onTstoreSupportActivated() internal virtual override {
        _copyFromStorageToTransient(REENTRANCY_GUARD_STORAGE);
    }
}

@limitbreak/tm-core-lib/src/utils/structs/EnumerableSet.sol

pragma solidity ^0.8.4;

/**
 * @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.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [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 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;
    }

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

        /// @solidity memory-safe-assembly
        assembly {
            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 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;

        /// @solidity memory-safe-assembly
        assembly {
            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 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;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

lib/multisig/src/Constants.sol

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

/// @dev Constant variable for zero.
uint256 constant ZERO = 0;
/// @dev Constant variable for one.
uint256 constant ONE = 1;
/// @dev Requires a minimum number of guardians when creating a multisig wallet or updating the signer set.
uint8 constant MINIMUM_GUARDIANS = 2;
/// @dev EIP712 typehash for a transaction to execute by the wallet
bytes32 constant TRANSACTION_TYPEHASH = keccak256("Transaction(uint256 nonce,address to,uint256 value,bytes data)");
/// @dev EIP712 typehash for a batch transaction to execute by the wallet
bytes32 constant BATCH_TRANSACTION_TYPEHASH = keccak256("BatchTransaction(Transaction[] transactions)Transaction(uint256 nonce,address to,uint256 value,bytes data)");
/// @dev EIP712 typehash for a cross chain transaction to execute by the wallet
bytes32 constant CROSS_CHAIN_TRANSACTION_TYPEHASH = keccak256("CrossChainTransaction(uint256 bucket,uint256 nonce,address to,uint256 value,bytes data)");
/// @dev EIP712 typehash for updating to a new signer set
bytes32 constant SIGNER_SET_TYPEHASH = keccak256("SignerSet(uint32 currentSignerSetId,uint256 threshold,address[] signers,address[] guardians)");

/// @dev Function selector to handle onERC1155Received calls in fallback
bytes4 constant SELECTOR_ON_ERC1155_RECEIVED = 0xf23a6e61;
/// @dev Return value when handling onERC1155Received calls in fallback
bytes constant RETURN_DATA_ON_ERC1155_RECEIVED = hex"f23a6e6100000000000000000000000000000000000000000000000000000000";
/// @dev Function selector to handle onERC1155BatchReceived calls in fallback
bytes4 constant SELECTOR_ON_ERC1155_BATCH_RECEIVED = 0xbc197c81;
/// @dev Return value when handling onERC1155BatchReceived calls in fallback
bytes constant RETURN_DATA_ON_ERC1155_BATCH_RECEIVED = hex"bc197c8100000000000000000000000000000000000000000000000000000000";
/// @dev Function selector to handle onERC721Received calls in fallback
bytes4 constant SELECTOR_ON_ERC721_RECEIVED = 0x150b7a02;
/// @dev Return value when handling onERC721Received calls in fallback
bytes constant RETURN_DATA_ON_ERC721_RECEIVED = hex"150b7a0200000000000000000000000000000000000000000000000000000000";

lib/multisig/src/DataTypes.sol

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

import "@limitbreak/tm-core-lib/src/utils/structs/EnumerableSet.sol";

/// @dev Storage for a set of signers with threshold
struct SignerSet {
    uint32 id;
    uint32 threshold;
    EnumerableSet.AddressSet signers;
    EnumerableSet.AddressSet guardians;
}

/// @dev Struct for signer's signatures when executing transactions
struct SignatureECDSA {
    uint256 v;
    bytes32 r;
    bytes32 s;
}

/// @dev Struct for batched transaction data
struct BatchedTransaction {
    address to;
    uint256 value;
    bytes data;
}

/// @dev Struct for batched transaction data
struct CrossChainTransaction {
    uint256 bucket;
    address to;
    uint256 value;
    bytes data;
}

/// @dev Struct to store state and return value for fallback returns
struct FallbackReturn {
    bool enabled;
    bytes returnData;
}

lib/multisig/src/EIP712.sol

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

pragma solidity 0.8.24;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic 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 their contracts 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.
 *
 * _Available since v3.4._
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
 */
abstract contract EIP712 {
    bytes32 private constant _CHAIN_TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 private constant _CHAINLESS_TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,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 _cachedChainDomainSeparator;
    bytes32 private immutable _cachedChainlessDomainSeparator;
    uint256 private immutable _cachedChainId;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    /**
     * @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) {
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedChainDomainSeparator = _buildChainDomainSeparator();
        _cachedChainlessDomainSeparator = _buildChainlessDomainSeparator();
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _chainDomainSeparator() internal view returns (bytes32 domainSeparator) {
        if (block.chainid == _cachedChainId) {
            domainSeparator = _cachedChainDomainSeparator;
        } else {
            domainSeparator = _buildChainDomainSeparator();
        }
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _chainlessDomainSeparator() internal view returns (bytes32 domainSeparator) {
        domainSeparator = _cachedChainlessDomainSeparator;
    }

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

    function _buildChainlessDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(_CHAINLESS_TYPE_HASH, _hashedName, _hashedVersion, address(this)));
    }

    function _hashChainTypedData(bytes32 structHash) internal view virtual returns (bytes32 hash) {
        hash = _toTypedDataHash(_chainDomainSeparator(), structHash);
    }

    function _hashChainlessTypedData(bytes32 structHash) internal view virtual returns (bytes32 hash) {
        hash = _toTypedDataHash(_chainlessDomainSeparator(), structHash);
    }

    function _toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }
}

lib/multisig/src/Errors.sol

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

/// @dev Thrown when setting a fallback return data and the caller is not the wallet
error MultisigWallet__CallerMustBeWallet();
/// @dev Thrown when executing a transaction and the call reverts
error MultisigWallet__CallReverted(bytes result);
/// @dev Thrown when a call with no value is not handled by the fallback function
error MultisigWallet__FallbackNotHandled();
/// @dev Thrown when executing a batch transaction or signer set update and array lengths do not match or are zero length
error MultisigWallet__InvalidArrayLengths();
/// @dev Thrown when validating signatures and a signer is not in the current signer set or signatures are not ordered by signer ascending
error MultisigWallet__InvalidSignatures();
/// @dev Thrown when updating a signer set and the number of guardians is less than `MINIMUM_GUARDIANS` or guardians are not ordered by their address ascending
error MultisigWallet__InvalidGuardianSet();
/// @dev Thrown when updating a signer set and the number of signers is less than threshold or signers are not ordered by signer ascending
error MultisigWallet__InvalidSignerSet();
/// @dev Thrown when a signature V value exceeds type(uint8).max
error MultisigWallet__InvalidV();
/// @dev Thrown when validating signatures and the number of signatures submitted is less than the threshold
error MultisigWallet__NotEnoughSignatures();
/// @dev Thrown when execute a cross chain transaction and the to address does not have deployed code
error MultisigWallet__ToHasNoCode();

lib/multisig/src/MultisigFactory.sol

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

import "./MultisigWallet.sol";

/**
 * @title  MultisigFactory
 * @author Limit Break, Inc.
 * @notice The MultisigFactory contract is designed to deploy MultisigWallet contracts using
 *         CREATE2 for a deterministic address that is based on a provided salt value,
 *         the initial signers and initial threshold for the wallet. This allows for a consistent
 *         address for a multisig wallet across any chain that the factory is deployed to.
 */
contract MultisigFactory {
    event MultisigCreated(address walletAddress);

    /**
     * @notice  Deploys a multisig wallet to a deterministic address with an initial
     * @notice  list of signers, guardians and a threshold.
     * 
     * @param salt       Salt value to allow deterministic deployment of a multisig wallet
     * @param threshold  Number of required signatures to execute a transaction
     * @param signers    Array of initial signers for the wallet
     * @param guardians  Array of initial guardians for the wallet
     * 
     * @return walletAddress  Returns the wallet address that was created
     */
    function deployWallet(
        bytes32 salt,
        uint256 threshold,
        address[] calldata signers,
        address[] calldata guardians
    ) external returns (address walletAddress) {
        walletAddress = address(
            new MultisigWallet{salt: salt}(
                threshold,
                signers,
                guardians,
                new bytes4[](0),
                new bytes[](0)
            )
        );
        emit MultisigCreated(walletAddress);
    }

    /**
     * @notice  Deploys a multisig wallet to a deterministic address with an initial
     * @notice  list of signers, guardians and a threshold.
     * 
     * @param salt                      Salt value to allow deterministic deployment of a multisig wallet
     * @param threshold                 Number of required signatures to execute a transaction
     * @param signers                   Array of initial signers for the wallet
     * @param guardians                 Array of initial guardians for the wallet
     * @param fallbackReturnSelectors   Array of function selectors to return a value for in the fallback.
     * @param fallbackReturnData        Array of data to return for each function signature in the fallback.
     * 
     * @return walletAddress  Returns the wallet address that was created
     */
    function deployWalletWithFallbackReturns(
        bytes32 salt,
        uint256 threshold,
        address[] calldata signers,
        address[] calldata guardians,
        bytes4[] calldata fallbackReturnSelectors,
        bytes[] calldata fallbackReturnData
    ) external returns (address walletAddress) {
        walletAddress = address(
            new MultisigWallet{salt: salt}(
                threshold,
                signers,
                guardians,
                fallbackReturnSelectors,
                fallbackReturnData
            )
        );
        emit MultisigCreated(walletAddress);
    }

    /**
     * @notice  Calculates the deterministic address for a multisig wallet deployed through
     * @notice  this factory with a given salt and initial signers, guardians and threshold.
     * 
     * @param salt                      Salt value to allow deterministic deployment of a multisig wallet
     * @param threshold                 Number of required signatures to execute a transaction
     * @param signers                   Array of initial signers for the wallet
     * @param guardians                 Array of initial guardians for the wallet
     * @param fallbackReturnSelectors   Array of function selectors to return a value for in the fallback.
     * @param fallbackReturnData        Array of data to return for each function signature in the fallback.
     * 
     * @return deploymentAddress  Returns the address the wallet will be deployed to
     */
    function computeDeploymentAddress(
        bytes32 salt,
        uint256 threshold,
        address[] calldata signers,
        address[] calldata guardians,
        bytes4[] calldata fallbackReturnSelectors,
        bytes[] calldata fallbackReturnData
    ) external view returns(address deploymentAddress) {
        bytes32 initCodeHash = keccak256(
            bytes.concat(
                type(MultisigWallet).creationCode,
                abi.encode(
                    threshold,
                    signers,
                    guardians,
                    fallbackReturnSelectors,
                    fallbackReturnData
                )
            )
        );

        deploymentAddress = address(
            uint160(
                uint256(
                    keccak256(
                        abi.encodePacked(
                            hex"ff",
                            address(this),
                            salt,
                            initCodeHash
                        )
                    )
                )
            )
        );
    }
}

lib/tm-core-lib/src/utils/misc/StorageTstorish.sol

pragma solidity ^0.8.24;

library StorageTstorish {   
    // keccak256(abi.encode(uint256(keccak256("storage.Tstorish")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant DATA_STORAGE_SLOT = 
        0xdacd49f6a6c42b45a5c3d195b83b324104542d9147bb8064a39c6a8d23ba9b00;

    struct Data {
        // Indicates if TSTORE support has been activated during or post-deployment.
        bool tstoreSupport;
    }

    function data() internal pure returns (Data storage ptr) {
        bytes32 slot = DATA_STORAGE_SLOT;
        assembly {
            ptr.slot := slot
        }
    }
}

lib/tm-core-lib/src/utils/misc/Tstorish.sol

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

import "./StorageTstorish.sol";

/**
 * @title  Tstorish
 * @notice Based on https://github.com/ProjectOpenSea/tstorish/commit/a81ed74453ed7b9fe7e96a9906bc4def19b73e33
 */
abstract contract Tstorish {

    /*
     * ------------------------------------------------------------------------+
     * Opcode      | Mnemonic         | Stack              | Memory            |
     * ------------------------------------------------------------------------|
     * 60 0x02     | PUSH1 0x02       | 0x02               |                   |
     * 60 0x1e     | PUSH1 0x1e       | 0x1e 0x02          |                   |
     * 61 0x3d5c   | PUSH2 0x3d5c     | 0x3d5c 0x1e 0x02   |                   |
     * 3d          | RETURNDATASIZE   | 0 0x3d5c 0x1e 0x02 |                   |
     *                                                                         |
     * :: store deployed bytecode in memory: (3d) RETURNDATASIZE (5c) TLOAD :: |
     * 52          | MSTORE           | 0x1e 0x02          | [0..0x20): 0x3d5c |
     * f3          | RETURN           |                    | [0..0x20): 0x3d5c |
     * ------------------------------------------------------------------------+
     */
    uint256 constant _TLOAD_TEST_PAYLOAD = 0x6002_601e_613d5c_3d_52_f3;
    uint256 constant _TLOAD_TEST_PAYLOAD_LENGTH = 0x0a;
    uint256 constant _TLOAD_TEST_PAYLOAD_OFFSET = 0x16;

    // Declare an immutable variable to store the tstore test contract address.
    address private immutable _tloadTestContract;

    // Declare an immutable variable to store the initial TSTORE support status.
    bool internal immutable _tstoreInitialSupport;

    // Declare an immutable function type variable for the _setTstorish function
    // based on chain support for tstore at time of deployment.
    function(uint256,uint256) internal immutable _setTstorish;

    // Declare an immutable function type variable for the _getTstorish function
    // based on chain support for tstore at time of deployment.
    function(uint256) view returns (uint256) internal immutable _getTstorish;

    // Declare an immutable function type variable for the _clearTstorish function
    // based on chain support for tstore at time of deployment.
    function(uint256) internal immutable _clearTstorish;

    // Declare a few custom revert error types.
    error TStoreAlreadyActivated();
    error TStoreNotSupported();
    error TloadTestContractDeploymentFailed();
    error OnlyDirectCalls();

    /**
     * @dev Determine TSTORE availability during deployment. This involves
     *      attempting to deploy a contract that utilizes TLOAD as part of the
     *      contract construction bytecode, and configuring initial support for
     *      using TSTORE in place of SSTORE based on the result.
     */
    constructor() {
        // Deploy the contract testing TLOAD support and store the address.
        address tloadTestContract = _prepareTloadTest();

        // Ensure the deployment was successful.
        if (tloadTestContract == address(0)) {
            revert TloadTestContractDeploymentFailed();
        }

        // Determine if TSTORE is supported.
        _tstoreInitialSupport = StorageTstorish.data().tstoreSupport = _testTload(tloadTestContract);

        if (_tstoreInitialSupport) {
            // If TSTORE is supported, set functions to their versions that use
            // tstore/tload directly without support checks.
            _setTstorish = _setTstore;
            _getTstorish = _getTstore;
            _clearTstorish = _clearTstore;
        } else {
            // If TSTORE is not supported, set functions to their versions that 
            // fallback to sstore/sload until tstoreSupport is true.
            _setTstorish = _setTstorishWithSstoreFallback;
            _getTstorish = _getTstorishWithSloadFallback;
            _clearTstorish = _clearTstorishWithSstoreFallback;
        }

        // Set the address of the deployed TLOAD test contract as an immutable.
        _tloadTestContract = tloadTestContract;
    }

    /**
     * @dev Called internally when tstore is activated by an external call to 
     *      `__activateTstore`. Developers must override this function and handle
     *      relevant transfers of data from regular storage to transient storage *OR*
     *      revert the transaction if it is in a state that should not support the activation
     *      of tstore.
     */
    function _onTstoreSupportActivated() internal virtual;

    /**
     * @dev External function to activate TSTORE usage. Does not need to be
     *      called if TSTORE is supported from deployment, and only needs to be
     *      called once. Reverts if TSTORE has already been activated or if the
     *      opcode is not available. Note that this must be called directly from
     *      an externally-owned account to avoid potential reentrancy issues.
     */
    function __activateTstore() external {
        // Determine if TSTORE can potentially be activated.
        if (_tstoreInitialSupport || StorageTstorish.data().tstoreSupport) {
            revert TStoreAlreadyActivated();
        }

        // Determine if TSTORE can be activated and revert if not.
        if (!_testTload(_tloadTestContract)) {
            revert TStoreNotSupported();
        }

        // Mark TSTORE as activated.
        StorageTstorish.data().tstoreSupport = true;

        _onTstoreSupportActivated();
    }

    /**
     * @dev Private function to set a TSTORISH value. Assigned to _setTstorish 
     *      internal function variable at construction if chain has tstore support.
     *
     * @param storageSlot The slot to write the TSTORISH value to.
     * @param value       The value to write to the given storage slot.
     */
    function _setTstore(uint256 storageSlot, uint256 value) internal {
        assembly {
            tstore(storageSlot, value)
        }
    }

    /**
     * @dev Private function to set a TSTORISH value with sstore fallback. 
     *      Assigned to _setTstorish internal function variable at construction
     *      if chain does not have tstore support.
     *
     * @param storageSlot The slot to write the TSTORISH value to.
     * @param value       The value to write to the given storage slot.
     */
    function _setTstorishWithSstoreFallback(uint256 storageSlot, uint256 value) internal {
        if (StorageTstorish.data().tstoreSupport) {
            assembly {
                tstore(storageSlot, value)
            }
        } else {
            assembly {
                sstore(storageSlot, value)
            }
        }
    }

    /**
     * @dev Private function to read a TSTORISH value. Assigned to _getTstorish
     *      internal function variable at construction if chain has tstore support.
     *
     * @param storageSlot The slot to read the TSTORISH value from.
     *
     * @return value The TSTORISH value at the given storage slot.
     */
    function _getTstore(
        uint256 storageSlot
    ) internal view returns (uint256 value) {
        assembly {
            value := tload(storageSlot)
        }
    }

    /**
     * @dev Private function to read a TSTORISH value with sload fallback. 
     *      Assigned to _getTstorish internal function variable at construction
     *      if chain does not have tstore support.
     *
     * @param storageSlot The slot to read the TSTORISH value from.
     *
     * @return value The TSTORISH value at the given storage slot.
     */
    function _getTstorishWithSloadFallback(
        uint256 storageSlot
    ) internal view returns (uint256 value) {
        if (StorageTstorish.data().tstoreSupport) {
            assembly {
                value := tload(storageSlot)
            }
        } else {
            assembly {
                value := sload(storageSlot)
            }
        }
    }

    /**
     * @dev Private function to clear a TSTORISH value. Assigned to _clearTstorish internal 
     *      function variable at construction if chain has tstore support.
     *
     * @param storageSlot The slot to clear the TSTORISH value for.
     */
    function _clearTstore(uint256 storageSlot) internal {
        assembly {
            tstore(storageSlot, 0)
        }
    }

    /**
     * @dev Private function to clear a TSTORISH value with sstore fallback. 
     *      Assigned to _clearTstorish internal function variable at construction
     *      if chain does not have tstore support.
     *
     * @param storageSlot The slot to clear the TSTORISH value for.
     */
    function _clearTstorishWithSstoreFallback(uint256 storageSlot) internal {
        if (StorageTstorish.data().tstoreSupport) {
            assembly {
                tstore(storageSlot, 0)
            }
        } else {
            assembly {
                sstore(storageSlot, 0)
            }
        }
    }

    /**
     * @dev Private function to copy a value from storage to transient storage at the same slot.
     *      Useful when tstore is activated on a chain that didn't initially support it.
     */
    function _copyFromStorageToTransient(uint256 storageSlot) internal {
        if (StorageTstorish.data().tstoreSupport) {
            assembly {
                tstore(storageSlot, sload(storageSlot))
            }
        } else {
            revert TStoreNotSupported();
        }
    }

    /**
     * @dev Private function to deploy a test contract that utilizes TLOAD as
     *      part of its fallback logic.
     */
    function _prepareTloadTest() private returns (address contractAddress) {
        // Utilize assembly to deploy a contract testing TLOAD support.
        assembly {
            // Write the contract deployment code payload to scratch space.
            mstore(0, _TLOAD_TEST_PAYLOAD)

            // Deploy the contract.
            contractAddress := create(
                0,
                _TLOAD_TEST_PAYLOAD_OFFSET,
                _TLOAD_TEST_PAYLOAD_LENGTH
            )
        }
    }

    /**
     * @dev Private view function to determine if TSTORE/TLOAD are supported by
     *      the current EVM implementation by attempting to call the test
     *      contract, which utilizes TLOAD as part of its fallback logic.
     */
    function _testTload(
        address tloadTestContract
    ) private view returns (bool ok) {
        // Call the test contract, which will perform a TLOAD test. If the call
        // does not revert, then TLOAD/TSTORE is supported. Do not forward all
        // available gas, as all forwarded gas will be consumed on revert.
        (ok, ) = tloadTestContract.staticcall{ gas: gasleft() / 10 }("");
    }
}

lib/tm-core-lib/src/utils/security/TstorishReentrancyGuard.sol

pragma solidity ^0.8.24;

import "../misc/Tstorish.sol";

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 */
abstract contract TstorishReentrancyGuard is Tstorish {

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

    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

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

    constructor() Tstorish() {
        if (!_tstoreInitialSupport) {
            _setTstorish(REENTRANCY_GUARD_STORAGE, 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 (_getTstorish(REENTRANCY_GUARD_STORAGE) == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _setTstorish(REENTRANCY_GUARD_STORAGE, ENTERED);
    }

    function _nonReentrantAfter() private {
        _setTstorish(REENTRANCY_GUARD_STORAGE, NOT_ENTERED);
    }

    function _onTstoreSupportActivated() internal virtual override {
        _copyFromStorageToTransient(REENTRANCY_GUARD_STORAGE);
    }
}

lib/tm-core-lib/src/utils/structs/EnumerableSet.sol

pragma solidity ^0.8.4;

/**
 * @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.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [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 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;
    }

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

        /// @solidity memory-safe-assembly
        assembly {
            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 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;

        /// @solidity memory-safe-assembly
        assembly {
            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 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;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 9999999,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    ":@limitbreak/creator-token-transfer-validator/=lib/creator-token-transfer-validator/",
    ":@limitbreak/permit-c/=lib/payment-processor-v2/lib/PermitC/src/",
    ":@limitbreak/tm-cloner/=lib/tm-cloner/",
    ":@limitbreak/tm-core-lib/=lib/tm-core-lib/",
    ":@limitbreak/tm-extension-registry/=lib/tm-extension-registry/",
    ":@limitbreak/tm-role-server/=lib/tm-role-server/",
    ":@limitbreak/tm-template-factory/=lib/tm-template-factory/",
    ":@limitbreak/tm-web2-gateway/=lib/tm-web2-gateway/",
    ":@limitbreak/trusted-forwarder/=lib/payment-processor-v2/lib/TrustedForwarder/src/",
    ":@limitbreak/wrapped-native/=lib/wrapped-native/",
    ":@opensea/tstorish/=lib/creator-token-standards/lib/tstorish/src/",
    ":@openzeppelin/=lib/payment-processor-v2/lib/openzeppelin-contracts/",
    ":@rari-capital/solmate/=lib/payment-processor-v2/lib/solmate/",
    ":ERC721A/=lib/creator-token-standards/lib/ERC721A/contracts/",
    ":PermitC/=lib/payment-processor-v2/lib/PermitC/",
    ":TrustedForwarder/=lib/TrustedForwarder/",
    ":creator-token-standards/=lib/creator-token-standards/",
    ":creator-token-transfer-validator/=lib/creator-token-transfer-validator/src/",
    ":ds-test/=lib/forge-std/lib/ds-test/src/",
    ":erc4626-tests/=lib/payment-processor-v2/lib/openzeppelin-contracts/lib/erc4626-tests/",
    ":erc721a/=lib/creator-token-standards/lib/ERC721A/",
    ":fake-contracts/=lib/fake-contracts/src/",
    ":forge-gas-metering/=lib/payment-processor-v2/lib/PermitC/lib/forge-gas-metering/",
    ":forge-std/=lib/forge-std/src/",
    ":multisig/=lib/multisig/",
    ":murky/=lib/payment-processor-v2/lib/murky/",
    ":openzeppelin-contracts/=lib/payment-processor-v2/lib/openzeppelin-contracts/",
    ":openzeppelin/=lib/payment-processor-v2/lib/openzeppelin-contracts/contracts/",
    ":payment-processor-v2/=lib/payment-processor-v2/",
    ":solady/=lib/payment-processor-v2/lib/PermitC/lib/forge-gas-metering/lib/solady/",
    ":solmate/=lib/payment-processor-v2/lib/solmate/src/",
    ":tm-cloner/=lib/tm-cloner/src/",
    ":tm-core-lib/=lib/tm-core-lib/src/",
    ":tm-extension-registry/=lib/tm-extension-registry/src/",
    ":tm-role-server/=lib/tm-role-server/src/",
    ":tm-template-factory/=lib/tm-template-factory/src/",
    ":tm-web2-gateway/=lib/tm-web2-gateway/src/",
    ":tstorish/=lib/creator-token-standards/lib/tstorish/src/",
    ":wrapped-native/=lib/wrapped-native/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.