ETH Price: $1,841.05 (-1.17%)
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

> 10 Internal Transactions found.

Latest 12 internal transactions

Advanced mode:
Parent Transaction Hash Method Block
From
To
0x3d602d80219263692025-02-25 22:36:35363 days ago1740522995
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x3d602d80217808912025-02-05 14:28:47383 days ago1738765727
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x3d602d80217415052025-01-31 2:23:11388 days ago1738290191
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x3d602d80217352392025-01-30 5:23:47389 days ago1738214627
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x3d602d80214712882024-12-24 8:58:23426 days ago1735030703
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x3d602d80214172642024-12-16 19:46:35434 days ago1734378395
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x3d602d80212940862024-11-29 14:57:11451 days ago1732892231
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x3d602d80212933222024-11-29 12:22:23451 days ago1732882943
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x3d602d80212933182024-11-29 12:21:35451 days ago1732882895
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x60806040212865132024-11-28 13:31:47452 days ago1732800707
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x60806040212865132024-11-28 13:31:47452 days ago1732800707
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
0x60806040212865132024-11-28 13:31:47452 days ago1732800707
0x61804D3B...0d89e4E09
 Contract Creation0 ETH
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

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

Contract Source Code Verified (Exact Match)

Contract Name:
LegionSaleFactory

Compiler Version
v0.8.25+commit.b61c2a91

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

import {ILegionSaleFactory} from "./interfaces/ILegionSaleFactory.sol";

import {LegionFixedPriceSale} from "./LegionFixedPriceSale.sol";
import {LegionPreLiquidSale} from "./LegionPreLiquidSale.sol";
import {LegionSealedBidAuction} from "./LegionSealedBidAuction.sol";

/**
 * @title Legion Sale Factory.
 * @author Legion.
 * @notice A factory contract for deploying proxy instances of Legion sales.
 */
contract LegionSaleFactory is ILegionSaleFactory, Ownable {
    using Clones for address;

    /// @dev The LegionFixedPriceSale implementation contract.
    address public immutable fixedPriceSaleTemplate = address(new LegionFixedPriceSale());

    /// @dev The LegionPreLiquidSale implementation contract.
    address public immutable preLiquidSaleTemplate = address(new LegionPreLiquidSale());

    /// @dev The LegionSealedBidAuction implementation contract.
    address public immutable sealedBidAuctionTemplate = address(new LegionSealedBidAuction());

    /**
     * @dev Constructor to initialize the LegionSaleFactory.
     *
     * @param newOwner The owner of the factory contract.
     */
    constructor(address newOwner) Ownable(newOwner) {}

    /**
     * @notice See {ILegionSaleFactory-createFixedPriceSale}.
     */
    function createFixedPriceSale(LegionFixedPriceSale.FixedPriceSaleConfig calldata fixedPriceSaleConfig)
        external
        onlyOwner
        returns (address payable fixedPriceSaleInstance)
    {
        /// Deploy a LegionFixedPriceSale instance
        fixedPriceSaleInstance = payable(fixedPriceSaleTemplate.clone());

        /// Emit successfully NewFixedPriceSaleCreated
        emit NewFixedPriceSaleCreated(fixedPriceSaleInstance, fixedPriceSaleConfig);

        /// Initialize the LegionFixedPriceSale with the provided configuration
        LegionFixedPriceSale(fixedPriceSaleInstance).initialize(fixedPriceSaleConfig);
    }

    /**
     * @notice See {ILegionSaleFactory-createPreLiquidSale}.
     */
    function createPreLiquidSale(LegionPreLiquidSale.PreLiquidSaleConfig calldata preLiquidSaleConfig)
        external
        onlyOwner
        returns (address payable preLiquidSaleInstance)
    {
        /// Deploy a LegionPreLiquidSale instance
        preLiquidSaleInstance = payable(preLiquidSaleTemplate.clone());

        /// Emit successfully NewPreLiquidSaleCreated
        emit NewPreLiquidSaleCreated(preLiquidSaleInstance, preLiquidSaleConfig);

        /// Initialize the LegionPreLiquidSale with the provided configuration
        LegionPreLiquidSale(preLiquidSaleInstance).initialize(preLiquidSaleConfig);
    }

    /**
     * @notice See {ILegionSaleFactory-createSealedBidAuction}.
     */
    function createSealedBidAuction(LegionSealedBidAuction.SealedBidAuctionConfig calldata sealedBidAuctionConfig)
        external
        onlyOwner
        returns (address payable sealedBidAuctionInstance)
    {
        /// Deploy a LegionSealedBidAuction instance
        sealedBidAuctionInstance = payable(sealedBidAuctionTemplate.clone());

        /// Emit successfully NewSealedBidAuctionCreated
        emit NewSealedBidAuctionCreated(sealedBidAuctionInstance, sealedBidAuctionConfig);

        /// Initialize the LegionSealedBidAuction with the provided configuration
        LegionSealedBidAuction(sealedBidAuctionInstance).initialize(sealedBidAuctionConfig);
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        return clone(implementation, 0);
    }

    /**
     * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
     * to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function clone(address implementation, uint256 value) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(value, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        return cloneDeterministic(implementation, salt, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
     * a `value` parameter to send native currency to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneDeterministic(
        address implementation,
        bytes32 salt,
        uint256 value
    ) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(value, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
import {ILegionFixedPriceSale} from "./ILegionFixedPriceSale.sol";
import {ILegionPreLiquidSale} from "./ILegionPreLiquidSale.sol";
import {ILegionSealedBidAuction} from "./ILegionSealedBidAuction.sol";

interface ILegionSaleFactory {
    /**
     * @notice This event is emitted when a new fixed price sale is deployed and initialized.
     *
     * @param saleInstance The address of the sale instance deployed.
     * @param fixedPriceSaleConfig The configuration for the fixed price sale.
     */
    event NewFixedPriceSaleCreated(
        address saleInstance, ILegionFixedPriceSale.FixedPriceSaleConfig fixedPriceSaleConfig
    );

    /**
     * @notice This event is emitted when a new pre-liquid sale is deployed and initialized.
     *
     * @param saleInstance The address of the sale instance deployed.
     * @param preLiquidSaleConfig The configuration for the pre-liquid sale.
     */
    event NewPreLiquidSaleCreated(address saleInstance, ILegionPreLiquidSale.PreLiquidSaleConfig preLiquidSaleConfig);

    /**
     * @notice This event is emitted when a new sealed bid auction is deployed and initialized.
     *
     * @param saleInstance The address of the sale instance deployed.
     * @param sealedBidAuctionConfig The configuration for the sealed bid auction.
     */
    event NewSealedBidAuctionCreated(
        address saleInstance, ILegionSealedBidAuction.SealedBidAuctionConfig sealedBidAuctionConfig
    );

    /**
     * @notice Deploy a LegionFixedPriceSale contract.
     *
     * @param fixedPriceSaleConfig The configuration for the fixed price sale.
     *
     * @return fixedPriceSaleInstance The address of the fixedPriceSaleInstance deployed.
     */
    function createFixedPriceSale(ILegionFixedPriceSale.FixedPriceSaleConfig calldata fixedPriceSaleConfig)
        external
        returns (address payable fixedPriceSaleInstance);

    /**
     * @notice Deploy a LegionPreLiquidSale contract.
     *
     * @param preLiquidSaleConfig The configuration for the pre-liquid sale.
     *
     * @return preLiquidSaleInstance The address of the preLiquidSaleInstance deployed.
     */
    function createPreLiquidSale(ILegionPreLiquidSale.PreLiquidSaleConfig calldata preLiquidSaleConfig)
        external
        returns (address payable preLiquidSaleInstance);

    /**
     * @notice Deploy a LegionSealedBidAuction contract.
     *
     * @param sealedBidAuctionConfig The configuration for the sealed bid auction.
     *
     * @return sealedBidAuctionInstance The address of the sealedBidAuctionInstance deployed.
     */
    function createSealedBidAuction(ILegionSealedBidAuction.SealedBidAuctionConfig calldata sealedBidAuctionConfig)
        external
        returns (address payable sealedBidAuctionInstance);
}

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

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

import {ILegionAddressRegistry} from "./interfaces/ILegionAddressRegistry.sol";
import {ILegionFixedPriceSale} from "./interfaces/ILegionFixedPriceSale.sol";
import {ILegionLinearVesting} from "./interfaces/ILegionLinearVesting.sol";
import {ILegionVestingFactory} from "./interfaces/ILegionVestingFactory.sol";

/**
 * @title Legion Fixed Price Sale.
 * @author Legion.
 * @notice A contract used to execute fixed price sales of ERC20 tokens after TGE.
 */
contract LegionFixedPriceSale is LegionBaseSale, ILegionFixedPriceSale {
    using SafeERC20 for IERC20;

    /// @dev The prefund period duration in seconds.
    uint256 private prefundPeriodSeconds;

    /// @dev The prefund allocation period duration in seconds.
    uint256 private prefundAllocationPeriodSeconds;

    /// @dev The price of the token being sold denominated in the token used to raise capital.
    uint256 private tokenPrice;

    /// @dev The unix timestamp (seconds) of the block when the prefund starts.
    uint256 private prefundStartTime;

    /// @dev The unix timestamp (seconds) of the block when the prefund ends.
    uint256 private prefundEndTime;

    /**
     * @notice See {ILegionFixedPriceSale-initialize}.
     */
    function initialize(FixedPriceSaleConfig calldata fixedPriceSaleConfig) external initializer {
        /// Initialize fixed price sale configuration
        prefundPeriodSeconds = fixedPriceSaleConfig.prefundPeriodSeconds;
        prefundAllocationPeriodSeconds = fixedPriceSaleConfig.prefundAllocationPeriodSeconds;
        salePeriodSeconds = fixedPriceSaleConfig.salePeriodSeconds;
        refundPeriodSeconds = fixedPriceSaleConfig.refundPeriodSeconds;
        lockupPeriodSeconds = fixedPriceSaleConfig.lockupPeriodSeconds;
        vestingDurationSeconds = fixedPriceSaleConfig.vestingDurationSeconds;
        vestingCliffDurationSeconds = fixedPriceSaleConfig.vestingCliffDurationSeconds;
        legionFeeOnCapitalRaisedBps = fixedPriceSaleConfig.legionFeeOnCapitalRaisedBps;
        legionFeeOnTokensSoldBps = fixedPriceSaleConfig.legionFeeOnTokensSoldBps;
        minimumPledgeAmount = fixedPriceSaleConfig.minimumPledgeAmount;
        tokenPrice = fixedPriceSaleConfig.tokenPrice;
        bidToken = fixedPriceSaleConfig.bidToken;
        askToken = fixedPriceSaleConfig.askToken;
        projectAdmin = fixedPriceSaleConfig.projectAdmin;
        addressRegistry = fixedPriceSaleConfig.addressRegistry;

        /// Calculate and set prefundStartTime, prefundEndTime, startTime, endTime and refundEndTime
        prefundStartTime = block.timestamp;
        prefundEndTime = prefundStartTime + fixedPriceSaleConfig.prefundPeriodSeconds;
        startTime = prefundEndTime + fixedPriceSaleConfig.prefundAllocationPeriodSeconds;
        endTime = startTime + fixedPriceSaleConfig.salePeriodSeconds;
        refundEndTime = endTime + fixedPriceSaleConfig.refundPeriodSeconds;

        /// Check if lockupPeriodSeconds is less than refundPeriodSeconds
        /// lockupEndTime should be at least refundEndTime
        if (fixedPriceSaleConfig.lockupPeriodSeconds <= fixedPriceSaleConfig.refundPeriodSeconds) {
            /// If yes, set lockupEndTime to be refundEndTime
            lockupEndTime = refundEndTime;
        } else {
            /// If no, calculate the lockupEndTime
            lockupEndTime = endTime + fixedPriceSaleConfig.lockupPeriodSeconds;
        }

        // Set the vestingStartTime to begin when lockupEndTime is reached
        vestingStartTime = lockupEndTime;

        /// Verify if the sale configuration is valid
        _verifyValidConfig(fixedPriceSaleConfig);

        /// Cache Legion addresses from `LegionAddressRegistry`
        legionBouncer = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_BOUNCER_ID);
        legionSigner = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_SIGNER_ID);
        legionFeeReceiver = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_FEE_RECEIVER_ID);
        vestingFactory = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_VESTING_FACTORY_ID);
    }

    /**
     * @notice See {ILegionFixedPriceSale-pledgeCapital}.
     */
    function pledgeCapital(uint256 amount, bytes memory signature) external {
        /// Verify that the investor is allowed to pledge capital
        _verifyLegionSignature(signature);

        /// Verify that pledge is not during the prefund allocation period
        _verifyNotPrefundAllocationPeriod();

        /// Verify that the sale has not ended
        _verifySaleHasNotEnded();

        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that the amount pledged is more than the minimum required
        _verifyMinimumPledgeAmount(amount);

        /// Increment total capital pledged from investors
        totalCapitalPledged += amount;

        /// Increment total pledged capital for the investor
        investorPositions[msg.sender].pledgedCapital += amount;

        /// Flag if capital is pledged during the prefund period
        bool isPrefund = _isPrefund();

        /// Emit successfully CapitalPledged
        emit CapitalPledged(amount, msg.sender, isPrefund, block.timestamp);

        /// Transfer the pledged capital to the contract
        IERC20(bidToken).safeTransferFrom(msg.sender, address(this), amount);
    }

    /**
     * @notice See {ILegionFixedPriceSale-publishSaleResults}.
     */
    function publishSaleResults(bytes32 merkleRoot, uint256 tokensAllocated, uint8 askTokenDecimals)
        external
        onlyLegion
    {
        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that the refund period is over
        _verifyRefundPeriodIsOver();

        /// Verify that sale results are not already published
        _verifyCanPublishSaleResults();

        /// Set the merkle root for claiming tokens
        claimTokensMerkleRoot = merkleRoot;

        /// Set the total tokens to be allocated by the Project team
        totalTokensAllocated = tokensAllocated;

        /// Set the total capital raised to be withdrawn by the project
        totalCapitalRaised = (tokensAllocated * tokenPrice) / (10 ** askTokenDecimals);

        /// Emit successfully SaleResultsPublished
        emit SaleResultsPublished(merkleRoot, tokensAllocated);
    }

    /**
     * @notice See {ILegionFixedPriceSale-saleConfiguration}.
     */
    function saleConfiguration() external view returns (FixedPriceSaleConfig memory saleConfig) {
        /// Get the fixed price sale config
        saleConfig = FixedPriceSaleConfig(
            prefundPeriodSeconds,
            prefundAllocationPeriodSeconds,
            salePeriodSeconds,
            refundPeriodSeconds,
            lockupPeriodSeconds,
            vestingDurationSeconds,
            vestingCliffDurationSeconds,
            legionFeeOnCapitalRaisedBps,
            legionFeeOnTokensSoldBps,
            minimumPledgeAmount,
            tokenPrice,
            bidToken,
            askToken,
            projectAdmin,
            addressRegistry
        );
    }

    /**
     * @notice See {ILegionFixedPriceSale-saleStatus}.
     */
    function saleStatus() external view returns (FixedPriceSaleStatus memory fixedPriceSaleStatus) {
        /// Get the fixed price sale status
        fixedPriceSaleStatus = FixedPriceSaleStatus(
            prefundStartTime,
            prefundEndTime,
            startTime,
            endTime,
            refundEndTime,
            lockupEndTime,
            vestingStartTime,
            totalCapitalPledged,
            totalTokensAllocated,
            totalCapitalRaised,
            claimTokensMerkleRoot,
            excessCapitalMerkleRoot,
            isCanceled,
            tokensSupplied,
            capitalWithdrawn
        );
    }

    /**
     * @notice Verify if prefund period is active (before sale startTime).
     */
    function _isPrefund() private view returns (bool) {
        return (block.timestamp < prefundEndTime);
    }

    /**
     * @notice Verify if prefund allocation period is active (after prefundEndTime and before sale startTime).
     */
    function _verifyNotPrefundAllocationPeriod() private view {
        if (block.timestamp >= prefundEndTime && block.timestamp < startTime) revert PrefundAllocationPeriodNotEnded();
    }

    /**
     * @notice Verify if the sale configuration is valid.
     *
     * @param _fixedPriceSaleConfig The configuration for the fixed price sale.
     */
    function _verifyValidConfig(FixedPriceSaleConfig calldata _fixedPriceSaleConfig) private pure {
        /// Check for zero addresses provided
        if (
            _fixedPriceSaleConfig.bidToken == address(0) || _fixedPriceSaleConfig.projectAdmin == address(0)
                || _fixedPriceSaleConfig.addressRegistry == address(0)
        ) {
            revert ZeroAddressProvided();
        }

        /// Check for zero values provided
        if (
            _fixedPriceSaleConfig.prefundPeriodSeconds == 0 || _fixedPriceSaleConfig.prefundAllocationPeriodSeconds == 0
                || _fixedPriceSaleConfig.salePeriodSeconds == 0 || _fixedPriceSaleConfig.refundPeriodSeconds == 0
                || _fixedPriceSaleConfig.lockupPeriodSeconds == 0 || _fixedPriceSaleConfig.tokenPrice == 0
        ) revert ZeroValueProvided();

        /// Check if prefund, allocation, sale, refund and lockup periods are longer than allowed
        if (
            _fixedPriceSaleConfig.prefundPeriodSeconds > THREE_MONTHS
                || _fixedPriceSaleConfig.prefundAllocationPeriodSeconds > TWO_WEEKS
                || _fixedPriceSaleConfig.salePeriodSeconds > THREE_MONTHS
                || _fixedPriceSaleConfig.refundPeriodSeconds > TWO_WEEKS
                || _fixedPriceSaleConfig.lockupPeriodSeconds > SIX_MONTHS
        ) revert InvalidPeriodConfig();

        /// Check if prefund, allocation, sale, refund and lockup periods are shorter than allowed
        if (
            _fixedPriceSaleConfig.prefundPeriodSeconds < ONE_HOUR
                || _fixedPriceSaleConfig.prefundAllocationPeriodSeconds < ONE_HOUR
                || _fixedPriceSaleConfig.salePeriodSeconds < ONE_HOUR
                || _fixedPriceSaleConfig.refundPeriodSeconds < ONE_HOUR
                || _fixedPriceSaleConfig.lockupPeriodSeconds < ONE_HOUR
        ) revert InvalidPeriodConfig();
    }
}

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {ILegionAddressRegistry} from "./interfaces/ILegionAddressRegistry.sol";
import {ILegionPreLiquidSale} from "./interfaces/ILegionPreLiquidSale.sol";
import {ILegionLinearVesting} from "./interfaces/ILegionLinearVesting.sol";
import {ILegionVestingFactory} from "./interfaces/ILegionVestingFactory.sol";

/**
 * @title Legion Pre-Liquid Sale.
 * @author Legion.
 * @notice A contract used to execute pre-liquid sales of ERC20 tokens before TGE.
 */
contract LegionPreLiquidSale is ILegionPreLiquidSale, Initializable {
    using SafeERC20 for IERC20;

    /// @dev The refund period duration in seconds.
    uint256 private refundPeriodSeconds;

    /// @dev The vesting schedule duration for the token sold in seconds.
    uint256 private vestingDurationSeconds;

    /// @dev The vesting cliff duration for the token sold in seconds.
    uint256 private vestingCliffDurationSeconds;

    /// @dev The token allocation amount released to investors after TGE with 18 decimals precision.
    uint256 private tokenAllocationOnTGERate;

    /// @dev Legion's fee on capital raised in BPS (Basis Points).
    uint256 private legionFeeOnCapitalRaisedBps;

    /// @dev Legion's fee on tokens sold in BPS (Basis Points).
    uint256 private legionFeeOnTokensSoldBps;

    /// @dev The merkle root for verification of token distribution amounts.
    bytes32 private saftMerkleRoot;

    /// @dev The address of the token used for raising capital.
    address private bidToken;

    /// @dev The admin address of the project raising capital.
    address private projectAdmin;

    /// @dev The address of Legion's Address Registry contract.
    address private addressRegistry;

    /// @dev The admin address of Legion.
    address private legionBouncer;

    /// @dev The address of Legion fee receiver.
    address private legionFeeReceiver;

    /// @dev The address of Legion's Vesting Factory contract.
    address private vestingFactory;

    /// @dev The address of the token being sold to investors.
    address private askToken;

    /// @dev The unix timestamp (seconds) of the block when the vesting starts.
    uint256 private vestingStartTime;

    /// @dev The total supply of the ask token
    uint256 private askTokenTotalSupply;

    /// @dev The total capital invested by investors.
    uint256 private totalCapitalInvested;

    /// @dev The total amount of tokens allocated to investors.
    uint256 private totalTokensAllocated;

    /// @dev The total capital withdrawn by the Project, from the sale.
    uint256 private totalCapitalWithdrawn;

    /// @dev Whether the sale has been canceled or not.
    bool private isCanceled;

    /// @dev Whether the ask tokens have been supplied to the sale.
    bool private askTokensSupplied;

    /// @dev Whether investment is being accepted by the Project.
    bool private investmentAccepted;

    /// @dev Mapping of investor address to investor position.
    mapping(address investorAddress => InvestorPosition investorPosition) public investorPositions;

    /// @dev Constant representing 2 weeks in seconds.
    uint256 private constant TWO_WEEKS = 1209600;

    /// @dev Constant representing the LEGION_BOUNCER unique ID
    bytes32 private constant LEGION_BOUNCER_ID = bytes32("LEGION_BOUNCER");

    /// @dev Constant representing the LEGION_FEE_RECEIVER unique ID
    bytes32 private constant LEGION_FEE_RECEIVER_ID = bytes32("LEGION_FEE_RECEIVER");

    /// @dev Constant representing the LEGION_VESTING_FACTORY unique ID
    bytes32 private constant LEGION_VESTING_FACTORY_ID = bytes32("LEGION_VESTING_FACTORY");

    /**
     * @notice Throws if called by any account other than Legion.
     */
    modifier onlyLegion() {
        if (msg.sender != legionBouncer) revert NotCalledByLegion();
        _;
    }

    /**
     * @notice Throws if called by any account other than the Project.
     */
    modifier onlyProject() {
        if (msg.sender != projectAdmin) revert NotCalledByProject();
        _;
    }

    /**
     * @notice LegionPreLiquidSale constructor.
     */
    constructor() {
        /// Disable initialization
        _disableInitializers();
    }

    /**
     * @notice See {ILegionPreLiquidSale-initialize}.
     */
    function initialize(PreLiquidSaleConfig calldata preLiquidSaleConfig) external initializer {
        /// Initialize pre-liquid sale configuration
        refundPeriodSeconds = preLiquidSaleConfig.refundPeriodSeconds;
        vestingDurationSeconds = preLiquidSaleConfig.vestingDurationSeconds;
        vestingCliffDurationSeconds = preLiquidSaleConfig.vestingCliffDurationSeconds;
        tokenAllocationOnTGERate = preLiquidSaleConfig.tokenAllocationOnTGERate;
        legionFeeOnCapitalRaisedBps = preLiquidSaleConfig.legionFeeOnCapitalRaisedBps;
        legionFeeOnTokensSoldBps = preLiquidSaleConfig.legionFeeOnTokensSoldBps;
        saftMerkleRoot = preLiquidSaleConfig.saftMerkleRoot;
        bidToken = preLiquidSaleConfig.bidToken;
        projectAdmin = preLiquidSaleConfig.projectAdmin;
        addressRegistry = preLiquidSaleConfig.addressRegistry;

        /// Accepting investment is set to true by default
        investmentAccepted = true;

        /// Verify if the sale configuration is valid
        _verifyValidConfig(preLiquidSaleConfig);

        /// Cache Legion addresses from `LegionAddressRegistry`
        legionBouncer = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_BOUNCER_ID);
        legionFeeReceiver = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_FEE_RECEIVER_ID);
        vestingFactory = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_VESTING_FACTORY_ID);
    }

    /**
     * @notice See {ILegionPreLiquidSale-invest}.
     */
    function invest(
        uint256 amount,
        uint256 saftInvestAmount,
        uint256 tokenAllocationRate,
        bytes32 saftHash,
        bytes32[] calldata proof
    ) external {
        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that investment is accepted by the Project
        _verifyInvestmentAccepted();

        /// Load the investor position
        InvestorPosition storage position = investorPositions[msg.sender];

        /// Increment total capital invested from investors
        totalCapitalInvested += amount;

        /// Increment total capital for the investor
        position.investedCapital += amount;

        // Cache the capital invest timestamp
        if (position.cachedInvestTimestamp == 0) {
            position.cachedInvestTimestamp = block.timestamp;
        }

        /// Cache the SAFT amount the investor is allowed to invest
        if (position.cachedSAFTInvestAmount != saftInvestAmount) {
            position.cachedSAFTInvestAmount = saftInvestAmount;
        }

        /// Cache the token allocation rate in 18 decimals precision
        if (position.cachedTokenAllocationRate != tokenAllocationRate) {
            position.cachedTokenAllocationRate = tokenAllocationRate;
        }

        /// Cache the hash of the SAFT signed by the investor
        if (position.cachedSAFTHash != saftHash) {
            position.cachedSAFTHash = saftHash;
        }

        /// Verify that the investor position is valid
        _verifyValidPosition(msg.sender, proof);

        /// Emit successfully CapitalInvested
        emit CapitalInvested(amount, msg.sender, tokenAllocationRate, saftHash, block.timestamp);

        /// Transfer the invested capital to the contract
        IERC20(bidToken).safeTransferFrom(msg.sender, address(this), amount);
    }

    /**
     * @notice See {ILegionPreLiquidSale-refund}.
     */
    function refund() external {
        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that the investor can get a refund
        _verifyRefundPeriodIsNotOver(msg.sender);

        /// Load the investor position
        InvestorPosition storage position = investorPositions[msg.sender];

        /// Cache the amount to refund in memory
        uint256 amountToRefund = position.investedCapital;

        /// Revert in case there's nothing to refund
        if (amountToRefund == 0) revert InvalidRefundAmount();

        /// Set the total invested capital for the investor to 0
        position.investedCapital = 0;

        /// Decrement total capital invested from investors
        totalCapitalInvested -= amountToRefund;

        /// Emit successfully CapitalRefunded
        emit CapitalRefunded(amountToRefund, msg.sender);

        /// Transfer the refunded amount back to the investor
        IERC20(bidToken).safeTransfer(msg.sender, amountToRefund);
    }

    /**
     * @notice See {ILegionPreLiquidSale-setTokenDetails}.
     */
    function publishTgeDetails(
        address _askToken,
        uint256 _askTokenTotalSupply,
        uint256 _vestingStartTime,
        uint256 _totalTokensAllocated
    ) external onlyLegion {
        /// Verify that the sale has not been canceled
        _verifySaleNotCanceled();

        /// Set the address of the token ditributed to investors
        askToken = _askToken;

        /// Set the total supply of the token distributed to investors
        askTokenTotalSupply = _askTokenTotalSupply;

        /// Set the vesting start time block timestamp
        vestingStartTime = _vestingStartTime;

        /// Set the total allocated amount of token for distribution.
        totalTokensAllocated = _totalTokensAllocated;

        /// Set `investmentAccepted` status to false
        if (investmentAccepted) investmentAccepted = false;

        /// Emit successfully TgeDetailsPublished
        emit TgeDetailsPublished(_askToken, _askTokenTotalSupply, _vestingStartTime, _totalTokensAllocated);
    }

    /**
     * @notice See {ILegionPreLiquidSale-supplyTokens}.
     */
    function supplyAskTokens(uint256 amount, uint256 legionFee) external onlyProject {
        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that tokens can be supplied for distribution
        _verifyCanSupplyTokens(amount);

        /// Calculate and verify Legion Fee
        if (legionFee != (legionFeeOnTokensSoldBps * amount) / 10000) revert InvalidFeeAmount();

        /// Flag that ask tokens have been supplied
        askTokensSupplied = true;

        /// Emit successfully TokensSuppliedForDistribution
        emit TokensSuppliedForDistribution(amount, legionFee);

        /// Transfer the allocated amount of tokens for distribution
        IERC20(askToken).safeTransferFrom(msg.sender, address(this), amount);

        /// Transfer the Legion fee to the Legion fee receiver address
        if (legionFee != 0) IERC20(askToken).safeTransferFrom(msg.sender, legionFeeReceiver, legionFee);
    }

    /**
     * @notice See {ILegionPreLiquidSale-updateSAFTMerkleRoot}.
     */
    function updateSAFTMerkleRoot(bytes32 merkleRoot) external onlyLegion {
        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that tokens for distribution have not been allocated
        _verifyTokensNotAllocated();

        /// Set the new SAFT merkle root
        saftMerkleRoot = merkleRoot;

        /// Emit successfully SAFTMerkleRootUpdated
        emit SAFTMerkleRootUpdated(merkleRoot);
    }

    /**
     * @notice See {ILegionPreLiquidSale-updateVestingTerms}.
     */
    function updateVestingTerms(
        uint256 _vestingDurationSeconds,
        uint256 _vestingCliffDurationSeconds,
        uint256 _tokenAllocationOnTGERate
    ) external onlyProject {
        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that the project has not withdrawn any capital
        _verifyNoCapitalWithdrawn();

        /// Verify that tokens for distribution have not been allocated
        _verifyTokensNotAllocated();

        /// Set the vesting duration in seconds
        vestingDurationSeconds = _vestingDurationSeconds;

        /// Set the vesting cliff duraation in seconds
        vestingCliffDurationSeconds = _vestingCliffDurationSeconds;

        /// Set the token allocation on TGE
        tokenAllocationOnTGERate = _tokenAllocationOnTGERate;

        /// Emit successfully VestingTermsUpdated
        emit VestingTermsUpdated(_vestingDurationSeconds, _vestingCliffDurationSeconds, _tokenAllocationOnTGERate);
    }

    /**
     * @notice See {ILegionPreLiquidSale-emergencyWithdraw}.
     */
    function emergencyWithdraw(address receiver, address token, uint256 amount) external onlyLegion {
        /// Emit successfully EmergencyWithdraw
        emit EmergencyWithdraw(receiver, token, amount);

        /// Transfer the amount to Legion's address
        IERC20(token).safeTransfer(receiver, amount);
    }

    /**
     * @notice See {ILegionPreLiquidSale-withdrawCapital}.
     */
    function withdrawRaisedCapital(address[] calldata investors) external onlyProject returns (uint256 amount) {
        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Loop through the investors positions
        for (uint256 i = 0; i < investors.length; ++i) {
            /// Verify that the refund period is over for the specified position
            _verifyRefundPeriodIsOver(investors[i]);

            /// Verify that the investor has actually invested capital
            _verifyCanWithdrawInvestorPosition(investors[i]);

            /// Load the investor position
            InvestorPosition storage position = investorPositions[investors[i]];

            /// Get the outstanding capital to be withdrawn
            uint256 currentAmount = position.investedCapital - position.withdrawnCapital;

            /// Mark the amount of capital withdrawn
            position.withdrawnCapital += currentAmount;

            /// Increment the total amount to be withdrawn
            amount += currentAmount;
        }

        /// Account for the capital withdrawn
        totalCapitalWithdrawn += amount;

        /// Calculate Legion Fee
        uint256 legionFee = (legionFeeOnCapitalRaisedBps * amount) / 10000;

        /// Emit successfully CapitalWithdrawn
        emit CapitalWithdrawn(amount);

        /// Transfer the amount to the Project's address
        IERC20(bidToken).safeTransfer(msg.sender, (amount - legionFee));

        /// Transfer the Legion fee to the Legion fee receiver address
        if (legionFee != 0) IERC20(bidToken).safeTransfer(legionFeeReceiver, legionFee);
    }

    /**
     * @notice See {ILegionPreLiquidSale-claimTokenAllocation}.
     */
    function claimAskTokenAllocation(bytes32[] calldata proof) external {
        /// Verify that the sale has not been canceled
        _verifySaleNotCanceled();

        /// Verify that the investor can claim the token allocation
        _verifyCanClaimTokenAllocation(msg.sender);

        /// Verify that the investor position is valid
        _verifyValidPosition(msg.sender, proof);

        /// Load the investor position
        InvestorPosition storage position = investorPositions[msg.sender];

        /// Calculate the total token amount to be claimed
        uint256 totalAmount = askTokenTotalSupply * position.cachedTokenAllocationRate / 1e18;

        /// Calculate the amount to be distributed on claim
        uint256 amountToDistributeOnClaim = totalAmount * tokenAllocationOnTGERate / 1e18;

        /// Calculate the remaining amount to be vested
        uint256 amountToBeVested = totalAmount - amountToDistributeOnClaim;

        /// Deploy a linear vesting schedule contract
        address payable vestingAddress = _createVesting(
            msg.sender, uint64(vestingStartTime), uint64(vestingDurationSeconds), uint64(vestingCliffDurationSeconds)
        );

        /// Save the vesting address for the investor
        position.vestingAddress = vestingAddress;

        /// Mark that the token amount has been settled
        position.hasSettled = true;

        /// Emit successfully TokenAllocationClaimed
        emit TokenAllocationClaimed(amountToBeVested, amountToDistributeOnClaim, msg.sender, vestingAddress);

        /// Transfer the allocated amount of tokens for distribution
        IERC20(askToken).safeTransfer(vestingAddress, amountToBeVested);

        if (amountToDistributeOnClaim != 0) {
            /// Transfer the allocated amount of tokens for distribution on claim
            IERC20(askToken).safeTransfer(msg.sender, amountToDistributeOnClaim);
        }
    }

    /**
     * @notice See {ILegionPreLiquidSale-cancelSale}.
     */
    function cancelSale() external onlyProject {
        /// Verify that the sale has not been canceled
        _verifySaleNotCanceled();

        /// Verify that no tokens have been supplied to the sale by the Project
        _verifyAskTokensNotSupplied();

        /// Cache the amount of funds to be returned to the sale
        uint256 capitalToReturn = totalCapitalWithdrawn;

        /// Mark the sale as canceled
        isCanceled = true;

        /// Emit successfully CapitalWithdrawn
        emit SaleCanceled();

        /// In case there's capital to return, transfer the funds back to the contract
        if (capitalToReturn > 0) {
            /// Set the totalCapitalWithdrawn to zero
            totalCapitalWithdrawn = 0;
            /// Transfer the allocated amount of tokens for distribution
            IERC20(bidToken).safeTransferFrom(msg.sender, address(this), capitalToReturn);
        }
    }

    /**
     * @notice See {ILegionPreLiquidSale-claimBackCapitalIfSaleIsCanceled}.
     */
    function withdrawCapitalIfSaleIsCanceled() external {
        /// Verify that the sale has been actually canceled
        _verifySaleIsCanceled();

        /// Cache the amount to refund in memory
        uint256 amountToClaim = investorPositions[msg.sender].investedCapital;

        /// Revert in case there's nothing to claim
        if (amountToClaim == 0) revert InvalidClaimAmount();

        /// Set the total pledged capital for the investor to 0
        investorPositions[msg.sender].investedCapital = 0;

        /// Decrement total capital pledged from investors
        totalCapitalInvested -= amountToClaim;

        /// Emit successfully CapitalRefundedAfterCancel
        emit CapitalRefundedAfterCancel(amountToClaim, msg.sender);

        /// Transfer the refunded amount back to the investor
        IERC20(bidToken).safeTransfer(msg.sender, amountToClaim);
    }

    /**
     * @notice See {ILegionPreLiquidSale-withdrawExcessCapital}.
     */
    function withdrawExcessCapital(
        uint256 amount,
        uint256 saftInvestAmount,
        uint256 tokenAllocationRate,
        bytes32 saftHash,
        bytes32[] calldata proof
    ) external {
        /// Verify that the sale has not been canceled
        _verifySaleNotCanceled();

        /// Load the investor position
        InvestorPosition storage position = investorPositions[msg.sender];

        /// Decrement total capital invested from investors
        totalCapitalInvested -= amount;

        /// Decrement total investor capital for the investor
        position.investedCapital -= amount;

        /// Cache the maximum amount the investor is allowed to invest
        if (position.cachedSAFTInvestAmount != saftInvestAmount) {
            position.cachedSAFTInvestAmount = saftInvestAmount;
        }

        /// Cache the token allocation rate in 18 decimals precision
        if (position.cachedTokenAllocationRate != tokenAllocationRate) {
            position.cachedTokenAllocationRate = tokenAllocationRate;
        }

        /// Cache the hash of the SAFT signed by the investor
        if (position.cachedSAFTHash != saftHash) {
            position.cachedSAFTHash = saftHash;
        }

        /// Verify that the investor position is valid
        _verifyValidPosition(msg.sender, proof);

        /// Emit successfully ExcessCapitalWithdrawn
        emit ExcessCapitalWithdrawn(amount, msg.sender, tokenAllocationRate, saftHash, block.timestamp);

        /// Transfer the excess capital to the investor
        IERC20(bidToken).safeTransfer(msg.sender, amount);
    }

    /**
     * @notice See {ILegionPreLiquidSale-releaseTokens}.
     */
    function releaseTokens() external {
        /// Get the investor position details
        InvestorPosition memory position = investorPositions[msg.sender];

        /// Revert in case there's no vesting for the investor
        if (position.vestingAddress == address(0)) revert ZeroAddressProvided();

        /// Release tokens to the investor account
        ILegionLinearVesting(position.vestingAddress).release(askToken);
    }

    /**
     * @notice See {ILegionPreLiquidSale-toggleInvestmentAccepted}.
     */
    function toggleInvestmentAccepted() external onlyProject {
        /// Verify that tokens for distribution have not been allocated
        _verifyTokensNotAllocated();

        /// Update the `investmentAccepted` status
        investmentAccepted = !investmentAccepted;

        /// Emit successfully ToggleInvestmentAccepted
        emit ToggleInvestmentAccepted(investmentAccepted);
    }

    /**
     * @notice See {ILegionPreLiquidSale-syncLegionAddresses}.
     */
    function syncLegionAddresses() external onlyLegion {
        /// Cache Legion addresses from `LegionAddressRegistry`
        legionBouncer = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_BOUNCER_ID);
        legionFeeReceiver = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_FEE_RECEIVER_ID);
        vestingFactory = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_VESTING_FACTORY_ID);

        /// Emit successfully LegionAddressesSynced
        emit LegionAddressesSynced(legionBouncer, legionFeeReceiver, vestingFactory);
    }

    /**
     * @notice See {ILegionPreLiquidSale-saleConfig}.
     */
    function saleConfig() external view returns (PreLiquidSaleConfig memory preLiquidSaleConfig) {
        /// Get the pre-liquid sale config
        preLiquidSaleConfig = PreLiquidSaleConfig(
            refundPeriodSeconds,
            vestingDurationSeconds,
            vestingCliffDurationSeconds,
            tokenAllocationOnTGERate,
            legionFeeOnCapitalRaisedBps,
            legionFeeOnTokensSoldBps,
            saftMerkleRoot,
            bidToken,
            projectAdmin,
            addressRegistry
        );
    }

    /**
     * @notice See {ILegionPreLiquidSale-saleStatus}.
     */
    function saleStatus() external view returns (PreLiquidSaleStatus memory preLiquidSaleStatus) {
        /// Get the pre-liquid sale status
        preLiquidSaleStatus = PreLiquidSaleStatus(
            askToken,
            vestingStartTime,
            askTokenTotalSupply,
            totalCapitalInvested,
            totalTokensAllocated,
            totalCapitalWithdrawn,
            isCanceled,
            askTokensSupplied,
            investmentAccepted
        );
    }

    /**
     * @notice Create a vesting schedule contract.
     *
     * @param _beneficiary The beneficiary.
     * @param _startTimestamp The start timestamp.
     * @param _durationSeconds The duration in seconds.
     * @param _cliffDurationSeconds The cliff duration in seconds.
     *
     * @return vestingInstance The address of the deployed vesting instance.
     */
    function _createVesting(
        address _beneficiary,
        uint64 _startTimestamp,
        uint64 _durationSeconds,
        uint64 _cliffDurationSeconds
    ) internal returns (address payable vestingInstance) {
        /// Deploy a vesting schedule instance
        vestingInstance = ILegionVestingFactory(vestingFactory).createLinearVesting(
            _beneficiary, _startTimestamp, _durationSeconds, _cliffDurationSeconds
        );
    }

    /**
     * @notice Verify if the sale configuration is valid.
     *
     * @param _preLiquidSaleConfig The configuration for the pre-liquid sale.
     */
    function _verifyValidConfig(PreLiquidSaleConfig calldata _preLiquidSaleConfig) private pure {
        /// Check for zero addresses provided
        if (
            _preLiquidSaleConfig.bidToken == address(0) || _preLiquidSaleConfig.projectAdmin == address(0)
                || _preLiquidSaleConfig.addressRegistry == address(0)
        ) revert ZeroAddressProvided();

        /// Check for zero values provided
        if (_preLiquidSaleConfig.refundPeriodSeconds == 0) {
            revert ZeroValueProvided();
        }

        /// Check if prefund, allocation, sale, refund and lockup periods are within range
        if (_preLiquidSaleConfig.refundPeriodSeconds > TWO_WEEKS) revert InvalidPeriodConfig();
    }

    function _verifyCanWithdrawInvestorPosition(address _investor) private view {
        /// Load the investor position
        InvestorPosition memory position = investorPositions[_investor];

        /// Check if the investor has invested capital
        if (position.investedCapital == 0) revert CapitalNotInvested(_investor);

        /// Check if the capital has not been already withdrawn by the Project
        if (position.withdrawnCapital == position.investedCapital) revert CapitalAlreadyWithdrawn(_investor);
    }

    /**
     * @notice Verify that the refund period is not over.
     *
     * @param _investor The address of the investor
     */
    function _verifyRefundPeriodIsNotOver(address _investor) private view {
        /// Load the investor position
        InvestorPosition memory position = investorPositions[_investor];

        /// Check if the refund period is over
        if (block.timestamp > position.cachedInvestTimestamp + refundPeriodSeconds) revert RefundPeriodIsOver();
    }

    /**
     * @notice Verify that the refund period is over.
     *
     * @param _investor The address of the investor
     */
    function _verifyRefundPeriodIsOver(address _investor) private view {
        /// Load the investor position
        InvestorPosition memory position = investorPositions[_investor];

        /// Check if the refund period is not over
        if (block.timestamp <= position.cachedInvestTimestamp + refundPeriodSeconds) revert RefundPeriodIsNotOver();
    }

    /**
     * @notice Verify if the project can supply tokens for distribution.
     *
     * @param _amount The amount to supply.
     */
    function _verifyCanSupplyTokens(uint256 _amount) private view {
        /// Revert if Legion has not set the total amount of tokens allocated for distribution
        if (totalTokensAllocated == 0) revert TokensNotAllocated();

        /// Revert if tokens have already been supplied
        if (askTokensSupplied) revert TokensAlreadySupplied();

        /// Revert if the amount of tokens supplied is different than the amount set by Legion
        if (_amount != totalTokensAllocated) revert InvalidTokenAmountSupplied(_amount);
    }

    /**
     * @notice Verify if the tokens for distribution have not been allocated.
     */
    function _verifyTokensNotAllocated() private view {
        /// Revert if the tokens for distribution have already been allocated
        if (totalTokensAllocated > 0) revert TokensAlreadyAllocated();
    }

    /**
     * @notice Verify that the sale is not canceled.
     */
    function _verifySaleNotCanceled() internal view {
        if (isCanceled) revert SaleIsCanceled();
    }

    /**
     * @notice Verify that the sale is canceled.
     */
    function _verifySaleIsCanceled() internal view {
        if (!isCanceled) revert SaleIsNotCanceled();
    }

    /**
     * @notice Verify that the Project has not withdrawn any capital.
     */
    function _verifyNoCapitalWithdrawn() internal view {
        if (totalCapitalWithdrawn > 0) revert ProjectHasWithdrawnCapital();
    }

    /**
     * @notice Verify if an investor is eligible to claim token allocation.
     *
     * @param _investor The address of the investor.
     */
    function _verifyCanClaimTokenAllocation(address _investor) internal view {
        /// Load the investor position
        InvestorPosition memory position = investorPositions[_investor];

        /// Check if the askToken has been supplied to the sale
        if (!askTokensSupplied) revert AskTokensNotSupplied();

        /// Check if the investor has already settled their allocation
        if (position.hasSettled) revert AlreadySettled(_investor);

        /// Check if the investor has invested capital
        if (position.investedCapital == 0) revert CapitalNotInvested(msg.sender);
    }

    /**
     * @notice Verify that the Project has not accepted the investment round.
     */
    function _verifyInvestmentAccepted() internal view {
        /// Check if investment is accepted by the Project
        if (!investmentAccepted) revert InvestmentNotAccepted();
    }

    /**
     * @notice Verify that the project has not supplied ask tokens to the sale.
     */
    function _verifyAskTokensNotSupplied() internal view virtual {
        if (askTokensSupplied) revert TokensAlreadySupplied();
    }

    /**
     * @notice Verify if the investor position is valid
     *
     * @param _investor The address of the investor.
     * @param _proof The merkle proof that the investor is part of the whitelist
     */
    function _verifyValidPosition(address _investor, bytes32[] calldata _proof) internal view {
        /// Load the investor position
        InvestorPosition memory position = investorPositions[_investor];

        /// Generate the merkle leaf
        bytes32 leaf = keccak256(
            bytes.concat(
                keccak256(
                    abi.encode(
                        _investor,
                        position.cachedSAFTInvestAmount,
                        position.cachedTokenAllocationRate,
                        position.cachedSAFTHash
                    )
                )
            )
        );

        /// Verify that the amount invested is equal to the SAFT amount
        if (position.investedCapital != position.cachedSAFTInvestAmount) {
            revert InvalidPositionAmount(_investor);
        }

        /// Verify the merkle proof
        if (!MerkleProof.verify(_proof, saftMerkleRoot, leaf)) revert InvalidProof(_investor);
    }
}

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {LegionBaseSale} from "./LegionBaseSale.sol";
import {ECIES, Point} from "./lib/ECIES.sol";

import {ILegionAddressRegistry} from "./interfaces/ILegionAddressRegistry.sol";
import {ILegionBaseSale} from "./interfaces/ILegionBaseSale.sol";
import {ILegionSealedBidAuction} from "./interfaces/ILegionSealedBidAuction.sol";
import {ILegionLinearVesting} from "./interfaces/ILegionLinearVesting.sol";
import {ILegionVestingFactory} from "./interfaces/ILegionVestingFactory.sol";

/**
 * @title Legion Sealed Bid Auction.
 * @author Legion.
 * @notice A contract used to execute seale bid auctions of ERC20 tokens after TGE.
 */
contract LegionSealedBidAuction is LegionBaseSale, ILegionSealedBidAuction {
    using SafeERC20 for IERC20;

    /// @dev The public key used to encrypt the sealed bids.
    Point private publicKey;

    /// @dev The private key used to decrypt the bids. Not set until results are published.
    uint256 private privateKey;

    /// @dev Boolean representing if canceling of the sale is locked
    bool private cancelLocked;

    /**
     * @notice See {ILegionSealedBidAuction-initialize}.
     */
    function initialize(SealedBidAuctionConfig calldata sealedBidAuctionConfig) external initializer {
        /// Initialize sealed bid auction period and fee configuration
        salePeriodSeconds = sealedBidAuctionConfig.salePeriodSeconds;
        refundPeriodSeconds = sealedBidAuctionConfig.refundPeriodSeconds;
        lockupPeriodSeconds = sealedBidAuctionConfig.lockupPeriodSeconds;
        vestingDurationSeconds = sealedBidAuctionConfig.vestingDurationSeconds;
        vestingCliffDurationSeconds = sealedBidAuctionConfig.vestingCliffDurationSeconds;
        legionFeeOnCapitalRaisedBps = sealedBidAuctionConfig.legionFeeOnCapitalRaisedBps;
        legionFeeOnTokensSoldBps = sealedBidAuctionConfig.legionFeeOnTokensSoldBps;
        minimumPledgeAmount = sealedBidAuctionConfig.minimumPledgeAmount;
        publicKey = sealedBidAuctionConfig.publicKey;
        bidToken = sealedBidAuctionConfig.bidToken;
        askToken = sealedBidAuctionConfig.askToken;
        projectAdmin = sealedBidAuctionConfig.projectAdmin;
        addressRegistry = sealedBidAuctionConfig.addressRegistry;

        /// Calculate and set startTime, endTime and refundEndTime
        startTime = block.timestamp;
        endTime = startTime + sealedBidAuctionConfig.salePeriodSeconds;
        refundEndTime = endTime + sealedBidAuctionConfig.refundPeriodSeconds;

        /// Check if lockupPeriodSeconds is less than refundPeriodSeconds
        /// lockupEndTime should be at least refundEndTime
        if (sealedBidAuctionConfig.lockupPeriodSeconds <= sealedBidAuctionConfig.refundPeriodSeconds) {
            /// If yes, set lockupEndTime to be refundEndTime
            lockupEndTime = refundEndTime;
        } else {
            /// If no, calculate the lockupEndTime
            lockupEndTime = endTime + sealedBidAuctionConfig.lockupPeriodSeconds;
        }

        // Set the vestingStartTime to begin when lockupEndTime is reached
        vestingStartTime = lockupEndTime;

        /// Verify if the sale configuration is valid
        _verifyValidConfig(sealedBidAuctionConfig);

        /// Cache Legion addresses from `LegionAddressRegistry`
        legionBouncer = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_BOUNCER_ID);
        legionSigner = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_SIGNER_ID);
        legionFeeReceiver = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_FEE_RECEIVER_ID);
        vestingFactory = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_VESTING_FACTORY_ID);
    }

    /**
     * @notice See {ILegionSealedBidAuction-pledgeCapital}.
     */
    function pledgeCapital(uint256 amount, bytes calldata sealedBid, bytes memory signature) external {
        /// Verify that the investor is allowed to pledge capital
        _verifyLegionSignature(signature);

        /// Decode the sealed bid data
        (uint256 encryptedAmountOut, uint256 salt, Point memory sealedBidPublicKey) =
            abi.decode(sealedBid, (uint256, uint256, Point));

        /// Verify that the provided salt is valid
        _verifyValidSalt(salt);

        /// Verify that the provided public key is valid
        _verifyValidPublicKey(sealedBidPublicKey);

        /// Verify that the sale has not ended
        _verifySaleHasNotEnded();

        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that the amount pledged is more than the minimum required
        _verifyMinimumPledgeAmount(amount);

        /// Increment total capital pledged from investors
        totalCapitalPledged += amount;

        /// Increment total pledged capital for the investor
        investorPositions[msg.sender].pledgedCapital += amount;

        /// Emit successfully CapitalPledged
        emit CapitalPledged(amount, encryptedAmountOut, salt, msg.sender, block.timestamp);

        /// Transfer the pledged capital to the contract
        IERC20(bidToken).safeTransferFrom(msg.sender, address(this), amount);
    }

    /**
     * @notice See {ILegionSealedBidAuction-initializePublishSaleResults}.
     */
    function initializePublishSaleResults() external onlyLegion {
        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that canceling is not locked
        _verifyCancelNotLocked();

        /// Verify that the refund period is over
        _verifyRefundPeriodIsOver();

        /// Verify that sale results are not already published
        _verifyCanPublishSaleResults();

        /// Flag the the sale is locked from canceling
        cancelLocked = true;

        /// Emit successfully PublishSaleResultsInitialized
        emit PublishSaleResultsInitialized();
    }

    /**
     * @notice See {ILegionSealedBidAuction-publishSaleResults}.
     */
    function publishSaleResults(
        bytes32 merkleRoot,
        uint256 tokensAllocated,
        uint256 capitalRaised,
        uint256 sealedBidPrivateKey
    ) external onlyLegion {
        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that canceling is locked
        _verifyCancelLocked();

        /// Verify that the refund period is over
        _verifyRefundPeriodIsOver();

        /// Verify if the provided private key is valid
        _verifyValidPrivateKey(sealedBidPrivateKey);

        /// Verify that sale results are not already published
        _verifyCanPublishSaleResults();

        /// Set the merkle root for claiming tokens
        claimTokensMerkleRoot = merkleRoot;

        /// Set the total tokens to be allocated by the Project team
        totalTokensAllocated = tokensAllocated;

        /// Set the total capital raised to be withdrawn by the project
        totalCapitalRaised = capitalRaised;

        /// Set the private key used to decrypt sealed bids
        privateKey = sealedBidPrivateKey;

        /// Emit successfully SaleResultsPublished
        emit SaleResultsPublished(merkleRoot, tokensAllocated, capitalRaised, sealedBidPrivateKey);
    }

    /**
     * @notice See {ILegionBaseSale-cancelSale}.
     */
    function cancelSale() public override(ILegionBaseSale, LegionBaseSale) onlyProject {
        /// Call parent method
        super.cancelSale();

        /// Verify that canceling the sale is not locked.
        _verifyCancelNotLocked();
    }

    /**
     * @notice See {ILegionSealedBidAuction-saleConfiguration}.
     */
    function saleConfiguration() external view returns (SealedBidAuctionConfig memory saleConfig) {
        /// Get the sealed bid auction config
        saleConfig = SealedBidAuctionConfig(
            salePeriodSeconds,
            refundPeriodSeconds,
            lockupPeriodSeconds,
            vestingDurationSeconds,
            vestingCliffDurationSeconds,
            legionFeeOnCapitalRaisedBps,
            legionFeeOnTokensSoldBps,
            minimumPledgeAmount,
            publicKey,
            bidToken,
            askToken,
            projectAdmin,
            addressRegistry
        );
    }

    /**
     * @notice See {ILegionSealedBidAuction-saleStatus}.
     */
    function saleStatus() external view returns (SealedBidAuctionStatus memory sealedBidAuctionStatus) {
        /// Get the sealed bid auction status
        sealedBidAuctionStatus = SealedBidAuctionStatus(
            startTime,
            endTime,
            refundEndTime,
            lockupEndTime,
            vestingStartTime,
            totalCapitalPledged,
            totalTokensAllocated,
            totalCapitalRaised,
            privateKey,
            claimTokensMerkleRoot,
            excessCapitalMerkleRoot,
            isCanceled,
            tokensSupplied,
            capitalWithdrawn
        );
    }

    /**
     * @notice See {ILegionSealedBidAuction-decryptBid}.
     */
    function decryptSealedBid(uint256 encryptedAmountOut, uint256 salt) public view returns (uint256) {
        /// Verify that the private key has been published by Legion
        _verifyPrivateKeyIsPublished();

        /// Decrypt the sealed bid
        return ECIES.decrypt(encryptedAmountOut, publicKey, privateKey, salt);
    }

    /**
     * @notice Verify if the sale configuration is valid.
     *
     * @param _sealedBidAuctionConfig The period and fee configuration for the sealed bid auction.
     */
    function _verifyValidConfig(SealedBidAuctionConfig calldata _sealedBidAuctionConfig) private pure {
        /// Check for zero addresses provided
        if (
            _sealedBidAuctionConfig.bidToken == address(0) || _sealedBidAuctionConfig.projectAdmin == address(0)
                || _sealedBidAuctionConfig.addressRegistry == address(0)
        ) revert ZeroAddressProvided();

        /// Check for zero values provided
        if (
            _sealedBidAuctionConfig.salePeriodSeconds == 0 || _sealedBidAuctionConfig.refundPeriodSeconds == 0
                || _sealedBidAuctionConfig.lockupPeriodSeconds == 0
        ) revert ZeroValueProvided();

        /// Check if the public key used for encryption is valid
        if (!ECIES.isValid(_sealedBidAuctionConfig.publicKey)) revert InvalidBidPublicKey();

        /// Check if sale, refund and lockup periods are longer than allowed
        if (
            _sealedBidAuctionConfig.salePeriodSeconds > THREE_MONTHS
                || _sealedBidAuctionConfig.refundPeriodSeconds > TWO_WEEKS
                || _sealedBidAuctionConfig.lockupPeriodSeconds > SIX_MONTHS
        ) revert InvalidPeriodConfig();

        /// Check if sale, refund and lockup periods are shorter than allowed
        if (
            _sealedBidAuctionConfig.salePeriodSeconds < ONE_HOUR
                || _sealedBidAuctionConfig.refundPeriodSeconds < ONE_HOUR
                || _sealedBidAuctionConfig.lockupPeriodSeconds < ONE_HOUR
        ) revert InvalidPeriodConfig();
    }

    /**
     * @notice Verify if the public key used to encrpyt the bid is valid.
     *
     * @param _publicKey The public key used to encrypt bids.
     */
    function _verifyValidPublicKey(Point memory _publicKey) private view {
        /// Verify that the _publicKey is a valid point for the encryption library
        if (!ECIES.isValid(_publicKey)) revert InvalidBidPublicKey();

        /// Verify that the _publicKey is the one used for the entire auction
        if (
            keccak256(abi.encodePacked(_publicKey.x, _publicKey.y))
                != keccak256(abi.encodePacked(publicKey.x, publicKey.y))
        ) revert InvalidBidPublicKey();
    }

    /**
     * @notice Verify if the provided private key is valid.
     *
     * @param _privateKey The private key used to decrypt bids.
     */
    function _verifyValidPrivateKey(uint256 _privateKey) private view {
        /// Verify that the private key has not already been published
        if (privateKey != 0) revert PrivateKeyAlreadyPublished();

        /// Verify that the private key is valid for the public key
        Point memory calcPubKey = ECIES.calcPubKey(Point(1, 2), _privateKey);
        if (calcPubKey.x != publicKey.x || calcPubKey.y != publicKey.y) revert InvalidBidPrivateKey();
    }

    /**
     * @notice Verify that the private key has been published by Legion.
     */
    function _verifyPrivateKeyIsPublished() private view {
        if (privateKey == 0) revert PrivateKeyNotPublished();
    }

    /**
     * @notice Verify that the salt used to encrypt the bid is valid.
     *
     * @param _salt The salt used for bid encryption
     */
    function _verifyValidSalt(uint256 _salt) private view {
        if (uint256(uint160(msg.sender)) != _salt) revert InvalidSalt();
    }

    /**
     * @notice Verify that canceling the is not locked.
     */
    function _verifyCancelNotLocked() private view {
        if (cancelLocked) revert CancelLocked();
    }

    /**
     * @notice Verify that canceling is locked.
     */
    function _verifyCancelLocked() private view {
        if (!cancelLocked) revert CancelNotLocked();
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
import {ILegionBaseSale} from "./ILegionBaseSale.sol";

interface ILegionFixedPriceSale is ILegionBaseSale {
    /**
     * @notice This event is emitted when capital is successfully pledged.
     *
     * @param amount The amount of capital pledged.
     * @param investor The address of the investor.
     * @param isPrefund Whether capital is pledged before sale start.
     * @param pledgeTimestamp The unix timestamp (seconds) of the block when capital has been pledged.
     */
    event CapitalPledged(uint256 amount, address investor, bool isPrefund, uint256 pledgeTimestamp);

    /**
     * @notice This event is emitted when sale results are successfully published by the Legion admin.
     *
     * @param merkleRoot The claim merkle root published.
     * @param tokensAllocated The amount of tokens allocated from the sale.
     */
    event SaleResultsPublished(bytes32 merkleRoot, uint256 tokensAllocated);

    /**
     * @notice Throws when capital is pledged during the prefund allocation period.
     */
    error PrefundAllocationPeriodNotEnded();

    /// @notice A struct describing the fixed price sale configuration.
    struct FixedPriceSaleConfig {
        /// @dev The prefund period duration in seconds.
        uint256 prefundPeriodSeconds;
        /// @dev The prefund allocation period duration in seconds.
        uint256 prefundAllocationPeriodSeconds;
        /// @dev The sale period duration in seconds.
        uint256 salePeriodSeconds;
        /// @dev The refund period duration in seconds.
        uint256 refundPeriodSeconds;
        /// @dev The lockup period duration in seconds.
        uint256 lockupPeriodSeconds;
        /// @dev The vesting schedule duration for the token sold in seconds.
        uint256 vestingDurationSeconds;
        /// @dev The vesting cliff duration for the token sold in seconds.
        uint256 vestingCliffDurationSeconds;
        /// @dev Legion's fee on capital raised in BPS (Basis Points).
        uint256 legionFeeOnCapitalRaisedBps;
        /// @dev Legion's fee on tokens sold in BPS (Basis Points).
        uint256 legionFeeOnTokensSoldBps;
        /// @dev The minimum pledge amount denominated in the `bidToken`
        uint256 minimumPledgeAmount;
        /// @dev The price of the token being sold denominated in the token used to raise capital.
        uint256 tokenPrice;
        /// @dev The address of the token used for raising capital.
        address bidToken;
        /// @dev The address of the token being sold to investors.
        address askToken;
        /// @dev The admin address of the project raising capital.
        address projectAdmin;
        /// @dev The address of Legion's Address Registry contract.
        address addressRegistry;
    }

    /// @notice A struct describing the fixed price sale status.
    struct FixedPriceSaleStatus {
        /// @dev The unix timestamp (seconds) of the block when the prefund starts.
        uint256 prefundStartTime;
        /// @dev The unix timestamp (seconds) of the block when the prefund ends.
        uint256 prefundEndTime;
        /// @dev The unix timestamp (seconds) of the block when the sale starts.
        uint256 startTime;
        /// @dev The unix timestamp (seconds) of the block when the sale ends.
        uint256 endTime;
        /// @dev The unix timestamp (seconds) of the block when the refund period ends.
        uint256 refundEndTime;
        /// @dev The unix timestamp (seconds) of the block when the lockup period ends.
        uint256 lockupEndTime;
        /// @dev The unix timestamp (seconds) of the block when the vesting period starts.
        uint256 vestingStartTime;
        /// @dev The total capital pledged by investors.
        uint256 totalCapitalPledged;
        /// @dev The total amount of tokens allocated to investors.
        uint256 totalTokensAllocated;
        /// @dev The total capital raised from the sale.
        uint256 totalCapitalRaised;
        /// @dev The merkle root for verification of token distribution amounts.
        bytes32 claimTokensMerkleRoot;
        /// @dev The merkle root for verification of excess capital distribution amounts.
        bytes32 excessCapitalMerkleRoot;
        /// @dev Whether the sale has been canceled or not.
        bool isCanceled;
        /// @dev Whether tokens have been supplied by the project or not.
        bool tokensSupplied;
        /// @dev Whether raised capital has been withdrawn from the sale by the project or not.
        bool capitalWithdrawn;
    }

    /**
     * @notice Initialized the contract with correct parameters.
     *
     * @param fixedPriceSaleConfig The configuration for the fixed price sale.
     */
    function initialize(FixedPriceSaleConfig calldata fixedPriceSaleConfig) external;

    /**
     * @notice Pledge capital to the fixed price sale.
     *
     * @param amount The amount of capital pledged.
     * @param signature The Legion signature for verification.
     */
    function pledgeCapital(uint256 amount, bytes memory signature) external;

    /**
     * @notice Publish merkle root for distribution of tokens, once the sale has concluded.
     *
     * @dev Can be called only by the Legion admin address.
     *
     * @param merkleRoot The merkle root to verify against.
     * @param tokensAllocated The total amount of tokens allocated for distribution among investors.
     * @param askTokenDecimals The decimals number of the ask token.
     */
    function publishSaleResults(bytes32 merkleRoot, uint256 tokensAllocated, uint8 askTokenDecimals) external;

    /**
     * @notice Returns the configuration for the fixed price sale.
     */
    function saleConfiguration() external view returns (FixedPriceSaleConfig memory saleConfig);

    /**
     * @notice Returns the status for the fixed price sale.
     */
    function saleStatus() external view returns (FixedPriceSaleStatus memory fixedPriceSaleStatus);
}

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
interface ILegionPreLiquidSale {
    /**
     * @notice This event is emitted when capital is successfully invested.
     *
     * @param amount The amount of capital invested.
     * @param investor The address of the investor.
     * @param tokenAllocationRate The token allocation the investor will receive as percentage of totalSupply, represented in 18 decimals precision.
     * @param saftHash The hash of the SAFT signed by the investor
     * @param investTimestamp The unix timestamp (seconds) of the block when capital has been invested.
     */
    event CapitalInvested(
        uint256 amount, address investor, uint256 tokenAllocationRate, bytes32 saftHash, uint256 investTimestamp
    );

    /**
     * @notice This event is emitted when excess capital is successfully withdrawn.
     *
     * @param amount The amount of capital withdrawn.
     * @param investor The address of the investor.
     * @param tokenAllocationRate The token allocation the investor will receive as percentage of totalSupply, represented in 18 decimals precision.
     * @param saftHash The hash of the SAFT signed by the investor
     * @param investTimestamp The unix timestamp (seconds) of the block when capital has been invested.
     */
    event ExcessCapitalWithdrawn(
        uint256 amount, address investor, uint256 tokenAllocationRate, bytes32 saftHash, uint256 investTimestamp
    );

    /**
     * @notice This event is emitted when capital is successfully refunded to the investor.
     *
     * @param amount The amount of capital refunded to the investor.
     * @param investor The address of the investor who requested the refund.
     */
    event CapitalRefunded(uint256 amount, address investor);

    /**
     * @notice This event is emitted when capital is successfully refunded to the investor after a sale has been canceled.
     *
     * @param amount The amount of capital refunded to the investor.
     * @param investor The address of the investor who requested the refund.
     */
    event CapitalRefundedAfterCancel(uint256 amount, address investor);

    /**
     * @notice This event is emitted when capital is successfully withdrawn by the Project.
     *
     * @param amount The amount of capital withdrawn by the project.
     */
    event CapitalWithdrawn(uint256 amount);

    /**
     * @notice This event is emitted when excess capital results are successfully published by the Legion admin.
     *
     * @param receiver The address of the receiver.
     * @param token The address of the token to be withdrawn.
     * @param amount The amount to be withdrawn.
     */
    event EmergencyWithdraw(address receiver, address token, uint256 amount);

    /**
     * @notice This event is emitted when excess capital results are successfully published by the Legion admin.
     *
     * @param legionBouncer The updated Legion bouncer address.
     * @param legionFeeReceiver The updated fee receiver address of Legion.
     * @param vestingFactory The updated vesting factory address.
     */
    event LegionAddressesSynced(address legionBouncer, address legionFeeReceiver, address vestingFactory);

    /**
     * @notice This event is emitted when the SAFT merkle root is updated by the Legion admin.
     *
     * @param merkleRoot The new SAFT merkle root.
     */
    event SAFTMerkleRootUpdated(bytes32 merkleRoot);

    /**
     * @notice This event is emitted when a sale is successfully canceled.
     */
    event SaleCanceled();

    /**
     * @notice This event is emitted when the token details have been set by the Legion admin.
     *
     * @param tokenAddress The address of the token distributed to investors
     * @param totalSupply The total supply of the token distributed to investors
     * @param vestingStartTime The unix timestamp (seconds) of the block when the vesting starts.
     * @param allocatedTokenAmount The allocated token amount for distribution to investors.
     */
    event TgeDetailsPublished(
        address tokenAddress, uint256 totalSupply, uint256 vestingStartTime, uint256 allocatedTokenAmount
    );

    /**
     * @notice This event is emitted when tokens are successfully claimed by the investor.
     *
     * @param amountToBeVested The amount of tokens distributed to the vesting contract.
     * @param amountOnClaim The amount of tokens to be deiistributed directly to the investor on claim
     * @param investor The address of the investor owning the vesting contract.
     * @param vesting The address of the vesting instance deployed.
     */
    event TokenAllocationClaimed(uint256 amountToBeVested, uint256 amountOnClaim, address investor, address vesting);

    /**
     * @notice This event is emitted when tokens are successfully supplied for distribution by the project admin.
     *
     * @param amount The amount of tokens supplied for distribution.
     * @param legionFee The fee amount collected by Legion.
     */
    event TokensSuppliedForDistribution(uint256 amount, uint256 legionFee);

    /**
     * @notice This event is emitted when tokens are successfully supplied for distribution by the project admin.
     *
     * @param _vestingDurationSeconds The vesting schedule duration for the token sold in seconds.
     * @param _vestingCliffDurationSeconds The vesting cliff duration for the token sold in seconds.
     * @param _tokenAllocationOnTGERate The token allocation amount released to investors after TGE in 18 decimals precision.
     */
    event VestingTermsUpdated(
        uint256 _vestingDurationSeconds, uint256 _vestingCliffDurationSeconds, uint256 _tokenAllocationOnTGERate
    );

    /**
     * @notice This event is emitted when excess capital is successfully refunded by the project admin.
     *
     * @param amount The amount of excess capital refunded to the sale.
     */
    event ExcessCapitalRefunded(uint256 amount);

    /**
     * @notice This event is emitted when `investmentAccepted` status is changed.
     *
     * @param investmentAccepted Wheter investment is accepted by the Project.
     */
    event ToggleInvestmentAccepted(bool investmentAccepted);

    /**
     * @notice Throws when tokens already settled by investor.
     *
     * @param investor The address of the investor trying to invest.
     */
    error AlreadySettled(address investor);

    /**
     * @notice Throws when the ask tokens have not been supplied by the project.
     */
    error AskTokensNotSupplied();

    /**
     * @notice Throws when the Project tries to withdraw more than the allowed capital.
     */
    error CannotWithdrawCapital();

    /**
     * @notice Throws when an invalid amount has been requested for refund.
     */
    error InvalidRefundAmount();

    /**
     * @notice Throws when an invalid time config has been provided.
     */
    error InvalidPeriodConfig();

    /**
     * @notice Throws when an invalid amount of tokens has been supplied by the project.
     *
     * @param amount The amount of tokens supplied.
     */
    error InvalidTokenAmountSupplied(uint256 amount);

    /**
     * @notice Throws when an invalid amount has been requested for fee.
     */
    error InvalidFeeAmount();

    /**
     * @notice Throws when an invalid total supply has been provided.
     */
    error InvalidTotalSupply();

    /**
     * @notice Throws when an invalid amount of tokens has been claimed.
     */
    error InvalidClaimAmount();

    /**
     * @notice Throws when the invested capital amount is not equal to the SAFT amount.
     *
     * @param investor The address of the investor.
     */
    error InvalidPositionAmount(address investor);

    /**
     * @notice Throws when the merkle proof for the investor is inavlid.
     *
     * @param investor The address of the investor.
     */
    error InvalidProof(address investor);

    /**
     * @notice Throws when the Project is not accepting investments.
     */
    error InvestmentNotAccepted();

    /**
     * @notice Throws when not called by Legion.
     */
    error NotCalledByLegion();

    /**
     * @notice Throws when not called by the Project.
     */
    error NotCalledByProject();

    /**
     * @notice Throws when the Project has withdrawn capital.
     */
    error ProjectHasWithdrawnCapital();

    /**
     * @notice Throws when no capital has been invested.
     *
     * @param investor The address of the investor
     */
    error CapitalNotInvested(address investor);

    /**
     * @notice Throws when capital has already been withdrawn for an investor.
     *
     * @param investor The address of the investor
     */
    error CapitalAlreadyWithdrawn(address investor);

    /**
     * @notice Throws when the refund period is over.
     */
    error RefundPeriodIsOver();

    /**
     * @notice Throws when the refund period is not over.
     */
    error RefundPeriodIsNotOver();

    /**
     * @notice Throws when the sale is canceled.
     */
    error SaleIsCanceled();

    /**
     * @notice Throws when the sale is not canceled.
     */
    error SaleIsNotCanceled();

    /**
     * @notice Throws when tokens have not been allocated.
     */
    error TokensNotAllocated();

    /**
     * @notice Throws when tokens have been allocated.
     */
    error TokensAlreadyAllocated();

    /**
     * @notice Throws when tokens have already been supplied.
     */
    error TokensAlreadySupplied();

    /**
     * @notice Throws when investor is unable to claim token allocation.
     */
    error UnableToClaimTokenAllocation();

    /**
     * @notice Throws when zero address has been provided.
     */
    error ZeroAddressProvided();

    /**
     * @notice Throws when zero value has been provided.
     */
    error ZeroValueProvided();

    /// @notice A struct describing the pre-liquid sale period and fee configuration.
    struct PreLiquidSaleConfig {
        /// @dev The refund period duration in seconds.
        uint256 refundPeriodSeconds;
        /// @dev The vesting schedule duration for the token sold in seconds.
        uint256 vestingDurationSeconds;
        /// @dev The vesting cliff duration for the token sold in seconds.
        uint256 vestingCliffDurationSeconds;
        /// @dev The token allocation amount released to investors after TGE in 18 decimals precision.
        uint256 tokenAllocationOnTGERate;
        /// @dev Legion's fee on capital raised in BPS (Basis Points).
        uint256 legionFeeOnCapitalRaisedBps;
        /// @dev Legion's fee on tokens sold in BPS (Basis Points).
        uint256 legionFeeOnTokensSoldBps;
        /// @dev The merkle root for verification of SAFT signers and percentage of token allocations.
        bytes32 saftMerkleRoot;
        /// @dev The address of the token used for raising capital.
        address bidToken;
        /// @dev The admin address of the project raising capital.
        address projectAdmin;
        /// @dev The address of Legion's Address Registry contract.
        address addressRegistry;
    }

    /// @notice A struct describing the pre-liquid sale status.
    struct PreLiquidSaleStatus {
        /// @dev The address of the token being sold to investors.
        address askToken;
        /// @dev The unix timestamp (seconds) of the block when the vesting starts.
        uint256 vestingStartTime;
        /// @dev The total supply of the ask token
        uint256 askTokenTotalSupply;
        /// @dev The total capital invested by investors.
        uint256 totalCapitalInvested;
        /// @dev The total amount of tokens allocated to investors.
        uint256 totalTokensAllocated;
        /// @dev The total capital withdrawn by the Project, from the sale.
        uint256 totalCapitalWithdrawn;
        /// @dev Whether the sale has been canceled or not.
        bool isCanceled;
        /// @dev Whether the ask tokens have been supplied to the sale.
        bool askTokensSupplied;
        /// @dev Whether investment is being accepted by the Project.
        bool investmentAccepted;
    }

    /// @notice A struct describing the investor position during the sale.
    struct InvestorPosition {
        /// @dev The total amount of capital invested by the investor.
        uint256 investedCapital;
        /// @dev The amount of capital withdrawn from the investor position by the Project.
        uint256 withdrawnCapital;
        /// @dev The unix timestamp (seconds) of the block when the latest invest ocurred.
        uint256 cachedInvestTimestamp;
        /// @dev The amount of capital the investor is allowed to invest, according to the SAFT.
        uint256 cachedSAFTInvestAmount;
        /// @dev The token allocation rate the investor will receive as percentage of totalSupply, represented in 18 decimals precision.
        uint256 cachedTokenAllocationRate;
        /// @dev The hash of the SAFT signed by the investor
        bytes32 cachedSAFTHash;
        /// @dev Flag if the investor has claimed the tokens allocated to them.
        bool hasSettled;
        /// @dev The address of the investor's vesting contract.
        address vestingAddress;
    }

    /**
     * @notice Initialized the contract with correct parameters.
     *
     * @param preLiquidSaleConfig The period and fee configuration for the pre-liquid sale.
     */
    function initialize(PreLiquidSaleConfig calldata preLiquidSaleConfig) external;

    /**
     * @notice Invest capital to the pre-liquid sale.
     *
     * @param amount The amount of capital invested.
     * @param saftInvestAmount The amount of capital the investor is allowed to invest, according to the SAFT.
     * @param tokenAllocationRate The token allocation the investor will receive as percentage of totalSupply, represented in 18 decimals precision.
     * @param saftHash The hash of the SAFT signed by the investor
     * @param proof The merkle proof that the investor has signed a SAFT
     */
    function invest(
        uint256 amount,
        uint256 saftInvestAmount,
        uint256 tokenAllocationRate,
        bytes32 saftHash,
        bytes32[] calldata proof
    ) external;

    /**
     * @notice Get a refund from the sale during the applicable time window.
     */
    function refund() external;

    /**
     * @notice Updates the token details after Token Generation Event (TGE).
     *
     * @dev Only callable by Legion.
     *
     * @param tokenAddress The address of the token distributed to investors
     * @param totalSupply The total supply of the token distributed to investors
     * @param vestingStartTime The unix timestamp (seconds) of the block when the vesting starts.
     * @param allocatedTokenAmount The allocated token amount for distribution to investors.
     */
    function publishTgeDetails(
        address tokenAddress,
        uint256 totalSupply,
        uint256 vestingStartTime,
        uint256 allocatedTokenAmount
    ) external;

    /**
     * @notice Supply tokens for distribution after the Token Generation Event (TGE).
     *
     * @dev Only callable by the Project.
     *
     * @param amount The amount of tokens to be supplied for distribution.
     * @param legionFee The Legion fee token amount.
     */
    function supplyAskTokens(uint256 amount, uint256 legionFee) external;

    /**
     * @notice Updates the SAFT merkle root.
     *
     * @dev Only callable by Legion.
     *
     * @param merkleRoot The merkle root used for investing capital.
     */
    function updateSAFTMerkleRoot(bytes32 merkleRoot) external;

    /**
     * @notice Updates the vesting terms.
     *
     * @dev Only callable by Legion, before the token have been supplied by the Project.
     *
     * @param vestingDurationSeconds The vesting schedule duration for the token sold in seconds.
     * @param vestingCliffDurationSeconds The vesting cliff duration for the token sold in seconds.
     * @param tokenAllocationOnTGERate The token allocation amount released to investors after TGE in 18 decimals precision.
     */
    function updateVestingTerms(
        uint256 vestingDurationSeconds,
        uint256 vestingCliffDurationSeconds,
        uint256 tokenAllocationOnTGERate
    ) external;

    /**
     * @notice Withdraw tokens from the contract in case of emergency.
     *
     * @dev Can be called only by the Legion admin address.
     *
     * @param receiver The address of the receiver.
     * @param token The address of the token to be withdrawn.
     * @param amount The amount to be withdrawn.
     */
    function emergencyWithdraw(address receiver, address token, uint256 amount) external;

    /**
     * @notice Withdraw capital from the contract.
     *
     * @dev Can be called only by the Project admin address.
     *
     * @param investors Array of the addresses of the investors' capital which will be withdrawn
     */
    function withdrawRaisedCapital(address[] calldata investors) external returns (uint256 amount);

    /**
     * @notice Claim token allocation by investors
     *
     * @param proof The merkle proof that the investor has signed a SAFT
     */
    function claimAskTokenAllocation(bytes32[] calldata proof) external;

    /**
     * @notice Cancel the sale.
     *
     * @dev Can be called only by the Project admin address.
     */
    function cancelSale() external;

    /**
     * @notice Claim back capital from investors if the sale has been canceled.
     */
    function withdrawCapitalIfSaleIsCanceled() external;

    /**
     * @notice Withdraw back excess capital from investors.
     *
     * @param amount The amount of excess capital to be withdrawn.
     * @param saftInvestAmount The amount of capital the investor is allowed to invest, according to the SAFT.
     * @param tokenAllocationRate The token allocation the investor will receive as percentage of totalSupply, represented in 18 decimals precision.
     * @param saftHash The hash of the SAFT signed by the investor
     * @param proof The merkle proof that the investor has signed a SAFT
     */
    function withdrawExcessCapital(
        uint256 amount,
        uint256 saftInvestAmount,
        uint256 tokenAllocationRate,
        bytes32 saftHash,
        bytes32[] calldata proof
    ) external;

    /**
     * @notice Releases tokens to the investor address.
     */
    function releaseTokens() external;

    /**
     * @notice Toggles the `investmentAccepted` status.
     */
    function toggleInvestmentAccepted() external;

    /**
     * @notice Syncs active Legion addresses from `LegionAddressRegistry.sol`
     */
    function syncLegionAddresses() external;

    /**
     * @notice Returns the configuration for the pre-liquid token sale.
     */
    function saleConfig() external view returns (PreLiquidSaleConfig memory preLiquidSaleConfig);

    /**
     * @notice Returns the status of the pre-liquid token sale.
     */
    function saleStatus() external view returns (PreLiquidSaleStatus memory preLiquidSaleStatus);
}

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
import {ECIES, Point} from "../lib/ECIES.sol";
import {ILegionBaseSale} from "./ILegionBaseSale.sol";

interface ILegionSealedBidAuction is ILegionBaseSale {
    /**
     * @notice This event is emitted when capital is successfully pledged.
     *
     * @param amount The amount of capital pledged.
     * @param encryptedAmountOut The encrpyped amount out.
     * @param salt The unique salt used in the encryption process.
     * @param investor The address of the investor.
     * @param pledgeTimestamp The unix timestamp (seconds) of the block when capital has been pledged.
     */
    event CapitalPledged(
        uint256 amount, uint256 encryptedAmountOut, uint256 salt, address investor, uint256 pledgeTimestamp
    );

    /**
     * @notice This event is emitted when publishing the sale results has been initialized.
     */
    event PublishSaleResultsInitialized();

    /**
     * @notice This event is emitted when sale results are successfully published by the Legion admin.
     *
     * @param merkleRoot The claim merkle root published.
     * @param tokensAllocated The amount of tokens allocated from the sale.
     * @param capitalRaised The capital raised from the sale.
     * @param sealedBidPrivateKey The private key used to decrypt sealed bids.
     */
    event SaleResultsPublished(
        bytes32 merkleRoot, uint256 tokensAllocated, uint256 capitalRaised, uint256 sealedBidPrivateKey
    );

    /**
     * @notice Throws when canceling is locked.
     */
    error CancelLocked();

    /**
     * @notice Throws when canceling is not locked.
     */
    error CancelNotLocked();

    /**
     * @notice Throws when an invalid bid public key is used to encrypt a bid.
     */
    error InvalidBidPublicKey();

    /**
     * @notice Throws when an invalid bid private key is provided to decrypt a bid.
     */
    error InvalidBidPrivateKey();

    /**
     * @notice Throws when the private key has already been published by Legion.
     */
    error PrivateKeyAlreadyPublished();

    /**
     * @notice Throws when the private key has not been published by Legion.
     */
    error PrivateKeyNotPublished();

    /**
     * @notice Throws when the salt used to encrypt the bid is invalid.
     */
    error InvalidSalt();

    /// @notice A struct describing the sealed bid auction configuration.
    struct SealedBidAuctionConfig {
        /// @dev The sale period duration in seconds.
        uint256 salePeriodSeconds;
        /// @dev The refund period duration in seconds.
        uint256 refundPeriodSeconds;
        /// @dev The lockup period duration in seconds.
        uint256 lockupPeriodSeconds;
        /// @dev The vesting schedule duration for the token sold in seconds.
        uint256 vestingDurationSeconds;
        /// @dev The vesting cliff duration for the token sold in seconds.
        uint256 vestingCliffDurationSeconds;
        /// @dev Legion's fee on capital raised in BPS (Basis Points).
        uint256 legionFeeOnCapitalRaisedBps;
        /// @dev Legion's fee on tokens sold in BPS (Basis Points).
        uint256 legionFeeOnTokensSoldBps;
        /// @dev The minimum pledge amount denominated in the `bidToken`
        uint256 minimumPledgeAmount;
        /// @dev The public key used to encrypt the sealed bids.
        Point publicKey;
        /// @dev The address of the token used for raising capital.
        address bidToken;
        /// @dev The address of the token being sold to investors.
        address askToken;
        /// @dev The admin address of the project raising capital.
        address projectAdmin;
        /// @dev The address of Legion's Address Registry contract.
        address addressRegistry;
    }

    /// @notice A struct describing the sealed bid auction status.
    struct SealedBidAuctionStatus {
        /// @dev The unix timestamp (seconds) of the block when the sale starts.
        uint256 startTime;
        /// @dev The unix timestamp (seconds) of the block when the sale ends.
        uint256 endTime;
        /// @dev The unix timestamp (seconds) of the block when the refund period ends.
        uint256 refundEndTime;
        /// @dev The unix timestamp (seconds) of the block when the lockup period ends.
        uint256 lockupEndTime;
        /// @dev The unix timestamp (seconds) of the block when the vesting period starts.
        uint256 vestingStartTime;
        /// @dev The total capital pledged by investors.
        uint256 totalCapitalPledged;
        /// @dev The total amount of tokens allocated to investors.
        uint256 totalTokensAllocated;
        /// @dev The total capital raised from the sale.
        uint256 totalCapitalRaised;
        /// @dev The private key used to decrypt the bids. Not set until results are published.
        uint256 privateKey;
        /// @dev The merkle root for verification of token distribution amounts.
        bytes32 claimTokensMerkleRoot;
        /// @dev The merkle root for verification of excess capital distribution amounts.
        bytes32 excessCapitalMerkleRoot;
        /// @dev Whether the sale has been canceled or not.
        bool isCanceled;
        /// @dev Whether tokens have been supplied by the project or not.
        bool tokensSupplied;
        /// @dev Whether raised capital has been withdrawn from the sale by the project or not.
        bool capitalWithdrawn;
    }

    /// @notice A struct describing the encrypted bid
    struct EncryptedBid {
        /// @dev The encrypted amount out.
        uint256 encryptedAmountOut;
        /// @dev The public key used to encrypt the bid
        Point publicKey;
    }

    /**
     * @notice Initialized the contract with correct parameters.
     *
     * @param sealedBidAuctionConfig The configuration for the sealed bid auction.
     */
    function initialize(SealedBidAuctionConfig calldata sealedBidAuctionConfig) external;

    /**
     * @notice Pledge capital to the sealed bid auction.
     *
     * @param amount The amount of capital pledged.
     * @param sealedBid The encoded sealed bid data.
     * @param signature The Legion signature for verification.
     */
    function pledgeCapital(uint256 amount, bytes calldata sealedBid, bytes memory signature) external;

    /**
     * @notice Initializes the process of publishing of sale results, by locking sale cancelation.
     */
    function initializePublishSaleResults() external;

    /**
     * @notice Publish merkle root for distribution of tokens, once the sale has concluded.
     *
     * @dev Can be called only by the Legion admin address.
     *
     * @param merkleRoot The merkle root to verify against.
     * @param tokensAllocated The total amount of tokens allocated for distribution among investors.
     * @param capitalRaised The total capital raised from the auction
     * @param sealedBidPrivateKey the private key used to decrypt sealed bids
     */
    function publishSaleResults(
        bytes32 merkleRoot,
        uint256 tokensAllocated,
        uint256 capitalRaised,
        uint256 sealedBidPrivateKey
    ) external;

    /**
     * @notice Returns the configuration for the sealed bid auction.
     */
    function saleConfiguration() external view returns (SealedBidAuctionConfig memory saleConfig);

    /**
     * @notice Returns the status for the sealed bid auction.
     */
    function saleStatus() external view returns (SealedBidAuctionStatus memory sealedBidAuctionStatus);

    /**
     * @notice Decrypts the sealed bid, once the private key has been published by Legion.
     *
     * @dev Can be called only of the private key has been published.
     *
     * @param encryptedAmountOut The encrypted bid amount
     * @param salt The salt used in the encryption process
     */
    function decryptSealedBid(uint256 encryptedAmountOut, uint256 salt) external view returns (uint256);
}

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

pragma solidity ^0.8.20;

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

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

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

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

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

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

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

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

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

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

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

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

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

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

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

        emit Transfer(from, to, value);
    }

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the Merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates Merkle trees that are safe
 * against this attack out of the box.
 *
 * IMPORTANT: Consider memory side-effects when using custom hashing functions
 * that access memory in an unsafe way.
 *
 * NOTE: This library supports proof verification for merkle trees built using
 * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
 * leaf inclusion in trees built using non-commutative hashing functions requires
 * additional logic that is not supported by this library.
 */
library MerkleProof {
    /**
     *@dev The multiproof provided is not valid.
     */
    error MerkleProofInvalidMultiproof();

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProof(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function processProof(
        bytes32[] memory proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProofCalldata(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function processProofCalldata(
        bytes32[] calldata proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProof(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }
}

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

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

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

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

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

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

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

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

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {ILegionAddressRegistry} from "./interfaces/ILegionAddressRegistry.sol";
import {ILegionBaseSale} from "./interfaces/ILegionBaseSale.sol";
import {ILegionLinearVesting} from "./interfaces/ILegionLinearVesting.sol";
import {ILegionVestingFactory} from "./interfaces/ILegionVestingFactory.sol";

abstract contract LegionBaseSale is ILegionBaseSale, Initializable {
    using SafeERC20 for IERC20;
    using ECDSA for bytes32;
    using MessageHashUtils for bytes32;

    /// @dev The sale period duration in seconds.
    uint256 internal salePeriodSeconds;

    /// @dev The refund period duration in seconds.
    uint256 internal refundPeriodSeconds;

    /// @dev The lockup period duration in seconds.
    uint256 internal lockupPeriodSeconds;

    /// @dev The vesting schedule duration for the token sold in seconds.
    uint256 internal vestingDurationSeconds;

    /// @dev The vesting cliff duration for the token sold in seconds.
    uint256 internal vestingCliffDurationSeconds;

    /// @dev Legion's fee on capital raised in BPS (Basis Points).
    uint256 internal legionFeeOnCapitalRaisedBps;

    /// @dev Legion's fee on tokens sold in BPS (Basis Points).
    uint256 internal legionFeeOnTokensSoldBps;

    /// @dev The minimum pledge amount denominated in the `bidToken`
    uint256 internal minimumPledgeAmount;

    /// @dev The address of the token used for raising capital.
    address internal bidToken;

    /// @dev The address of the token being sold to investors.
    address internal askToken;

    /// @dev The admin address of the project raising capital.
    address internal projectAdmin;

    /// @dev The address of Legion's Address Registry contract.
    address internal addressRegistry;

    /// @dev The address of Legion bouncer.
    address internal legionBouncer;

    /// @dev The address of Legion signer.
    address internal legionSigner;

    /// @dev The address of Legion fee receiver.
    address internal legionFeeReceiver;

    /// @dev The address of Legion's Vesting Factory contract.
    address internal vestingFactory;

    /// @dev The unix timestamp (seconds) of the block when the sale starts.
    uint256 internal startTime;

    /// @dev The unix timestamp (seconds) of the block when the sale ends.
    uint256 internal endTime;

    /// @dev The unix timestamp (seconds) of the block when the refund period ends.
    uint256 internal refundEndTime;

    /// @dev The unix timestamp (seconds) of the block when the lockup period ends.
    uint256 internal lockupEndTime;

    /// @dev The unix timestamp (seconds) of the block when the vesting period starts.
    uint256 internal vestingStartTime;

    /// @dev The total capital pledged by investors.
    uint256 internal totalCapitalPledged;

    /// @dev The total amount of tokens allocated to investors.
    uint256 internal totalTokensAllocated;

    /// @dev The total capital raised from the sale.
    uint256 internal totalCapitalRaised;

    /// @dev The merkle root for verification of token distribution amounts.
    bytes32 internal claimTokensMerkleRoot;

    /// @dev The merkle root for verification of excess capital distribution amounts.
    bytes32 internal excessCapitalMerkleRoot;

    /// @dev Whether the sale has been canceled or not.
    bool internal isCanceled;

    /// @dev Whether tokens have been supplied by the project or not.
    bool internal tokensSupplied;

    /// @dev Whether raised capital has been withdrawn from the sale by the project or not.
    bool internal capitalWithdrawn;

    /// @dev Mapping of investor address to investor position.
    mapping(address investorAddress => InvestorPosition investorPosition) public investorPositions;

    /// @dev Constant representing 1 hour in seconds.
    uint256 internal constant ONE_HOUR = 3600;

    /// @dev Constant representing 2 weeks in seconds.
    uint256 internal constant TWO_WEEKS = 1209600;

    /// @dev Constant representing 3 months in seconds.
    uint256 internal constant THREE_MONTHS = 7776000;

    /// @dev Constant representing 6 months in seconds.
    uint256 internal constant SIX_MONTHS = 15780000;

    /// @dev Constant representing the LEGION_BOUNCER unique ID
    bytes32 internal constant LEGION_BOUNCER_ID = bytes32("LEGION_BOUNCER");

    /// @dev Constant representing the LEGION_SIGNER unique ID
    bytes32 internal constant LEGION_SIGNER_ID = bytes32("LEGION_SIGNER");

    /// @dev Constant representing the LEGION_FEE_RECEIVER unique ID
    bytes32 internal constant LEGION_FEE_RECEIVER_ID = bytes32("LEGION_FEE_RECEIVER");

    /// @dev Constant representing the LEGION_VESTING_FACTORY unique ID
    bytes32 internal constant LEGION_VESTING_FACTORY_ID = bytes32("LEGION_VESTING_FACTORY");

    /**
     * @notice Throws if called by any account other than Legion.
     */
    modifier onlyLegion() {
        if (msg.sender != legionBouncer) revert NotCalledByLegion();
        _;
    }

    /**
     * @notice Throws if called by any account other than the Project.
     */
    modifier onlyProject() {
        if (msg.sender != projectAdmin) revert NotCalledByProject();
        _;
    }

    /**
     * @notice Throws when method is called and the `askToken` is unavailable.
     */
    modifier askTokenAvailable() {
        if (askToken == address(0)) revert AskTokenUnavailable();
        _;
    }

    /**
     * @notice LegionBaseSale constructor.
     */
    constructor() {
        /// Disable initialization
        _disableInitializers();
    }

    /**
     * @notice See {ILegionBaseSale-requestRefund}.
     */
    function requestRefund() external virtual {
        /// Verify that the refund period is not over
        _verifyRefundPeriodIsNotOver();

        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that the sale has ended
        _verifySaleHasEnded();

        /// Cache the amount to refund in memory
        uint256 amountToRefund = investorPositions[msg.sender].pledgedCapital;

        /// Revert in case there's nothing to refund
        if (amountToRefund == 0) revert InvalidRefundAmount();

        /// Set the total pledged capital for the investor to 0
        investorPositions[msg.sender].pledgedCapital = 0;

        /// Decrement total capital pledged from investors
        totalCapitalPledged -= amountToRefund;

        /// Emit successfully CapitalRefunded
        emit CapitalRefunded(amountToRefund, msg.sender);

        /// Transfer the refunded amount back to the investor
        IERC20(bidToken).safeTransfer(msg.sender, amountToRefund);
    }

    /**
     * @notice See {ILegionBaseSale-withdrawCapital}.
     */
    function withdrawCapital() external virtual onlyProject {
        /// Verify that the refund period is over
        _verifyRefundPeriodIsOver();

        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that sale results have been published
        _verifySaleResultsArePublished();

        /// Verify that the project can withdraw capital
        _verifyCanWithdrawCapital();

        /// Check if projects are withdrawing capital on the sale source chain
        if (askToken != address(0)) {
            /// Allow projects to withdraw capital only in case they've supplied tokens
            _verifyTokensSupplied();
        }

        /// Flag that the capital has been withdrawn
        capitalWithdrawn = true;

        /// Cache value in memory
        uint256 _totalCapitalRaised = totalCapitalRaised;

        /// Calculate Legion Fee
        uint256 _legionFee = (legionFeeOnCapitalRaisedBps * _totalCapitalRaised) / 10000;

        /// Emit successfully CapitalWithdrawn
        emit CapitalWithdrawn(_totalCapitalRaised, msg.sender);

        /// Transfer the raised capital to the project owner
        IERC20(bidToken).safeTransfer(msg.sender, (_totalCapitalRaised - _legionFee));

        /// Transfer the Legion fee to the Legion fee receiver address
        if (_legionFee != 0) IERC20(bidToken).safeTransfer(legionFeeReceiver, _legionFee);
    }

    /**
     * @notice See {ILegionBaseSale-claimTokenAllocation}.
     */
    function claimTokenAllocation(uint256 amount, bytes32[] calldata proof) external virtual askTokenAvailable {
        /// Verify that sales results have been published
        _verifySaleResultsArePublished();

        /// Verify that the investor is eligible to claim the requested amount
        _verifyCanClaimTokenAllocation(msg.sender, amount, proof);

        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that the lockup period is over
        _verifyLockupPeriodIsOver();

        /// Mark that the token amount has been settled
        investorPositions[msg.sender].hasSettled = true;

        /// Deploy vesting and distribute tokens only if there is anything to distribute
        if (amount != 0) {
            /// Deploy a linear vesting schedule contract
            address payable vestingAddress = _createVesting(
                msg.sender,
                uint64(vestingStartTime),
                uint64(vestingDurationSeconds),
                uint64(vestingCliffDurationSeconds)
            );

            /// Emit successfully TokenAllocationClaimed
            emit TokenAllocationClaimed(amount, msg.sender, vestingAddress);

            /// Save the vesting address for the investor
            investorPositions[msg.sender].vestingAddress = vestingAddress;

            /// Transfer the allocated amount of tokens for distribution
            IERC20(askToken).safeTransfer(vestingAddress, amount);
        }
    }

    /**
     * @notice See {ILegionBaseSale-claimExcessCapital}.
     */
    function claimExcessCapital(uint256 amount, bytes32[] calldata proof) external virtual {
        /// Verify that the sale has ended
        _verifySaleHasEnded();

        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that the investor is eligible to get excess capital back
        _verifyCanClaimExcessCapital(msg.sender, amount, proof);

        /// Mark that the excess capital has been returned
        investorPositions[msg.sender].hasClaimedExcess = true;

        if (amount != 0) {
            /// Decrement the total pledged capital for the investor
            investorPositions[msg.sender].pledgedCapital -= amount;

            /// Decrement total capital pledged from investors
            totalCapitalPledged -= amount;

            /// Emit successfully ExcessCapitalClaimed
            emit ExcessCapitalClaimed(amount, msg.sender);

            /// Transfer the excess capital back to the investor
            IERC20(bidToken).safeTransfer(msg.sender, amount);
        }
    }

    /**
     * @notice See {ILegionBaseSale-releaseTokens}.
     */
    function releaseTokens() external virtual askTokenAvailable {
        /// Get the investor position details
        InvestorPosition memory position = investorPositions[msg.sender];

        /// Revert in case there's no vesting for the investor
        if (position.vestingAddress == address(0)) revert ZeroAddressProvided();

        /// Release tokens to the investor account
        ILegionLinearVesting(position.vestingAddress).release(askToken);
    }

    /**
     * @notice See {ILegionBaseSale-supplyTokens}.
     */
    function supplyTokens(uint256 amount, uint256 legionFee) external virtual onlyProject askTokenAvailable {
        /// Verify that tokens can be supplied for distribution
        _verifyCanSupplyTokens(amount);

        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that tokens have not been supplied
        _verifyTokensNotSupplied();

        /// Flag that tokens have been supplied
        tokensSupplied = true;

        /// Calculate and verify Legion Fee
        if (legionFee != (legionFeeOnTokensSoldBps * amount) / 10000) revert InvalidFeeAmount();

        /// Emit successfully TokensSuppliedForDistribution
        emit TokensSuppliedForDistribution(amount, legionFee);

        /// Transfer the allocated amount of tokens for distribution
        IERC20(askToken).safeTransferFrom(msg.sender, address(this), amount);

        /// Transfer the Legion fee to the Legion fee receiver address
        if (legionFee != 0) IERC20(askToken).safeTransferFrom(msg.sender, legionFeeReceiver, legionFee);
    }

    /**
     * @notice See {ILegionBaseSale-publishExcessCapitalResults}.
     */
    function publishExcessCapitalResults(bytes32 merkleRoot) external virtual onlyLegion {
        /// Verify that the sale is not canceled
        _verifySaleNotCanceled();

        /// Verify that the sale has ended
        _verifySaleHasEnded();

        /// Verify that excess capital results are not already published
        _verifyCanPublishExcessCapitalResults();

        /// Set the merkle root for claiming excess capital
        excessCapitalMerkleRoot = merkleRoot;

        /// Emit successfully ExcessCapitalResultsPublished
        emit ExcessCapitalResultsPublished(merkleRoot);
    }

    /**
     * @notice See {ILegionBaseSale-cancelSale}.
     */
    function cancelSale() public virtual onlyProject {
        /// Allow the Project to cancel the sale at any time until results are published
        /// Results are published after the refund period is over
        _verifySaleResultsNotPublished();

        /// Verify sale has not already been canceled
        _verifySaleNotCanceled();

        /// Mark sale as canceled
        isCanceled = true;

        /// Emit successfully SaleCanceled
        emit SaleCanceled();
    }

    /**
     * @notice See {ILegionBaseSale-cancelExpiredSale}.
     */
    function cancelExpiredSale() external virtual {
        /// Verify that the lockup period is over
        _verifyLockupPeriodIsOver();

        /// Verify sale has not already been canceled
        _verifySaleNotCanceled();

        if (askToken != address(0)) {
            /// Verify that no tokens have been supplied by the project
            _verifyTokensNotSupplied();
        } else {
            /// Verify that the sale results have not been published
            _verifySaleResultsNotPublished();
        }

        /// Mark sale as canceled
        isCanceled = true;

        /// Emit successfully SaleCanceled
        emit SaleCanceled();
    }

    /**
     * @notice See {ILegionBaseSale-claimBackCapitalIfCanceled}.
     */
    function claimBackCapitalIfCanceled() external virtual {
        /// Verify that the sale has been actually canceled
        _verifySaleIsCanceled();

        /// Cache the amount to refund in memory
        uint256 amountToClaim = investorPositions[msg.sender].pledgedCapital;

        /// Revert in case there's nothing to claim
        if (amountToClaim == 0) revert InvalidClaimAmount();

        /// Set the total pledged capital for the investor to 0
        investorPositions[msg.sender].pledgedCapital = 0;

        /// Decrement total capital pledged from investors
        totalCapitalPledged -= amountToClaim;

        /// Emit successfully CapitalRefundedAfterCancel
        emit CapitalRefundedAfterCancel(amountToClaim, msg.sender);

        /// Transfer the refunded amount back to the investor
        IERC20(bidToken).safeTransfer(msg.sender, amountToClaim);
    }

    /**
     * @notice See {ILegionBaseSale-emergencyWithdraw}.
     */
    function emergencyWithdraw(address receiver, address token, uint256 amount) external virtual onlyLegion {
        /// Emit successfully EmergencyWithdraw
        emit EmergencyWithdraw(receiver, token, amount);

        /// Transfer the amount to Legion's address
        IERC20(token).safeTransfer(receiver, amount);
    }

    /**
     * @notice See {ILegionBaseSale-syncLegionAddresses}.
     */
    function syncLegionAddresses() external virtual onlyLegion {
        /// Cache Legion addresses from `LegionAddressRegistry`
        legionBouncer = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_BOUNCER_ID);
        legionSigner = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_SIGNER_ID);
        legionFeeReceiver = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_FEE_RECEIVER_ID);
        vestingFactory = ILegionAddressRegistry(addressRegistry).getLegionAddress(LEGION_VESTING_FACTORY_ID);

        /// Emit successfully LegionAddressesSynced
        emit LegionAddressesSynced(legionBouncer, legionSigner, legionFeeReceiver, vestingFactory);
    }

    /**
     * @notice Create a vesting schedule contract.
     *
     * @param _beneficiary The beneficiary.
     * @param _startTimestamp The start timestamp.
     * @param _durationSeconds The duration in seconds.
     * @param _cliffDurationSeconds The cliff duration in seconds.
     *
     * @return vestingInstance The address of the deployed vesting instance.
     */
    function _createVesting(
        address _beneficiary,
        uint64 _startTimestamp,
        uint64 _durationSeconds,
        uint64 _cliffDurationSeconds
    ) internal virtual returns (address payable vestingInstance) {
        /// Deploy a vesting schedule instance
        vestingInstance = ILegionVestingFactory(vestingFactory).createLinearVesting(
            _beneficiary, _startTimestamp, _durationSeconds, _cliffDurationSeconds
        );
    }

    /**
     * @notice Verify if an investor is eligible to claim tokens allocated from the sale.
     *
     * @param _investor The address of the investor trying to participate.
     * @param _amount The amount to claim.
     * @param _proof The merkle proof that the investor is part of the whitelist
     */
    function _verifyCanClaimTokenAllocation(address _investor, uint256 _amount, bytes32[] calldata _proof)
        internal
        view
        virtual
    {
        /// Generate the merkle leaf
        bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(_investor, _amount))));

        /// Load the investor position
        InvestorPosition memory position = investorPositions[_investor];

        /// Verify the merkle proof
        if (!MerkleProof.verify(_proof, claimTokensMerkleRoot, leaf)) revert NotInClaimWhitelist(_investor);

        /// Check if the investor has already settled their allocation
        if (position.hasSettled) revert AlreadySettled(_investor);

        /// Safeguard to check if the investor has pledged capital
        if (position.pledgedCapital == 0) revert NoCapitalPledged(_investor);
    }

    /**
     * @notice Verify if an investor is eligible to get excess capital back.
     *
     * @param _investor The address of the investor trying to participate.
     * @param _amount The amount to claim.
     * @param _proof The merkle proof that the investor is part of the whitelist
     */
    function _verifyCanClaimExcessCapital(address _investor, uint256 _amount, bytes32[] calldata _proof)
        internal
        view
        virtual
    {
        /// Generate the merkle leaf
        bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(_investor, _amount))));

        /// Load the investor position
        InvestorPosition memory position = investorPositions[_investor];

        /// Verify the merkle proof
        if (!MerkleProof.verify(_proof, excessCapitalMerkleRoot, leaf)) revert CannotClaimExcessCapital(_investor);

        /// Check if the investor has already settled their allocation
        if (position.hasClaimedExcess) revert AlreadyClaimedExcess(_investor);

        /// Safeguard to check if the investor has pledged capital
        if (position.pledgedCapital == 0) revert NoCapitalPledged(_investor);
    }

    /**
     * @notice Verify that the amount pledge is more than the minimum required.
     *
     * @param _amount The amount being pledged.
     */
    function _verifyMinimumPledgeAmount(uint256 _amount) internal view virtual {
        if (_amount < minimumPledgeAmount) revert InvalidPledgeAmount(_amount);
    }

    /**
     * @notice Verify that the sale has ended.
     */
    function _verifySaleHasEnded() internal view virtual {
        if (block.timestamp < endTime) revert SaleHasNotEnded();
    }

    /**
     * @notice Verify that the sale has not ended.
     */
    function _verifySaleHasNotEnded() internal view virtual {
        if (block.timestamp >= endTime) revert SaleHasEnded();
    }

    /**
     * @notice Verify that the refund period is over.
     */
    function _verifyRefundPeriodIsOver() internal view virtual {
        if (block.timestamp < refundEndTime) revert RefundPeriodIsNotOver();
    }

    /**
     * @notice Verify that the refund period is not over.
     */
    function _verifyRefundPeriodIsNotOver() internal view virtual {
        if (block.timestamp >= refundEndTime) revert RefundPeriodIsOver();
    }

    /**
     * @notice Verify that the lockup period is over.
     */
    function _verifyLockupPeriodIsOver() internal view virtual {
        if (block.timestamp < lockupEndTime) revert LockupPeriodIsNotOver();
    }

    /**
     * @notice Verify if sale results are published.
     */
    function _verifySaleResultsArePublished() internal view virtual {
        if (totalTokensAllocated == 0) revert SaleResultsNotPublished();
    }

    /**
     * @notice Verify if sale results are not published.
     */
    function _verifySaleResultsNotPublished() internal view virtual {
        if (totalTokensAllocated != 0) revert SaleResultsAlreadyPublished();
    }

    /**
     * @notice Verify if the project can supply tokens for distribution.
     *
     * @param _amount The amount to supply.
     */
    function _verifyCanSupplyTokens(uint256 _amount) internal view virtual {
        /// Revert if Legion has not set the total amount of tokens allocated for distribution
        if (totalTokensAllocated == 0) revert TokensNotAllocated();

        /// Revert if the amount of tokens supplied is different than the amount set by Legion
        if (_amount != totalTokensAllocated) revert InvalidTokenAmountSupplied(_amount);
    }

    /**
     * @notice Verify if Legion can publish sale results.
     */
    function _verifyCanPublishSaleResults() internal view virtual {
        if (totalTokensAllocated != 0) revert TokensAlreadyAllocated(totalTokensAllocated);
    }

    /**
     * @notice Verify if Legion can publish the excess capital results.
     */
    function _verifyCanPublishExcessCapitalResults() internal view virtual {
        if (excessCapitalMerkleRoot != bytes32(0)) revert ExcessCapitalResultsAlreadyPublished(excessCapitalMerkleRoot);
    }

    /**
     * @notice Verify that the sale is not canceled.
     */
    function _verifySaleNotCanceled() internal view virtual {
        if (isCanceled) revert SaleIsCanceled();
    }

    /**
     * @notice Verify that the sale is canceled.
     */
    function _verifySaleIsCanceled() internal view virtual {
        if (!isCanceled) revert SaleIsNotCanceled();
    }

    /**
     * @notice Verify that the project has not supplied tokens to the sale.
     */
    function _verifyTokensNotSupplied() internal view virtual {
        if (tokensSupplied) revert TokensAlreadySupplied();
    }

    /**
     * @notice Verify that the project has supplied tokens to the sale.
     */
    function _verifyTokensSupplied() internal view virtual {
        if (!tokensSupplied) revert TokensNotSupplied();
    }

    /**
     * @notice Verify that the signature provided is signed by Legion.
     *
     * @param _signature The signature to verify.
     */
    function _verifyLegionSignature(bytes memory _signature) internal view virtual {
        bytes32 _data = keccak256(abi.encodePacked(msg.sender, address(this), block.chainid)).toEthSignedMessageHash();
        if (_data.recover(_signature) != legionSigner) revert InvalidSignature();
    }

    /**
     * @notice Verify that the project can withdraw capital.
     */
    function _verifyCanWithdrawCapital() internal view virtual {
        if (capitalWithdrawn) revert CapitalAlreadyWithdrawn();
    }
}

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
interface ILegionAddressRegistry {
    /**
     * @notice This event is emitted when a new Legion address is set or updated.
     *
     * @param id The unique identifier of the address.
     * @param previousAddress The previous address before the update.
     * @param updatedAddress The updated address.
     */
    event LegionAddressSet(bytes32 id, address previousAddress, address updatedAddress);

    /**
     * @notice Sets a Legion address.
     *
     * @param id The unique identifier of the address.
     * @param updatedAddress The updated address.
     */
    function setLegionAddress(bytes32 id, address updatedAddress) external;

    /**
     * @notice Gets a Legion address.
     *
     * @param id The unique identifier of the address.
     *
     * @return The requested address.
     */
    function getLegionAddress(bytes32 id) external view returns (address);
}

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
interface ILegionLinearVesting {
    /**
     * @notice See {VestingWalletUpgradeable-start}.
     */
    function start() external view returns (uint256);

    /**
     * @notice See {VestingWalletUpgradeable-duration}.
     */
    function duration() external view returns (uint256);

    /**
     * @notice See {VestingWalletUpgradeable-end}.
     */
    function end() external view returns (uint256);

    /**
     * @notice See {VestingWalletUpgradeable-released}.
     */
    function released() external view returns (uint256);

    /**
     * @notice See {VestingWalletUpgradeable-released}.
     */
    function released(address token) external view returns (uint256);

    /**
     * @notice See {VestingWalletUpgradeable-releasable}.
     */
    function releasable() external view returns (uint256);

    /**
     * @notice See {VestingWalletUpgradeable-releasable}.
     */
    function releasable(address token) external view returns (uint256);

    /**
     * @notice See {VestingWalletUpgradeable-release}.
     */
    function release() external;

    /**
     * @notice See {VestingWalletUpgradeable-release}.
     */
    function release(address token) external;

    /**
     * @notice See {VestingWalletUpgradeable-vestedAmount}.
     */
    function vestedAmount(uint64 timestamp) external view returns (uint256);

    /**
     * @notice See {VestingWalletUpgradeable-vestedAmount}.
     */
    function vestedAmount(address token, uint64 timestamp) external view returns (uint256);
}

File 21 of 38 : ILegionVestingFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
interface ILegionVestingFactory {
    /**
     * @notice This event is emitted when a new linear vesting schedule contract is deployed for an investor.
     *
     * @param beneficiary The address of the beneficiary.
     * @param startTimestamp The start timestamp of the vesting period.
     * @param durationSeconds The vesting duration in seconds.
     * @param cliffDurationSeconds The vesting cliff duration in seconds.
     */
    event NewLinearVestingCreated(
        address beneficiary, uint64 startTimestamp, uint64 durationSeconds, uint64 cliffDurationSeconds
    );

    /**
     * @notice Deploy a LegionLinearVesting contract.
     *
     * @dev Can be called only by addresses allowed to deploy.
     *
     * @param beneficiary The beneficiary.
     * @param startTimestamp The start timestamp.
     * @param durationSeconds The duration in seconds.
     * @param cliffDurationSeconds The cliff duration in seconds.
     *
     * @return linearVestingInstance The address of the deployed linearVesting instance.
     */
    function createLinearVesting(
        address beneficiary,
        uint64 startTimestamp,
        uint64 durationSeconds,
        uint64 cliffDurationSeconds
    ) external returns (address payable linearVestingInstance);
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.25;

struct Point {
    uint256 x;
    uint256 y;
}

/// @notice This library implements a simplified version of the Elliptic Curve Integrated Encryption Scheme (ECIES) using the alt_bn128 curve.
/// @dev    The alt_bn128 curve is used since there are precompiled contracts for point addition, calar multiplication, and pairing that make it gas efficient.
///         XOR encryption is used with the derived symmetric key, which is not as secure as modern encryption algorithms, but is simple and cheap to implement.
///         We use keccak256 as the key derivation function, which, as a hash-based key derivation function, is susceptible to dictionary attacks, but is sufficient for our purposes.
///         As a result of the relative weakness of the symmetric encryption and key derivation function, we rely on the security of the elliptic curve to hide the shared secret.
///         Recent advances in attacks on the alt_bn128 curve have reduced the expected security of the curve to ~98 bits.
///         Therefore, this implementation should not be used to secure value directly. It can be used to secure data which, if compromised, would not be catastrophic.
///         Inspired by:
///         - https://cryptobook.nakov.com/asymmetric-key-ciphers/ecies-public-key-encryption
///         - https://billatnapier.medium.com/how-do-i-implement-symmetric-key-encryption-in-ethereum-14afffff6e42
///         - https://github.com/PhilippSchindler/EthDKG/blob/master/contracts/ETHDKG.sol
///         This library assumes the curve used is y^2 = x^3 + 3, which has generator point (1, 2).
/// @author Oighty
library ECIES {
    uint256 public constant GROUP_ORDER =
        21_888_242_871_839_275_222_246_405_745_257_275_088_548_364_400_416_034_343_698_204_186_575_808_495_617;
    uint256 public constant FIELD_MODULUS =
        21_888_242_871_839_275_222_246_405_745_257_275_088_696_311_157_297_823_662_689_037_894_645_226_208_583;

    /// @notice We use a hash function to derive a symmetric key from the shared secret and a provided salt.
    /// @dev This is not as secure as modern key derivation functions, since hash-based keys are susceptible to dictionary attacks.
    ///      However, it is simple and cheap to implement, and is sufficient for our purposes.
    ///      The salt prevents duplication even if a shared secret is reused.
    function deriveSymmetricKey(uint256 sharedSecret_, uint256 s1_) public pure returns (uint256) {
        return uint256(keccak256(abi.encodePacked(sharedSecret_, s1_)));
    }

    /// @notice Recover the shared secret as the x-coordinate of the EC point computed as the multiplication of the ciphertext public key and the private key.
    function recoverSharedSecret(
        Point memory ciphertextPubKey_,
        uint256 privateKey_
    ) public view returns (uint256) {
        // Validate public key is on the curve
        if (!isOnBn128(ciphertextPubKey_)) revert("Invalid public key.");

        // Validate private key is less than the group order and not zero
        if (privateKey_ >= GROUP_ORDER || privateKey_ == 0) revert("Invalid private key.");

        Point memory p = _ecMul(ciphertextPubKey_, privateKey_);

        return p.x;
    }

    /// @notice Decrypt a message using the provided ciphertext, ciphertext public key, and private key from the recipient.
    /// @dev    We use XOR encryption. The security of the algorithm relies on the security of the elliptic curve to hide the shared secret.
    /// @param ciphertext_ - The encrypted message.
    /// @param ciphertextPubKey_ - The ciphertext public key provided by the sender.
    /// @param privateKey_ - The private key of the recipient.
    /// @param salt_ - A salt used to derive the symmetric key from the shared secret. Ensures that the symmetric key is unique even if the shared secret is reused.
    /// @return message_ - The decrypted message.
    function decrypt(
        uint256 ciphertext_,
        Point memory ciphertextPubKey_,
        uint256 privateKey_,
        uint256 salt_
    ) public view returns (uint256 message_) {
        // Calculate the shared secret
        // Validates the ciphertext public key is on the curve and the private key is valid
        uint256 sharedSecret = recoverSharedSecret(ciphertextPubKey_, privateKey_);

        // Derive the symmetric key from the shared secret and the salt
        uint256 symmetricKey = deriveSymmetricKey(sharedSecret, salt_);

        // Decrypt the message using XOR encryption
        message_ = ciphertext_ ^ symmetricKey;
    }

    /// @notice Encrypt a message using the provided recipient public key and the sender private key. Note: sending the private key to an RPC can leak it. This should be used locally.
    /// @param message_ - The message to encrypt.
    /// @param recipientPubKey_ - The public key of the recipient.
    /// @param privateKey_ - The private key to use to encrypt the message.
    /// @param salt_ - A salt used to derive the symmetric key from the shared secret. Ensures that the symmetric key is unique even if the shared secret is reused.
    /// @return ciphertext_ - The encrypted message.
    /// @return messagePubKey_ - The public key of the message that the receipient can use to decrypt it.
    function encrypt(
        uint256 message_,
        Point memory recipientPubKey_,
        uint256 privateKey_,
        uint256 salt_
    ) public view returns (uint256 ciphertext_, Point memory messagePubKey_) {
        // Create the message public key using the provided private key
        // Validates the private key is valid
        messagePubKey_ = calcPubKey(Point(1, 2), privateKey_);

        // Calculate the shared secret
        // Validates the recipient public key is on the curve
        uint256 sharedSecret = recoverSharedSecret(recipientPubKey_, privateKey_);

        // Derive the symmetric key from the shared secret and the salt
        uint256 symmetricKey = deriveSymmetricKey(sharedSecret, salt_);

        // Encrypt the message using XOR encryption
        ciphertext_ = message_ ^ symmetricKey;
    }

    /// @notice Calculate the point on the generator curve that corresponds to the provided private key. This is used as the public key.
    /// @param generator_ - The point on the the alt_bn128 curve. to use as the generator.
    /// @param privateKey_ - The private key to calculate the public key for.
    function calcPubKey(
        Point memory generator_,
        uint256 privateKey_
    ) public view returns (Point memory) {
        // Validate generator is on the curve
        if (!isOnBn128(generator_)) revert("Invalid generator point.");

        // Validate private key is less than the group order and not zero
        if (privateKey_ >= GROUP_ORDER || privateKey_ == 0) revert("Invalid private key.");

        return _ecMul(generator_, privateKey_);
    }

    function _ecMul(Point memory p, uint256 scalar) private view returns (Point memory p2) {
        (bool success, bytes memory output) =
            address(0x07).staticcall{gas: 6000}(abi.encode(p.x, p.y, scalar));

        if (!success || output.length == 0) revert("ecMul failed.");

        p2 = abi.decode(output, (Point));
    }

    /// @notice Checks whether a point is on the alt_bn128 curve.
    /// @param  p - The point to check (consists of x and y coordinates).
    function isOnBn128(Point memory p) public pure returns (bool) {
        // check if the provided point is on the bn128 curve y**2 = x**3 + 3, which has generator point (1, 2)
        return _fieldmul(p.y, p.y) == _fieldadd(_fieldmul(p.x, _fieldmul(p.x, p.x)), 3);
    }

    /// @notice Checks whether a point is valid. We consider a point valid if it is on the curve and not the generator point or the point at infinity.
    function isValid(Point memory p) public pure returns (bool) {
        return isOnBn128(p) && !(p.x == 1 && p.y == 2) && !(p.x == 0 && p.y == 0) && (p.x < FIELD_MODULUS) && (p.y < FIELD_MODULUS);
    }

    function _fieldmul(uint256 a, uint256 b) private pure returns (uint256 c) {
        assembly {
            c := mulmod(a, b, FIELD_MODULUS)
        }
    }

    function _fieldadd(uint256 a, uint256 b) private pure returns (uint256 c) {
        assembly {
            c := addmod(a, b, FIELD_MODULUS)
        }
    }
}

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

/**
 * ██      ███████  ██████  ██  ██████  ███    ██
 * ██      ██      ██       ██ ██    ██ ████   ██
 * ██      █████   ██   ███ ██ ██    ██ ██ ██  ██
 * ██      ██      ██    ██ ██ ██    ██ ██  ██ ██
 * ███████ ███████  ██████  ██  ██████  ██   ████
 *
 * If you find a bug, please contact security(at)legion.cc
 * We will pay a fair bounty for any issue that puts user's funds at risk.
 *
 */
interface ILegionBaseSale {
    /**
     * @notice This event is emitted when capital is successfully withdrawn by the project owner.
     *
     * @param amountToWithdraw The amount of capital withdrawn.
     * @param projectOwner The address of the project owner.
     */
    event CapitalWithdrawn(uint256 amountToWithdraw, address projectOwner);

    /**
     * @notice This event is emitted when capital is successfully refunded to the investor.
     *
     * @param amount The amount of capital refunded to the investor.
     * @param investor The address of the investor who requested the refund.
     */
    event CapitalRefunded(uint256 amount, address investor);

    /**
     * @notice This event is emitted when capital is successfully refunded to the investor after a sale has been canceled.
     *
     * @param amount The amount of capital refunded to the investor.
     * @param investor The address of the investor who requested the refund.
     */
    event CapitalRefundedAfterCancel(uint256 amount, address investor);

    /**
     * @notice This event is emitted when excess capital is successfully claimed by the investor after a sale has ended.
     *
     * @param amount The amount of capital refunded to the investor.
     * @param investor The address of the investor who requested the refund.
     */
    event ExcessCapitalClaimed(uint256 amount, address investor);

    /**
     * @notice This event is emitted when excess capital results are successfully published by the Legion admin.
     *
     * @param merkleRoot The claim merkle root published.
     */
    event ExcessCapitalResultsPublished(bytes32 merkleRoot);

    /**
     * @notice This event is emitted when excess capital results are successfully published by the Legion admin.
     *
     * @param receiver The address of the receiver.
     * @param token The address of the token to be withdrawn.
     * @param amount The amount to be withdrawn.
     */
    event EmergencyWithdraw(address receiver, address token, uint256 amount);

    /**
     * @notice This event is emitted when excess capital results are successfully published by the Legion admin.
     *
     * @param legionBouncer The updated Legion bouncer address.
     * @param legionSigner The updated Legion signer address.
     * @param legionFeeReceiver The updated fee receiver address of Legion.
     * @param vestingFactory The updated vesting factory address.
     */
    event LegionAddressesSynced(
        address legionBouncer, address legionSigner, address legionFeeReceiver, address vestingFactory
    );

    /**
     * @notice This event is emitted when a sale is successfully canceled.
     */
    event SaleCanceled();

    /**
     * @notice This event is emitted when tokens are successfully supplied for distribution by the project admin.
     *
     * @param amount The amount of tokens supplied for distribution.
     * @param legionFee The fee amount collected by Legion.
     */
    event TokensSuppliedForDistribution(uint256 amount, uint256 legionFee);

    /**
     * @notice This event is emitted when tokens are successfully claimed by the investor.
     *
     * @param amount The amount of tokens distributed to the vesting contract.
     * @param investor The address of the investor owning the vesting contract.
     * @param vesting The address of the vesting instance deployed.
     */
    event TokenAllocationClaimed(uint256 amount, address investor, address vesting);

    /**
     * @notice Throws when tokens already settled by investor.
     *
     * @param investor The address of the investor trying to claim.
     */
    error AlreadySettled(address investor);

    /**
     * @notice Throws when excess capital has already been claimed by investor.
     *
     * @param investor The address of the investor trying to get excess capital back.
     */
    error AlreadyClaimedExcess(address investor);

    /**
     * @notice Throws when capital has already been withdrawn by the Project.
     */
    error CapitalAlreadyWithdrawn();

    /**
     * @notice Throws when the excess capital results have already been published.
     *
     * @param merkleRoot The merkle root for distribution of excess capital.
     */
    error ExcessCapitalResultsAlreadyPublished(bytes32 merkleRoot);

    /**
     * @notice Throws when an invalid amount of tokens has been supplied by the project.
     *
     * @param amount The amount of tokens supplied.
     */
    error InvalidTokenAmountSupplied(uint256 amount);

    /**
     * @notice Throws when an invalid amount of tokens has been claimed.
     */
    error InvalidClaimAmount();

    /**
     * @notice Throws when an invalid amount has been requested for refund.
     */
    error InvalidRefundAmount();

    /**
     * @notice Throws when an invalid amount has been requested for fee.
     */
    error InvalidFeeAmount();

    /**
     * @notice Throws when an invalid time config has been provided.
     */
    error InvalidPeriodConfig();

    /**
     * @notice Throws when an invalid pledge amount has been sent.
     *
     * @param amount The amount being pledged.
     */
    error InvalidPledgeAmount(uint256 amount);

    /**
     * @notice Throws when an invalid signature has been provided when pledging capital.
     *
     */
    error InvalidSignature();

    /**
     * @notice Throws when the lockup period is not over.
     */
    error LockupPeriodIsNotOver();

    /**
     * @notice Throws when the investor is not in the claim whitelist for tokens.
     *
     * @param investor The address of the investor.
     */
    error NotInClaimWhitelist(address investor);

    /**
     * @notice Throws when the investor is not flagged to have excess capital returned.
     *
     * @param investor The address of the investor.
     */
    error CannotClaimExcessCapital(address investor);

    /**
     * @notice Throws when no capital has been pledged by an investor.
     *
     * @param investor The address of the investor.
     */
    error NoCapitalPledged(address investor);

    /**
     * @notice Throws when not called by Legion.
     */
    error NotCalledByLegion();

    /**
     * @notice Throws when not called by the Project.
     */
    error NotCalledByProject();

    /**
     * @notice Throws when the `askToken` is unavailable.
     */
    error AskTokenUnavailable();

    /**
     * @notice Throws when the refund period is not over.
     */
    error RefundPeriodIsNotOver();

    /**
     * @notice Throws when the refund period is over.
     */
    error RefundPeriodIsOver();

    /**
     * @notice Throws when the sale has ended.
     */
    error SaleHasEnded();

    /**
     * @notice Throws when the sale has not ended.
     */
    error SaleHasNotEnded();

    /**
     * @notice Throws when the sale is canceled.
     */
    error SaleIsCanceled();

    /**
     * @notice Throws when the sale is not canceled.
     */
    error SaleIsNotCanceled();

    /**
     * @notice Throws when the sale results are not published.
     */
    error SaleResultsNotPublished();

    /**
     * @notice Throws when the sale results have been already published.
     */
    error SaleResultsAlreadyPublished();

    /**
     * @notice Throws when the tokens have already been allocated.
     * @param totalTokensAllocated The total amount of tokens allocated.
     */
    error TokensAlreadyAllocated(uint256 totalTokensAllocated);

    /**
     * @notice Throws when tokens have not been allocated.
     */
    error TokensNotAllocated();

    /**
     * @notice Throws when tokens have already been supplied.
     */
    error TokensAlreadySupplied();

    /**
     * @notice Throws when tokens have not been supplied.
     */
    error TokensNotSupplied();

    /**
     * @notice Throws when zero address has been provided.
     */
    error ZeroAddressProvided();

    /**
     * @notice Throws when zero value has been provided.
     */
    error ZeroValueProvided();

    /// @notice A struct describing the investor position during the sale.
    struct InvestorPosition {
        /// @dev The total amount of capital pledged by the investor.
        uint256 pledgedCapital;
        /// @dev Flag if the investor has claimed the tokens allocated to them.
        bool hasSettled;
        /// @dev Flag if the investor has claimed the excess capital pledged.
        bool hasClaimedExcess;
        /// @dev The address of the investor's vesting contract.
        address vestingAddress;
    }

    /**
     * @notice Request a refund from the sale during the applicable time window.
     */
    function requestRefund() external;

    /**
     * @notice Withdraw capital from the sale contract.
     *
     * @dev Can be called only by the Project admin address.
     */
    function withdrawCapital() external;

    /**
     * @notice Claims the investor token allocation.
     *
     * @param amount The amount to be distributed.
     * @param proof The merkle proof verification for claiming.
     */
    function claimTokenAllocation(uint256 amount, bytes32[] calldata proof) external;

    /**
     * @notice Claim excess capital back to the investor.
     *
     * @param amount The amount to be returned.
     * @param proof The merkle proof verification for the return.
     */
    function claimExcessCapital(uint256 amount, bytes32[] calldata proof) external;

    /**
     * @notice Releases tokens to the investor address.
     */
    function releaseTokens() external;

    /**
     * @notice Supply tokens once the sale results have been published.
     *
     * @dev Can be called only by the Project admin address.
     *
     * @param amount The token amount supplied by the project.
     * @param legionFee The token amount supplied by the project.
     */
    function supplyTokens(uint256 amount, uint256 legionFee) external;

    /**
     * @notice Publish merkle root for distribution of excess capital, once the sale has concluded.
     *
     * @dev Can be called only by the Legion admin address.
     *
     * @param merkleRoot The merkle root to verify against.
     */
    function publishExcessCapitalResults(bytes32 merkleRoot) external;

    /**
     * @notice Cancels an ongoing sale.
     *
     * @dev Can be called only by the Project admin address.
     */
    function cancelSale() external;

    /**
     * @notice Cancels a sale in case the project has not supplied tokens after the lockup period is over.
     */
    function cancelExpiredSale() external;

    /**
     * @notice Claims back capital in case the sale has been canceled.
     */
    function claimBackCapitalIfCanceled() external;

    /**
     * @notice Withdraw tokens from the contract in case of emergency.
     *
     * @dev Can be called only by the Legion admin address.
     *
     * @param receiver The address of the receiver.
     * @param token The address of the token to be withdrawn.
     * @param amount The amount to be withdrawn.
     */
    function emergencyWithdraw(address receiver, address token, uint256 amount) external;

    /**
     * @notice Syncs active Legion addresses from `LegionAddressRegistry.sol`
     */
    function syncLegionAddresses() external;
}

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

pragma solidity ^0.8.20;

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

/**
 * @dev Library of standard hash functions.
 *
 * _Available since v5.1._
 */
library Hashes {
    /**
     * @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
     *
     * NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
     */
    function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
        return a < b ? _efficientKeccak256(a, b) : _efficientKeccak256(b, a);
    }

    /**
     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
     */
    function _efficientKeccak256(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        assembly ("memory-safe") {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

File 31 of 38 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

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

File 32 of 38 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

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

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

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

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

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

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

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

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

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

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

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 1);
        }
        return result;
    }

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

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solady/=lib/solady/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "paris",
  "viaIR": false,
  "libraries": {
    "src/lib/ECIES.sol": {
      "ECIES": "0xBf90a24F24890D8fBFbC4C34542B3ac4Cebe04ab"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"FailedDeployment","type":"error"},{"inputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"saleInstance","type":"address"},{"components":[{"internalType":"uint256","name":"prefundPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"prefundAllocationPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"salePeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"refundPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"lockupPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingCliffDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnCapitalRaisedBps","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnTokensSoldBps","type":"uint256"},{"internalType":"uint256","name":"minimumPledgeAmount","type":"uint256"},{"internalType":"uint256","name":"tokenPrice","type":"uint256"},{"internalType":"address","name":"bidToken","type":"address"},{"internalType":"address","name":"askToken","type":"address"},{"internalType":"address","name":"projectAdmin","type":"address"},{"internalType":"address","name":"addressRegistry","type":"address"}],"indexed":false,"internalType":"struct ILegionFixedPriceSale.FixedPriceSaleConfig","name":"fixedPriceSaleConfig","type":"tuple"}],"name":"NewFixedPriceSaleCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"saleInstance","type":"address"},{"components":[{"internalType":"uint256","name":"refundPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingCliffDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"tokenAllocationOnTGERate","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnCapitalRaisedBps","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnTokensSoldBps","type":"uint256"},{"internalType":"bytes32","name":"saftMerkleRoot","type":"bytes32"},{"internalType":"address","name":"bidToken","type":"address"},{"internalType":"address","name":"projectAdmin","type":"address"},{"internalType":"address","name":"addressRegistry","type":"address"}],"indexed":false,"internalType":"struct ILegionPreLiquidSale.PreLiquidSaleConfig","name":"preLiquidSaleConfig","type":"tuple"}],"name":"NewPreLiquidSaleCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"saleInstance","type":"address"},{"components":[{"internalType":"uint256","name":"salePeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"refundPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"lockupPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingCliffDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnCapitalRaisedBps","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnTokensSoldBps","type":"uint256"},{"internalType":"uint256","name":"minimumPledgeAmount","type":"uint256"},{"components":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"}],"internalType":"struct Point","name":"publicKey","type":"tuple"},{"internalType":"address","name":"bidToken","type":"address"},{"internalType":"address","name":"askToken","type":"address"},{"internalType":"address","name":"projectAdmin","type":"address"},{"internalType":"address","name":"addressRegistry","type":"address"}],"indexed":false,"internalType":"struct ILegionSealedBidAuction.SealedBidAuctionConfig","name":"sealedBidAuctionConfig","type":"tuple"}],"name":"NewSealedBidAuctionCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[{"components":[{"internalType":"uint256","name":"prefundPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"prefundAllocationPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"salePeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"refundPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"lockupPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingCliffDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnCapitalRaisedBps","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnTokensSoldBps","type":"uint256"},{"internalType":"uint256","name":"minimumPledgeAmount","type":"uint256"},{"internalType":"uint256","name":"tokenPrice","type":"uint256"},{"internalType":"address","name":"bidToken","type":"address"},{"internalType":"address","name":"askToken","type":"address"},{"internalType":"address","name":"projectAdmin","type":"address"},{"internalType":"address","name":"addressRegistry","type":"address"}],"internalType":"struct ILegionFixedPriceSale.FixedPriceSaleConfig","name":"fixedPriceSaleConfig","type":"tuple"}],"name":"createFixedPriceSale","outputs":[{"internalType":"address payable","name":"fixedPriceSaleInstance","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"refundPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingCliffDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"tokenAllocationOnTGERate","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnCapitalRaisedBps","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnTokensSoldBps","type":"uint256"},{"internalType":"bytes32","name":"saftMerkleRoot","type":"bytes32"},{"internalType":"address","name":"bidToken","type":"address"},{"internalType":"address","name":"projectAdmin","type":"address"},{"internalType":"address","name":"addressRegistry","type":"address"}],"internalType":"struct ILegionPreLiquidSale.PreLiquidSaleConfig","name":"preLiquidSaleConfig","type":"tuple"}],"name":"createPreLiquidSale","outputs":[{"internalType":"address payable","name":"preLiquidSaleInstance","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"salePeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"refundPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"lockupPeriodSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"vestingCliffDurationSeconds","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnCapitalRaisedBps","type":"uint256"},{"internalType":"uint256","name":"legionFeeOnTokensSoldBps","type":"uint256"},{"internalType":"uint256","name":"minimumPledgeAmount","type":"uint256"},{"components":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"}],"internalType":"struct Point","name":"publicKey","type":"tuple"},{"internalType":"address","name":"bidToken","type":"address"},{"internalType":"address","name":"askToken","type":"address"},{"internalType":"address","name":"projectAdmin","type":"address"},{"internalType":"address","name":"addressRegistry","type":"address"}],"internalType":"struct ILegionSealedBidAuction.SealedBidAuctionConfig","name":"sealedBidAuctionConfig","type":"tuple"}],"name":"createSealedBidAuction","outputs":[{"internalType":"address payable","name":"sealedBidAuctionInstance","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"fixedPriceSaleTemplate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"preLiquidSaleTemplate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sealedBidAuctionTemplate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60e06040526040516100109061015d565b604051809103906000f08015801561002c573d6000803e3d6000fd5b506001600160a01b03166080526040516100459061016a565b604051809103906000f080158015610061573d6000803e3d6000fd5b506001600160a01b031660a05260405161007a90610177565b604051809103906000f080158015610096573d6000803e3d6000fd5b506001600160a01b031660c0523480156100af57600080fd5b506040516185f83803806185f88339810160408190526100ce91610184565b806001600160a01b0381166100fd57604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b6101068161010d565b50506101b4565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b61293780610a8483390190565b6124ac806133bb83390190565b612d918061586783390190565b60006020828403121561019657600080fd5b81516001600160a01b03811681146101ad57600080fd5b9392505050565b60805160a05160c05161088e6101f66000396000818160cc015261028d015260008181610135015261033001526000818160fd015261019f015261088e6000f3fe608060405234801561001057600080fd5b50600436106100935760003560e01c80638da5cb5b116100665780638da5cb5b1461011f57806392be66a414610130578063b03a465c14610157578063e4029d7b1461016a578063f2fde38b1461017d57600080fd5b80630f0846eb1461009857806318a1fa18146100c7578063715018a6146100ee5780638be135a7146100f8575b600080fd5b6100ab6100a636600461052d565b610190565b6040516001600160a01b03909116815260200160405180910390f35b6100ab7f000000000000000000000000000000000000000000000000000000000000000081565b6100f661026a565b005b6100ab7f000000000000000000000000000000000000000000000000000000000000000081565b6000546001600160a01b03166100ab565b6100ab7f000000000000000000000000000000000000000000000000000000000000000081565b6100ab610165366004610546565b61027e565b6100ab610178366004610559565b610321565b6100f661018b366004610588565b6103c4565b600061019a610407565b6101cc7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316610434565b90507fc885257800d59db61c968e71fd418b0f13fc6856a461fe9d6a609769520f42b881836040516101ff929190610689565b60405180910390a1604051630ad7ad1d60e21b81526001600160a01b03821690632b5eb474906102339085906004016106a7565b600060405180830381600087803b15801561024d57600080fd5b505af1158015610261573d6000803e3d6000fd5b50505050919050565b610272610407565b61027c6000610447565b565b6000610288610407565b6102ba7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316610434565b90507f6d58823c69470598cccd895c0db67d76a8af14a2fb8f244c91fec83d30e8cd9581836040516102ed92919061077b565b60405180910390a1604051630335759f60e41b81526001600160a01b0382169063335759f090610233908590600401610799565b600061032b610407565b61035d7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316610434565b90507f19b9a3a06c9c0b07cbe0b2dfabfb3071306ffadc16ae66e12a01e0590816e1a5818360405161039092919061082b565b60405180910390a1604051639eaeba1760e01b81526001600160a01b03821690639eaeba1790610233908590600401610849565b6103cc610407565b6001600160a01b0381166103fb57604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b61040481610447565b50565b6000546001600160a01b0316331461027c5760405163118cdaa760e01b81523360048201526024016103f2565b6000610441826000610497565b92915050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6000814710156104c35760405163cf47918160e01b8152476004820152602481018390526044016103f2565b763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b176020526037600983f090506001600160a01b0381166104415760405163b06ebf3d60e01b815260040160405180910390fd5b60006101e0828403121561054057600080fd5b50919050565b60006101c0828403121561054057600080fd5b6000610140828403121561054057600080fd5b80356001600160a01b038116811461058357600080fd5b919050565b60006020828403121561059a57600080fd5b6105a38261056c565b9392505050565b803582526020810135602083015260408101356040830152606081013560608301526080810135608083015260a081013560a083015260c081013560c083015260e081013560e083015261010080820135818401525061012080820135818401525061014080820135818401525061016061062681830161056c565b6001600160a01b03169083015261018061064182820161056c565b6001600160a01b0316908301526101a061065c82820161056c565b6001600160a01b0316908301526101c061067782820161056c565b6001600160a01b031692019190915250565b6001600160a01b038316815261020081016105a360208301846105aa565b6101e0810161044182846105aa565b803582526020810135602083015260408101356040830152606081013560608301526080810135608083015260a081013560a083015260c081013560c083015260e081013560e083015261010061071b81840182840180358252602090810135910152565b5061014061072a81830161056c565b6001600160a01b03169083015261016061074582820161056c565b6001600160a01b03169083015261018061076082820161056c565b6001600160a01b0316908301526101a061067782820161056c565b6001600160a01b03831681526101e081016105a360208301846106b6565b6101c0810161044182846106b6565b803582526020810135602083015260408101356040830152606081013560608301526080810135608083015260a081013560a083015260c081013560c08301526107f460e0820161056c565b6001600160a01b031660e083015261010061081082820161056c565b6001600160a01b03169083015261012061067782820161056c565b6001600160a01b038316815261016081016105a360208301846107a8565b610140810161044182846107a856fea2646970667358221220a13bc061e1361d7808c9c5e310dcae8a9d2cf305315d1e77533669791f59c47564736f6c634300081900336080604052348015600f57600080fd5b506016601a565b60ca565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff161560695760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b039081161460c75780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b61285e806100d96000396000f3fe608060405234801561001057600080fd5b50600436106101165760003560e01c8063ada14d77116100a2578063e63ea40811610071578063e63ea4081461023a578063e7e104901461024d578063e8d2145314610255578063e90b366314610268578063f9020e331461027b57600080fd5b8063ada14d771461020f578063b14d8bd514610217578063bcb520bd1461021f578063d5cef1331461023257600080fd5b80635111e986116100e95780635111e9861461015357806376eb0443146101cc57806389bd6265146101df57806390dbb806146101f2578063a96f86681461020757600080fd5b80630a636d5b1461011b57806317727a00146101255780632b5eb4741461012d57806349bfdafd14610140575b600080fd5b610123610290565b005b61012361056b565b61012361013b366004612288565b610685565b61012361014e3660046122a1565b610b94565b6101986101613660046122cf565b601b602052600090815260409020805460019091015460ff808216916101008104909116906201000090046001600160a01b031684565b604080519485529215156020850152901515918301919091526001600160a01b031660608201526080015b60405180910390f35b6101236101da3660046122ec565b610c12565b6101236101ed36600461232b565b610cc2565b6101fa610dee565b6040516101c3919061234d565b610123610f28565b61012361102e565b6101236110e3565b61012361022d36600461242d565b611151565b610123611223565b6101236102483660046124ac565b6112ca565b610123611354565b61012361026336600461242d565b61138f565b610123610276366004612503565b6114ae565b610283611580565b6040516101c391906125be565b600c546001600160a01b031633146102bb5760405163abdc864160e01b815260040160405180910390fd5b600b5460405163970559cf60e01b81526d2622a3a4a7a72fa127aaa721a2a960911b60048201526001600160a01b039091169063970559cf90602401602060405180830381865afa158015610314573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103389190612677565b600c80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b81526c2622a3a4a7a72fa9a4a3a722a960991b600482015291169063970559cf90602401602060405180830381865afa1580156103a3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103c79190612677565b600d80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b8152722622a3a4a7a72fa322a2afa922a1a2a4ab22a960691b600482015291169063970559cf90602401602060405180830381865afa158015610438573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061045c9190612677565b600e80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b8152754c4547494f4e5f56455354494e475f464143544f525960501b600482015291169063970559cf90602401602060405180830381865afa1580156104d0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104f49190612677565b600f80546001600160a01b0319166001600160a01b03928316908117909155600c54600d54600e5460408051938616845291851660208401529093169281019290925260608201527fbe3bfe64947d6e55482c3ff74c8fd3ddbb9bc20b6eb9c979b68567d929ebd3839060800160405180910390a1565b600a546001600160a01b031633146105965760405163424e3f9b60e01b815260040160405180910390fd5b61059e6116a7565b6105a66116cc565b6105ae6116f0565b6105b6611713565b6009546001600160a01b0316156105cf576105cf61173d565b601a805462ff0000191662010000179055601754600554600090612710906105f89084906126aa565b61060291906126c1565b604080518481523360208201529192507f2d6f01e5411cbd4277f423f351cb310dc3488eec3993da5a4ae9276837d4b82f910160405180910390a161065e3361064b83856126e3565b6008546001600160a01b03169190611765565b801561068157600e54600854610681916001600160a01b03918216911683611765565b5050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff166000811580156106cb5750825b905060008267ffffffffffffffff1660011480156106e85750303b155b9050811580156106f6575080155b156107145760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561073e57845460ff60401b1916600160401b1785555b8535601c556020860135601d5560408601356000556060860135600155608086013560025560a086013560035560c086013560045560e0860135600555610100860135600655610120860135600755610140860135601e556107a8610180870161016088016122cf565b600880546001600160a01b0319166001600160a01b03929092169190911790556107da6101a0870161018088016122cf565b600980546001600160a01b0319166001600160a01b039290921691909117905561080c6101c087016101a088016122cf565b600a80546001600160a01b0319166001600160a01b039290921691909117905561083e6101e087016101c088016122cf565b600b80546001600160a01b0319166001600160a01b039290921691909117905542601f819055610870908735906126f6565b60208181556108839190880135906126f6565b6010819055610897906040880135906126f6565b60118190556108ab906060880135906126f6565b60125560608601356080870135116108c8576012546013556108de565b85608001356011546108da91906126f6565b6013555b6013546014556108ed866117c4565b600b5460405163970559cf60e01b81526d2622a3a4a7a72fa127aaa721a2a960911b60048201526001600160a01b039091169063970559cf90602401602060405180830381865afa158015610946573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061096a9190612677565b600c80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b81526c2622a3a4a7a72fa9a4a3a722a960991b600482015291169063970559cf90602401602060405180830381865afa1580156109d5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109f99190612677565b600d80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b8152722622a3a4a7a72fa322a2afa922a1a2a4ab22a960691b600482015291169063970559cf90602401602060405180830381865afa158015610a6a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a8e9190612677565b600e80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b8152754c4547494f4e5f56455354494e475f464143544f525960501b600482015291169063970559cf90602401602060405180830381865afa158015610b02573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b269190612677565b600f80546001600160a01b0319166001600160a01b03929092169190911790558315610b8c57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b505050505050565b600c546001600160a01b03163314610bbf5760405163abdc864160e01b815260040160405180910390fd5b610bc76116cc565b610bcf61197a565b610bd761199d565b60198190556040518181527f1d05456b2ffc08dcb82751ae9e81ca9abf41f6579406fa5f5b9939abbb51cf7f9060200160405180910390a150565b600c546001600160a01b03163314610c3d5760405163abdc864160e01b815260040160405180910390fd5b610c456116cc565b610c4d6116a7565b610c556119cd565b60188390556016829055610c6a81600a6127ed565b601e54610c7790846126aa565b610c8191906126c1565b60175560408051848152602081018490527f86f76a0050decd53ce203c8e8294aa73d2f1f21363a5551d08325fa564f361e6910160405180910390a1505050565b600a546001600160a01b03163314610ced5760405163424e3f9b60e01b815260040160405180910390fd5b6009546001600160a01b0316610d1657604051632c7efdd160e21b815260040160405180910390fd5b610d1f826119f4565b610d276116cc565b610d2f611a3c565b601a805461ff00191661010017905560065461271090610d509084906126aa565b610d5a91906126c1565b8114610d785760405162a4671960e71b815260040160405180910390fd5b60408051838152602081018390527f8fb31ceaccebf6ba3c9c15e8959a4b82e39bf26a144aa885ae5e82a1d1b9c16c910160405180910390a1600954610dc9906001600160a01b0316333085611a65565b801561068157600e54600954610681916001600160a01b039182169133911684611a65565b610e8b604051806101e00160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160006001600160a01b0316815260200160006001600160a01b0316815260200160006001600160a01b0316815260200160006001600160a01b031681525090565b50604080516101e081018252601c548152601d546020820152600054918101919091526001546060820152600254608082015260035460a082015260045460c082015260055460e0820152600654610100820152600754610120820152601e546101408201526008546001600160a01b039081166101608301526009548116610180830152600a5481166101a0830152600b54166101c082015290565b6009546001600160a01b0316610f5157604051632c7efdd160e21b815260040160405180910390fd5b336000908152601b602090815260409182902082516080810184528154815260019091015460ff80821615159383019390935261010081049092161515928101929092526201000090046001600160a01b031660608201819052610fc857604051638474420160e01b815260040160405180910390fd5b6060810151600954604051631916558760e01b81526001600160a01b039182166004820152911690631916558790602401600060405180830381600087803b15801561101357600080fd5b505af1158015611027573d6000803e3d6000fd5b5050505050565b611036611a9e565b336000908152601b6020526040812054908190036110675760405163843ce46b60e01b815260040160405180910390fd5b336000908152601b602052604081208190556015805483929061108b9084906126e3565b9091555050604080518281523360208201527f3807f78213e07f1e91138875c27db2a63adf27577192e6d8617910fb3b755b1391015b60405180910390a16008546110e0906001600160a01b03163383611765565b50565b6110eb611ac1565b6110f36116cc565b6009546001600160a01b0316156111115761110c611a3c565b611119565b611119611ae4565b601a805460ff191660011790556040517f0943552b21b3bcfb11bcb560653f2703faf49c76ac2a791e285b130c0117678a90600090a1565b61115961197a565b6111616116cc565b61116d33848484611b05565b336000908152601b60205260409020600101805461ff001916610100179055821561121e57336000908152601b6020526040812080548592906111b19084906126e3565b9250508190555082601560008282546111ca91906126e3565b9091555050604080518481523360208201527f4a475b512b2940a96ef545685fe93076a8d71b278f57c3206f204dc7e9049acc910160405180910390a160085461121e906001600160a01b03163385611765565b505050565b61122b611c64565b6112336116cc565b61123b61197a565b336000908152601b60205260408120549081900361126c576040516316365d5f60e01b815260040160405180910390fd5b336000908152601b60205260408120819055601580548392906112909084906126e3565b9091555050604080518281523360208201527f68537ca51c1b2cb464f6b47b5ab5fed672fd221e6745c3784c21d1cf127693b691016110c1565b600c546001600160a01b031633146112f55760405163abdc864160e01b815260040160405180910390fd5b604080516001600160a01b038086168252841660208201529081018290527ff24ef89f38eadc1bde50701ad6e4d6d11a2dc24f7cf834a486991f38833285049060600160405180910390a161121e6001600160a01b0383168483611765565b600a546001600160a01b0316331461137f5760405163424e3f9b60e01b815260040160405180910390fd5b611387611ae4565b6111196116cc565b6009546001600160a01b03166113b857604051632c7efdd160e21b815260040160405180910390fd5b6113c06116f0565b6113cc33848484611c86565b6113d46116cc565b6113dc611ac1565b336000908152601b602052604090206001908101805460ff19169091179055821561121e57600061141533601454600354600454611db8565b604080518681523360208201526001600160a01b0383168183015290519192507f4a05d5cbbd2a218b1587ca6133e262548c26dc0596c2178e5bac5812b1f9a610919081900360600190a1336000908152601b6020526040902060010180546001600160a01b03808416620100000262010000600160b01b0319909216919091179091556009546114a891168286611765565b50505050565b6114b781611e52565b6114bf611f12565b6114c7611f43565b6114cf6116cc565b6114d882611f65565b81601560008282546114ea91906126f6565b9091555050336000908152601b60205260408120805484929061150e9084906126f6565b9091555050602054600090421060408051858152336020820152821515918101919091524260608201529091507f42dc9c05c6880bfa823f19361e04c707f8c5a03bb7197ba9d9737f5a5624d7dc9060800160405180910390a160085461121e906001600160a01b0316333086611a65565b611605604051806101e001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008019168152602001600080191681526020016000151581526020016000151581526020016000151581525090565b50604080516101e081018252601f5481526020805490820152601054918101919091526011546060820152601254608082015260135460a082015260145460c082015260155460e082015260165461010080830191909152601754610120830152601854610140830152601954610160830152601a5460ff8082161515610180850152918104821615156101a08401526201000090041615156101c082015290565b6012544210156116ca57604051630aabc7c160e11b815260040160405180910390fd5b565b601a5460ff16156116ca57604051638019358960e01b815260040160405180910390fd5b6016546000036116ca57604051630efd8e0d60e21b815260040160405180910390fd5b601a5462010000900460ff16156116ca5760405163431ecacf60e11b815260040160405180910390fd5b601a54610100900460ff166116ca57604051630479472b60e51b815260040160405180910390fd5b6040516001600160a01b0383811660248301526044820183905261121e91859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611f8b565b60006117d8610180830161016084016122cf565b6001600160a01b03161480611807575060006117fc6101c083016101a084016122cf565b6001600160a01b0316145b8061182c575060006118216101e083016101c084016122cf565b6001600160a01b0316145b1561184a57604051638474420160e01b815260040160405180910390fd5b8035158061185a57506020810135155b8061186757506040810135155b8061187457506060810135155b8061188157506080810135155b8061188f5750610140810135155b156118ad5760405163ad3e811360e01b815260040160405180910390fd5b6276a700813511806118c55750621275008160200135115b806118d657506276a7008160400135115b806118e75750621275008160600135115b806118f8575062f0c8a08160800135115b1561191657604051630373c09360e51b815260040160405180910390fd5b610e108135108061192c5750610e108160200135105b8061193c5750610e108160400135105b8061194c5750610e108160600135105b8061195c5750610e108160800135105b156110e057604051630373c09360e51b815260040160405180910390fd5b6011544210156116ca576040516313365f7760e01b815260040160405180910390fd5b601954156116ca57601954604051630ce9692f60e41b81526004016119c491815260200190565b60405180910390fd5b601654156116ca57601654604051632d459d4360e01b81526004016119c491815260200190565b601654600003611a17576040516324f7856360e01b815260040160405180910390fd5b60165481146110e05760405163fda813a360e01b8152600481018290526024016119c4565b601a54610100900460ff16156116ca576040516323e6655160e11b815260040160405180910390fd5b6040516001600160a01b0384811660248301528381166044830152606482018390526114a89186918216906323b872dd90608401611792565b601a5460ff166116ca57604051639903ed3760e01b815260040160405180910390fd5b6013544210156116ca57604051631a7fddef60e01b815260040160405180910390fd5b601654156116ca57604051630a1bb29160e01b815260040160405180910390fd5b604080516001600160a01b038616602082015290810184905260009060600160408051601f198184030181528282528051602091820120908301520160408051601f1981840301815282825280516020918201206001600160a01b03808a166000908152601b8452849020608086018552805486526001015460ff80821615158786015261010082041615158686015262010000900416606085015282518683028181018401909452868152909450611be192909187918791829190850190849080828437600092019190915250506019549150859050611ffc565b611c0957604051638b68cb5760e01b81526001600160a01b03871660048201526024016119c4565b806040015115611c3757604051633b8936cf60e11b81526001600160a01b03871660048201526024016119c4565b8051600003610b8c5760405163f224fc4960e01b81526001600160a01b03871660048201526024016119c4565b60125442106116ca57604051632a65994560e21b815260040160405180910390fd5b604080516001600160a01b038616602082015290810184905260009060600160408051601f198184030181528282528051602091820120908301520160408051601f1981840301815282825280516020918201206001600160a01b03808a166000908152601b8452849020608086018552805486526001015460ff80821615158786015261010082041615158686015262010000900416606085015282518683028181018401909452868152909450611d6292909187918791829190850190849080828437600092019190915250506018549150859050611ffc565b611d8a576040516375774fbf60e11b81526001600160a01b03871660048201526024016119c4565b806020015115611c3757604051634f051ead60e11b81526001600160a01b03871660048201526024016119c4565b600f54604051636ddc243d60e01b81526001600160a01b03868116600483015267ffffffffffffffff80871660248401528086166044840152841660648301526000921690636ddc243d906084016020604051808303816000875af1158015611e25573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e499190612677565b95945050505050565b6040516bffffffffffffffffffffffff1933606090811b8216602084015230901b166034820152466048820152600090611ed290606801604051602081830303815290604052805190602001207f19457468657265756d205369676e6564204d6573736167653a0a3332000000006000908152601c91909152603c902090565b600d549091506001600160a01b0316611eeb8284612012565b6001600160a01b03161461068157604051638baa579f60e01b815260040160405180910390fd5b6020544210158015611f25575060105442105b156116ca5760405163043f49dd60e11b815260040160405180910390fd5b60115442106116ca57604051634298ddab60e11b815260040160405180910390fd5b6007548110156110e0576040516328c3d6d560e01b8152600481018290526024016119c4565b600080602060008451602086016000885af180611fae576040513d6000823e3d81fd5b50506000513d91508115611fc6578060011415611fd3565b6001600160a01b0384163b155b156114a857604051635274afe760e01b81526001600160a01b03851660048201526024016119c4565b600082612009858461203e565b14949350505050565b6000806000806120228686612081565b92509250925061203282826120ce565b50909150505b92915050565b600081815b84518110156120795761206f82868381518110612062576120626127fc565b6020026020010151612187565b9150600101612043565b509392505050565b600080600083516041036120bb5760208401516040850151606086015160001a6120ad888285856121b9565b9550955095505050506120c7565b50508151600091506002905b9250925092565b60008260038111156120e2576120e2612812565b036120eb575050565b60018260038111156120ff576120ff612812565b0361211d5760405163f645eedf60e01b815260040160405180910390fd5b600282600381111561213157612131612812565b036121525760405163fce698f760e01b8152600481018290526024016119c4565b600382600381111561216657612166612812565b03610681576040516335e2f38360e21b8152600481018290526024016119c4565b60008183106121a35760008281526020849052604090206121b2565b60008381526020839052604090205b9392505050565b600080807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411156121f4575060009150600390508261227e565b604080516000808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015612248573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166122745750600092506001915082905061227e565b9250600091508190505b9450945094915050565b60006101e0828403121561229b57600080fd5b50919050565b6000602082840312156122b357600080fd5b5035919050565b6001600160a01b03811681146110e057600080fd5b6000602082840312156122e157600080fd5b81356121b2816122ba565b60008060006060848603121561230157600080fd5b8335925060208401359150604084013560ff8116811461232057600080fd5b809150509250925092565b6000806040838503121561233e57600080fd5b50508035926020909101359150565b60006101e082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015160e0830152610100808401518184015250610120808401518184015250610140808401518184015250610160808401516123df828501826001600160a01b03169052565b5050610180838101516001600160a01b0381168483015250506101a0838101516001600160a01b0381168483015250506101c0838101516001600160a01b038116848301525b505092915050565b60008060006040848603121561244257600080fd5b83359250602084013567ffffffffffffffff8082111561246157600080fd5b818601915086601f83011261247557600080fd5b81358181111561248457600080fd5b8760208260051b850101111561249957600080fd5b6020830194508093505050509250925092565b6000806000606084860312156124c157600080fd5b83356124cc816122ba565b925060208401356124dc816122ba565b929592945050506040919091013590565b634e487b7160e01b600052604160045260246000fd5b6000806040838503121561251657600080fd5b82359150602083013567ffffffffffffffff8082111561253557600080fd5b818501915085601f83011261254957600080fd5b81358181111561255b5761255b6124ed565b604051601f8201601f19908116603f01168101908382118183101715612583576125836124ed565b8160405282815288602084870101111561259c57600080fd5b8260208601602083013760006020848301015280955050505050509250929050565b60006101e082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015160e0830152610100808401518184015250610120808401518184015250610140808401518184015250610160808401518184015250610180808401516126558285018215159052565b50506101a0838101511515908301526101c08084015180151582850152612425565b60006020828403121561268957600080fd5b81516121b2816122ba565b634e487b7160e01b600052601160045260246000fd5b808202811582820484141761203857612038612694565b6000826126de57634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561203857612038612694565b8082018082111561203857612038612694565b600181815b8085111561274457816000190482111561272a5761272a612694565b8085161561273757918102915b93841c939080029061270e565b509250929050565b60008261275b57506001612038565b8161276857506000612038565b816001811461277e5760028114612788576127a4565b6001915050612038565b60ff84111561279957612799612694565b50506001821b612038565b5060208310610133831016604e8410600b84101617156127c7575081810a612038565b6127d18383612709565b80600019048211156127e5576127e5612694565b029392505050565b60006121b260ff84168361274c565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052602160045260246000fdfea2646970667358221220ab0c144cb349325a3d41f52732cfef93297d2384432d6d2aadc469e70d7d3ad664736f6c634300081900336080604052348015600f57600080fd5b506016601a565b60ca565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff161560695760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b039081161460c75780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b6123d3806100d96000396000f3fe608060405234801561001057600080fd5b50600436106101215760003560e01c8063b19164d0116100ad578063e63ea40811610071578063e63ea408146102a1578063e7e10490146102b4578063f37bfe74146102bc578063f9020e33146102cf578063fb408d31146102e457600080fd5b8063b19164d014610258578063c366eff81461026b578063c5e9339f14610273578063c684e70a14610286578063e5ccd91b1461029957600080fd5b8063590e1ae3116100f4578063590e1ae3146101ff578063689513a01461020757806390aa0b0f146102285780639eaeba171461023d578063a96f86681461025057600080fd5b80630a636d5b146101265780634e474163146101305780634e9148a6146101435780635111e98614610156575b600080fd5b61012e6102f7565b005b61012e61013e366004612008565b610535565b61012e610151366004612087565b61064a565b6101b46101643660046120c2565b6014602052600090815260409020805460018201546002830154600384015460048501546005860154600690960154949593949293919290919060ff81169061010090046001600160a01b031688565b604080519889526020890197909752958701949094526060860192909252608085015260a0840152151560c08301526001600160a01b031660e0820152610100015b60405180910390f35b61012e61071c565b61021a6102153660046120df565b6107cf565b6040519081526020016101f6565b6102306109bb565b6040516101f69190612121565b61012e61024b3660046121ba565b610a9d565b61012e610e54565b61012e610266366004612008565b610f4e565b61012e61103e565b61012e6102813660046121d3565b6110f2565b61012e6102943660046121ec565b611168565b61012e611262565b61012e6102af36600461220e565b6112ef565b61012e61137e565b61012e6102ca36600461224f565b611415565b6102d76114ad565b6040516101f6919061227b565b61012e6102f23660046120df565b61157e565b600a546001600160a01b031633146103225760405163abdc864160e01b815260040160405180910390fd5b60095460405163970559cf60e01b81526d2622a3a4a7a72fa127aaa721a2a960911b60048201526001600160a01b039091169063970559cf90602401602060405180830381865afa15801561037b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061039f91906122f5565b600a80546001600160a01b0319166001600160a01b0392831617905560095460405163970559cf60e01b8152722622a3a4a7a72fa322a2afa922a1a2a4ab22a960691b600482015291169063970559cf90602401602060405180830381865afa158015610410573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061043491906122f5565b600b80546001600160a01b0319166001600160a01b0392831617905560095460405163970559cf60e01b8152754c4547494f4e5f56455354494e475f464143544f525960501b600482015291169063970559cf90602401602060405180830381865afa1580156104a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104cc91906122f5565b600c80546001600160a01b0319166001600160a01b03928316908117909155600a54600b5460408051928516835293166020820152918201527f6e5a74eba2ea936201a18b6c7bd3bfd535da26cae809dcb81bb4bdc399b332a9906060015b60405180910390a1565b61053d6116db565b610545611701565b3360009081526014602052604081206010805491928992610567908490612328565b9091555050805487908290600090610580908490612328565b90915550506002810154600003610598574260028201555b858160030154146105ab57600381018690555b848160040154146105be57600481018590555b838160050154146105d157600581018490555b6105dc338484611729565b60408051888152336020820152908101869052606081018590524260808201527f1a67a76a9e304ee20506c8fcce419857970b8af84bc88f250510f3042caad1d69060a00160405180910390a1600754610641906001600160a01b031633308a61189c565b50505050505050565b600a546001600160a01b031633146106755760405163abdc864160e01b815260040160405180910390fd5b61067d6116db565b600d80546001600160a01b0319166001600160a01b038616179055600f839055600e829055601181905560135462010000900460ff16156106c5576013805462ff0000191690555b604080516001600160a01b038616815260208101859052908101839052606081018290527f0d1e7d410b8c1f5458a5aed9b93922c886b6cba9e90562aefd5eebd46fb00c5d9060800160405180910390a150505050565b6107246116db565b61072d33611909565b33600090815260146020526040812080549091819003610760576040516316365d5f60e01b815260040160405180910390fd5b60008083556010805483929061077790849061233b565b9091555050604080518281523360208201527f68537ca51c1b2cb464f6b47b5ab5fed672fd221e6745c3784c21d1cf127693b6910160405180910390a16007546107cb906001600160a01b031633836119b3565b5050565b6008546000906001600160a01b031633146107fd5760405163424e3f9b60e01b815260040160405180910390fd5b6108056116db565b60005b828110156108fe5761083f8484838181106108255761082561234e565b905060200201602081019061083a91906120c2565b6119e4565b61086e8484838181106108545761085461234e565b905060200201602081019061086991906120c2565b611a8d565b6000601460008686858181106108865761088661234e565b905060200201602081019061089b91906120c2565b6001600160a01b0316815260208101919091526040016000908120600181015481549193506108c99161233b565b9050808260010160008282546108df9190612328565b909155506108ef90508185612328565b93505050806001019050610808565b5080601260008282546109119190612328565b9250508190555060006127108260045461092b9190612364565b610935919061237b565b90507f3ae35a082057a5be9e6d5f35595c7af95c80661ebf74fdbb3790f6ef55c75e4f8260405161096891815260200190565b60405180910390a16109913361097e838561233b565b6007546001600160a01b031691906119b3565b80156109b457600b546007546109b4916001600160a01b039182169116836119b3565b5092915050565b610a2f6040518061014001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000801916815260200160006001600160a01b0316815260200160006001600160a01b0316815260200160006001600160a01b031681525090565b50604080516101408101825260005481526001546020820152600254918101919091526003546060820152600454608082015260055460a082015260065460c08201526007546001600160a01b0390811660e083015260085481166101008301526009541661012082015290565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff16600081158015610ae35750825b905060008267ffffffffffffffff166001148015610b005750303b155b905081158015610b0e575080155b15610b2c5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315610b5657845460ff60401b1916600160401b1785555b8535600055602086013560015560408601356002556060860135600355608086013560045560a086013560055560c0860135600655610b9c610100870160e088016120c2565b600780546001600160a01b0319166001600160a01b0392909216919091179055610bce610120870161010088016120c2565b600880546001600160a01b0319166001600160a01b0392909216919091179055610c00610140870161012088016120c2565b600980546001600160a01b03929092166001600160a01b03199092169190911790556013805462ff0000191662010000179055610c3c86611b65565b60095460405163970559cf60e01b81526d2622a3a4a7a72fa127aaa721a2a960911b60048201526001600160a01b039091169063970559cf90602401602060405180830381865afa158015610c95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cb991906122f5565b600a80546001600160a01b0319166001600160a01b0392831617905560095460405163970559cf60e01b8152722622a3a4a7a72fa322a2afa922a1a2a4ab22a960691b600482015291169063970559cf90602401602060405180830381865afa158015610d2a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d4e91906122f5565b600b80546001600160a01b0319166001600160a01b0392831617905560095460405163970559cf60e01b8152754c4547494f4e5f56455354494e475f464143544f525960501b600482015291169063970559cf90602401602060405180830381865afa158015610dc2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610de691906122f5565b600c80546001600160a01b0319166001600160a01b03929092169190911790558315610e4c57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b505050505050565b3360009081526014602090815260409182902082516101008082018552825482526001830154938201939093526002820154938101939093526003810154606084015260048101546080840152600581015460a08401526006015460ff8116151560c0840152046001600160a01b031660e08201819052610ee857604051638474420160e01b815260040160405180910390fd5b60e0810151600d54604051631916558760e01b81526001600160a01b039182166004820152911690631916558790602401600060405180830381600087803b158015610f3357600080fd5b505af1158015610f47573d6000803e3d6000fd5b5050505050565b610f566116db565b3360009081526014602052604081206010805491928992610f7890849061233b565b9091555050805487908290600090610f9190849061233b565b909155505060038101548614610fa957600381018690555b84816004015414610fbc57600481018590555b83816005015414610fcf57600581018490555b610fda338484611729565b60408051888152336020820152908101869052606081018590524260808201527fd84decea969f0c829ea42947cd8c6f90667f2eb8458cf4a499c0f1d4983950439060a00160405180910390a1600754610641906001600160a01b031633896119b3565b611046611c31565b33600090815260146020526040812054908190036110775760405163843ce46b60e01b815260040160405180910390fd5b3360009081526014602052604081208190556010805483929061109b90849061233b565b9091555050604080518281523360208201527f3807f78213e07f1e91138875c27db2a63adf27577192e6d8617910fb3b755b13910160405180910390a16007546110ef906001600160a01b031633836119b3565b50565b600a546001600160a01b0316331461111d5760405163abdc864160e01b815260040160405180910390fd5b6111256116db565b61112d611c54565b60068190556040518181527fac6ccaebceb7db9d2c79237384a321e39219912d1cbb6a95c09ae874c6ca4a8d9060200160405180910390a150565b6008546001600160a01b031633146111935760405163424e3f9b60e01b815260040160405180910390fd5b61119b6116db565b6111a482611c75565b612710826005546111b59190612364565b6111bf919061237b565b81146111dd5760405162a4671960e71b815260040160405180910390fd5b6013805461ff00191661010017905560408051838152602081018390527f8fb31ceaccebf6ba3c9c15e8959a4b82e39bf26a144aa885ae5e82a1d1b9c16c910160405180910390a1600d5461123d906001600160a01b031633308561189c565b80156107cb57600b54600d546107cb916001600160a01b03918216913391168461189c565b6008546001600160a01b0316331461128d5760405163424e3f9b60e01b815260040160405180910390fd5b611295611c54565b6013805460ff62010000808304821615810262ff00001990931692909217928390556040517f45feb7652572c788bb34f6d73371acf0a76228b5f94a6267ab079c67448ee6629361052b9390049091161515815260200190565b600a546001600160a01b0316331461131a5760405163abdc864160e01b815260040160405180910390fd5b604080516001600160a01b038086168252841660208201529081018290527ff24ef89f38eadc1bde50701ad6e4d6d11a2dc24f7cf834a486991f38833285049060600160405180910390a16113796001600160a01b03831684836119b3565b505050565b6008546001600160a01b031633146113a95760405163424e3f9b60e01b815260040160405180910390fd5b6113b16116db565b6113b9611ce6565b6012546013805460ff191660011790556040517f0943552b21b3bcfb11bcb560653f2703faf49c76ac2a791e285b130c0117678a90600090a180156110ef5760006012556007546110ef906001600160a01b031633308461189c565b6008546001600160a01b031633146114405760405163424e3f9b60e01b815260040160405180910390fd5b6114486116db565b611450611d0f565b611458611c54565b60018390556002829055600381905560408051848152602081018490529081018290527f58e28d925e2c26857c5c2ca9745e16c543063e7a0cfe5eb61045cce9a465466b9060600160405180910390a1505050565b61150b60405180610120016040528060006001600160a01b0316815260200160008152602001600081526020016000815260200160008152602001600081526020016000151581526020016000151581526020016000151581525090565b506040805161012081018252600d546001600160a01b03168152600e546020820152600f54918101919091526010546060820152601154608082015260125460a082015260135460ff808216151560c08401526101008083048216151560e0850152620100009092041615159082015290565b6115866116db565b61158f33611d30565b61159a338383611729565b3360009081526014602052604081206004810154600f54919291670de0b6b3a7640000916115c791612364565b6115d1919061237b565b90506000670de0b6b3a7640000600354836115ec9190612364565b6115f6919061237b565b90506000611604828461233b565b9050600061161a33600e54600154600254611e24565b60068601805460ff196001600160a01b03841661010002166001600160a81b03199091161760011790556040519091507ff923792c0048215a0ec9c4a916271549f6ef7be7caddd9438ea7edfef2e6e38a9061169f90849086903390869093845260208401929092526001600160a01b03908116604084015216606082015260800190565b60405180910390a1600d546116be906001600160a01b031682846119b3565b821561064157600d54610641906001600160a01b031633856119b3565b60135460ff16156116ff57604051638019358960e01b815260040160405180910390fd5b565b60135462010000900460ff166116ff57604051625abecd60e71b815260040160405180910390fd5b6001600160a01b03838116600081815260146020908152604080832081516101008082018452825482526001830154828601526002830154828501526003830154606080840182905260048501546080808601829052600587015460a080880182905260069098015460ff8116151560c089015295909504909b1660e0860152865197880199909952948601529284019590955294820152919290910160408051601f198184030181528282528051602091820120908301520160405160208183030381529060405280519060200120905081606001518260000151146118335760405163f64afe6960e01b81526001600160a01b03861660048201526024015b60405180910390fd5b611874848480806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250506006549150849050611ebe565b610f4757604051639a06a13f60e01b81526001600160a01b038616600482015260240161182a565b6040516001600160a01b0384811660248301528381166044830152606482018390526119039186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611ed4565b50505050565b6001600160a01b038082166000908152601460209081526040808320815161010080820184528254825260018301549482019490945260028201549281018390526003820154606082015260048201546080820152600582015460a082015260069091015460ff8116151560c08301529290920490931660e0820152905490916119939190612328565b4211156107cb57604051632a65994560e21b815260040160405180910390fd5b6040516001600160a01b0383811660248301526044820183905261137991859182169063a9059cbb906064016118d1565b6001600160a01b038082166000908152601460209081526040808320815161010080820184528254825260018301549482019490945260028201549281018390526003820154606082015260048201546080820152600582015460a082015260069091015460ff8116151560c08301529290920490931660e082015290549091611a6e9190612328565b42116107cb57604051630aabc7c160e11b815260040160405180910390fd5b6001600160a01b0380821660009081526014602090815260408083208151610100808201845282548083526001840154958301959095526002830154938201939093526003820154606082015260048201546080820152600582015460a082015260069091015460ff8116151560c08301529190910490931660e08401529003611b3557604051633177dde360e21b81526001600160a01b038316600482015260240161182a565b80516020820151036107cb576040516392f1dcf760e01b81526001600160a01b038316600482015260240161182a565b6000611b78610100830160e084016120c2565b6001600160a01b03161480611ba757506000611b9c610120830161010084016120c2565b6001600160a01b0316145b80611bcc57506000611bc1610140830161012084016120c2565b6001600160a01b0316145b15611bea57604051638474420160e01b815260040160405180910390fd5b8035600003611c0c5760405163ad3e811360e01b815260040160405180910390fd5b62127500813511156110ef57604051630373c09360e51b815260040160405180910390fd5b60135460ff166116ff57604051639903ed3760e01b815260040160405180910390fd5b601154156116ff57604051632801533160e21b815260040160405180910390fd5b601154600003611c98576040516324f7856360e01b815260040160405180910390fd5b601354610100900460ff1615611cc1576040516323e6655160e11b815260040160405180910390fd5b60115481146110ef5760405163fda813a360e01b81526004810182905260240161182a565b601354610100900460ff16156116ff576040516323e6655160e11b815260040160405180910390fd5b601254156116ff57604051638aada42160e01b815260040160405180910390fd5b6001600160a01b0380821660009081526014602090815260409182902082516101008082018552825482526001830154938201939093526002820154938101939093526003810154606084015260048101546080840152600581015460a08401526006015460ff808216151560c08501529082900490931660e08301526013549192910416611dd25760405163130f6b4360e31b815260040160405180910390fd5b8060c0015115611e0057604051634f051ead60e11b81526001600160a01b038316600482015260240161182a565b80516000036107cb57604051633177dde360e21b815233600482015260240161182a565b600c54604051636ddc243d60e01b81526001600160a01b03868116600483015267ffffffffffffffff80871660248401528086166044840152841660648301526000921690636ddc243d906084016020604051808303816000875af1158015611e91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eb591906122f5565b95945050505050565b600082611ecb8584611f45565b14949350505050565b600080602060008451602086016000885af180611ef7576040513d6000823e3d81fd5b50506000513d91508115611f0f578060011415611f1c565b6001600160a01b0384163b155b1561190357604051635274afe760e01b81526001600160a01b038516600482015260240161182a565b600081815b8451811015611f8057611f7682868381518110611f6957611f6961234e565b6020026020010151611f8a565b9150600101611f4a565b5090505b92915050565b6000818310611fa6576000828152602084905260409020611fb5565b60008381526020839052604090205b9392505050565b60008083601f840112611fce57600080fd5b50813567ffffffffffffffff811115611fe657600080fd5b6020830191508360208260051b850101111561200157600080fd5b9250929050565b60008060008060008060a0878903121561202157600080fd5b86359550602087013594506040870135935060608701359250608087013567ffffffffffffffff81111561205457600080fd5b61206089828a01611fbc565b979a9699509497509295939492505050565b6001600160a01b03811681146110ef57600080fd5b6000806000806080858703121561209d57600080fd5b84356120a881612072565b966020860135965060408601359560600135945092505050565b6000602082840312156120d457600080fd5b8135611fb581612072565b600080602083850312156120f257600080fd5b823567ffffffffffffffff81111561210957600080fd5b61211585828601611fbc565b90969095509350505050565b600061014082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015161218460e08401826001600160a01b03169052565b50610100838101516001600160a01b038116848301525050610120838101516001600160a01b038116848301525b505092915050565b600061014082840312156121cd57600080fd5b50919050565b6000602082840312156121e557600080fd5b5035919050565b600080604083850312156121ff57600080fd5b50508035926020909101359150565b60008060006060848603121561222357600080fd5b833561222e81612072565b9250602084013561223e81612072565b929592945050506040919091013590565b60008060006060848603121561226457600080fd5b505081359360208301359350604090920135919050565b60006101208201905060018060a01b0383511682526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c0830151151560c083015260e08301516122e160e084018215159052565b5061010083810151801515848301526121b2565b60006020828403121561230757600080fd5b8151611fb581612072565b634e487b7160e01b600052601160045260246000fd5b80820180821115611f8457611f84612312565b81810381811115611f8457611f84612312565b634e487b7160e01b600052603260045260246000fd5b8082028115828204841417611f8457611f84612312565b60008261239857634e487b7160e01b600052601260045260246000fd5b50049056fea26469706673582212203eb56096f9dbdf71dbb86b9715e2fdc361a8ced76335af19b6a2960cb5cc92db64736f6c634300081900336080604052348015600f57600080fd5b506016601a565b60ca565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff161560695760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b039081161460c75780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b612cb8806100d96000396000f3fe608060405234801561001057600080fd5b506004361061012c5760003560e01c8063a96f8668116100ad578063d5cef13311610071578063d5cef13314610284578063e63ea4081461028c578063e7e104901461029f578063e8d21453146102a7578063f9020e33146102ba57600080fd5b8063a96f866814610246578063ada14d771461024e578063b14d8bd514610256578063bcb520bd1461025e578063c043586a1461027157600080fd5b8063335759f0116100f4578063335759f01461018457806349bfdafd146101975780635111e986146101aa57806389bd62651461021e57806390dbb8061461023157600080fd5b80630a636d5b1461013157806311c0dcaa1461013b57806317727a0014610161578063245b5e6b146101695780632a8b6fae1461017c575b600080fd5b6101396102cf565b005b61014e61014936600461268e565b6105aa565b6040519081526020015b60405180910390f35b610139610653565b6101396101773660046126b0565b61076d565b610139610823565b6101396101923660046126e2565b6108a6565b6101396101a53660046126fb565b610d85565b6101ef6101b8366004612729565b601b602052600090815260409020805460019091015460ff808216916101008104909116906201000090046001600160a01b031684565b604080519485529215156020850152901515918301919091526001600160a01b03166060820152608001610158565b61013961022c36600461268e565b610e03565b610239610f2f565b604051610158919061274d565b610139610fd7565b6101396110dd565b610139611192565b61013961026c366004612830565b611200565b61013961027f3660046128ee565b6112d2565b6101396113c5565b61013961029a3660046129fb565b61146c565b6101396114f6565b6101396102b5366004612830565b611533565b6102c2611652565b6040516101589190612a3c565b600c546001600160a01b031633146102fa5760405163abdc864160e01b815260040160405180910390fd5b600b5460405163970559cf60e01b81526d2622a3a4a7a72fa127aaa721a2a960911b60048201526001600160a01b039091169063970559cf90602401602060405180830381865afa158015610353573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103779190612aea565b600c80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b81526c2622a3a4a7a72fa9a4a3a722a960991b600482015291169063970559cf90602401602060405180830381865afa1580156103e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104069190612aea565b600d80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b8152722622a3a4a7a72fa322a2afa922a1a2a4ab22a960691b600482015291169063970559cf90602401602060405180830381865afa158015610477573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061049b9190612aea565b600e80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b8152754c4547494f4e5f56455354494e475f464143544f525960501b600482015291169063970559cf90602401602060405180830381865afa15801561050f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105339190612aea565b600f80546001600160a01b0319166001600160a01b03928316908117909155600c54600d54600e5460408051938616845291851660208401529093169281019290925260608201527fbe3bfe64947d6e55482c3ff74c8fd3ddbb9bc20b6eb9c979b68567d929ebd3839060800160405180910390a1565b60006105b4611769565b601e54604051633a89a52360e01b815260048101859052601c546024820152601d54604482015260648101919091526084810183905273bf90a24f24890d8fbfbc4c34542b3ac4cebe04ab90633a89a5239060a401602060405180830381865af4158015610626573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061064a9190612b07565b90505b92915050565b600a546001600160a01b0316331461067e5760405163424e3f9b60e01b815260040160405180910390fd5b61068661178c565b61068e6117af565b6106966117d3565b61069e6117f6565b6009546001600160a01b0316156106b7576106b7611820565b601a805462ff0000191662010000179055601754600554600090612710906106e0908490612b36565b6106ea9190612b4d565b604080518481523360208201529192507f2d6f01e5411cbd4277f423f351cb310dc3488eec3993da5a4ae9276837d4b82f910160405180910390a1610746336107338385612b6f565b6008546001600160a01b03169190611848565b801561076957600e54600854610769916001600160a01b03918216911683611848565b5050565b600c546001600160a01b031633146107985760405163abdc864160e01b815260040160405180910390fd5b6107a06117af565b6107a86118a7565b6107b061178c565b6107b9816118ca565b6107c16119bd565b601884905560168390556017829055601e8190556040805185815260208101859052908101839052606081018290527f15002cf84c247aa6d0a704e65b626e112d5204efb8b2bcc20ac504b336fef5a69060800160405180910390a150505050565b600c546001600160a01b0316331461084e5760405163abdc864160e01b815260040160405180910390fd5b6108566117af565b61085e6119ed565b61086661178c565b61086e6119bd565b601f805460ff191660011790556040517f7e3cf79491a274018c7f265a2e16256849ea1679173c4b19f0fea8cb7c34a87a90600090a1565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff166000811580156108ec5750825b905060008267ffffffffffffffff1660011480156109095750303b155b905081158015610917575080155b156109355760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561095f57845460ff60401b1916600160401b1785555b8535600055602086013560015560408601356002556060860135600355608086013560045560a086013560055560c086013560065560e0860135600755610100860135601c55610120860135601d556109c061016087016101408801612729565b600880546001600160a01b0319166001600160a01b03929092169190911790556109f261018087016101608801612729565b600980546001600160a01b0319166001600160a01b0392909216919091179055610a246101a087016101808801612729565b600a80546001600160a01b0319166001600160a01b0392909216919091179055610a566101c087016101a08801612729565b600b80546001600160a01b0319166001600160a01b0392909216919091179055426010819055610a8890873590612b82565b6011819055610a9c90602088013590612b82565b6012556020860135604087013511610ab957601254601355610acf565b8560400135601154610acb9190612b82565b6013555b601354601455610ade86611a11565b600b5460405163970559cf60e01b81526d2622a3a4a7a72fa127aaa721a2a960911b60048201526001600160a01b039091169063970559cf90602401602060405180830381865afa158015610b37573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b5b9190612aea565b600c80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b81526c2622a3a4a7a72fa9a4a3a722a960991b600482015291169063970559cf90602401602060405180830381865afa158015610bc6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bea9190612aea565b600d80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b8152722622a3a4a7a72fa322a2afa922a1a2a4ab22a960691b600482015291169063970559cf90602401602060405180830381865afa158015610c5b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c7f9190612aea565b600e80546001600160a01b0319166001600160a01b03928316179055600b5460405163970559cf60e01b8152754c4547494f4e5f56455354494e475f464143544f525960501b600482015291169063970559cf90602401602060405180830381865afa158015610cf3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d179190612aea565b600f80546001600160a01b0319166001600160a01b03929092169190911790558315610d7d57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b505050505050565b600c546001600160a01b03163314610db05760405163abdc864160e01b815260040160405180910390fd5b610db86117af565b610dc0611bfd565b610dc8611c20565b60198190556040518181527f1d05456b2ffc08dcb82751ae9e81ca9abf41f6579406fa5f5b9939abbb51cf7f9060200160405180910390a150565b600a546001600160a01b03163314610e2e5760405163424e3f9b60e01b815260040160405180910390fd5b6009546001600160a01b0316610e5757604051632c7efdd160e21b815260040160405180910390fd5b610e6082611c47565b610e686117af565b610e70611c8f565b601a805461ff00191661010017905560065461271090610e91908490612b36565b610e9b9190612b4d565b8114610eb95760405162a4671960e71b815260040160405180910390fd5b60408051838152602081018390527f8fb31ceaccebf6ba3c9c15e8959a4b82e39bf26a144aa885ae5e82a1d1b9c16c910160405180910390a1600954610f0a906001600160a01b0316333085611cb8565b801561076957600e54600954610769916001600160a01b039182169133911684611cb8565b610f3761260b565b50604080516101a0810182526000548152600154602080830191909152600254828401526003546060830152600454608083015260055460a083015260065460c083015260075460e08301528251808401909352601c548352601d54908301526101008101919091526008546001600160a01b039081166101208301526009548116610140830152600a548116610160830152600b541661018082015290565b6009546001600160a01b031661100057604051632c7efdd160e21b815260040160405180910390fd5b336000908152601b602090815260409182902082516080810184528154815260019091015460ff80821615159383019390935261010081049092161515928101929092526201000090046001600160a01b03166060820181905261107757604051638474420160e01b815260040160405180910390fd5b6060810151600954604051631916558760e01b81526001600160a01b039182166004820152911690631916558790602401600060405180830381600087803b1580156110c257600080fd5b505af11580156110d6573d6000803e3d6000fd5b5050505050565b6110e5611cf1565b336000908152601b6020526040812054908190036111165760405163843ce46b60e01b815260040160405180910390fd5b336000908152601b602052604081208190556015805483929061113a908490612b6f565b9091555050604080518281523360208201527f3807f78213e07f1e91138875c27db2a63adf27577192e6d8617910fb3b755b1391015b60405180910390a160085461118f906001600160a01b03163383611848565b50565b61119a611d14565b6111a26117af565b6009546001600160a01b0316156111c0576111bb611c8f565b6111c8565b6111c8611d37565b601a805460ff191660011790556040517f0943552b21b3bcfb11bcb560653f2703faf49c76ac2a791e285b130c0117678a90600090a1565b611208611bfd565b6112106117af565b61121c33848484611d58565b336000908152601b60205260409020600101805461ff00191661010017905582156112cd57336000908152601b602052604081208054859290611260908490612b6f565b9250508190555082601560008282546112799190612b6f565b9091555050604080518481523360208201527f4a475b512b2940a96ef545685fe93076a8d71b278f57c3206f204dc7e9049acc910160405180910390a16008546112cd906001600160a01b03163385611848565b505050565b6112db81611eb7565b600080806112eb85870187612b95565b9250925092506112fa82611f77565b61130381611f97565b61130b6120a2565b6113136117af565b61131c876120c4565b866015600082825461132e9190612b82565b9091555050336000908152601b602052604081208054899290611352908490612b82565b909155505060408051888152602081018590529081018390523360608201524260808201527f9e2b3387341690ff22eba0ca100d437b6c0e24ca49e13174fb09b991b8050e469060a00160405180910390a16008546113bc906001600160a01b031633308a611cb8565b50505050505050565b6113cd6120ea565b6113d56117af565b6113dd611bfd565b336000908152601b60205260408120549081900361140e576040516316365d5f60e01b815260040160405180910390fd5b336000908152601b6020526040812081905560158054839290611432908490612b6f565b9091555050604080518281523360208201527f68537ca51c1b2cb464f6b47b5ab5fed672fd221e6745c3784c21d1cf127693b69101611170565b600c546001600160a01b031633146114975760405163abdc864160e01b815260040160405180910390fd5b604080516001600160a01b038086168252841660208201529081018290527ff24ef89f38eadc1bde50701ad6e4d6d11a2dc24f7cf834a486991f38833285049060600160405180910390a16112cd6001600160a01b0383168483611848565b600a546001600160a01b031633146115215760405163424e3f9b60e01b815260040160405180910390fd5b61152961210c565b6115316119ed565b565b6009546001600160a01b031661155c57604051632c7efdd160e21b815260040160405180910390fd5b6115646117d3565b61157033848484612147565b6115786117af565b611580611d14565b336000908152601b602052604090206001908101805460ff1916909117905582156112cd5760006115b933601454600354600454612279565b604080518681523360208201526001600160a01b0383168183015290519192507f4a05d5cbbd2a218b1587ca6133e262548c26dc0596c2178e5bac5812b1f9a610919081900360600190a1336000908152601b6020526040902060010180546001600160a01b03808416620100000262010000600160b01b03199092169190911790915560095461164c91168286611848565b50505050565b6116d0604051806101c0016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008019168152602001600080191681526020016000151581526020016000151581526020016000151581525090565b50604080516101c08101825260105481526011546020820152601254918101919091526013546060820152601454608082015260155460a082015260165460c082015260175460e0820152601e5461010080830191909152601854610120830152601954610140830152601a5460ff8082161515610160850152918104821615156101808401526201000090041615156101a082015290565b601e546000036115315760405163483d23a160e11b815260040160405180910390fd5b60125442101561153157604051630aabc7c160e11b815260040160405180910390fd5b601a5460ff161561153157604051638019358960e01b815260040160405180910390fd5b60165460000361153157604051630efd8e0d60e21b815260040160405180910390fd5b601a5462010000900460ff16156115315760405163431ecacf60e11b815260040160405180910390fd5b601a54610100900460ff1661153157604051630479472b60e51b815260040160405180910390fd5b6040516001600160a01b038381166024830152604482018390526112cd91859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050612313565b601f5460ff1661153157604051634f21a3b760e01b815260040160405180910390fd5b601e54156118eb576040516336fb475960e01b815260040160405180910390fd5b604080518082018252600181526002602082019081529151632bf48e2b60e21b815290516004820152905160248201526044810182905260009073bf90a24f24890d8fbfbc4c34542b3ac4cebe04ab9063afd238ac906064016040805180830381865af4158015611960573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119849190612beb565b601c54815191925014158061199f5750601d54602082015114155b1561076957604051635508a9c960e01b815260040160405180910390fd5b6016541561153157601654604051632d459d4360e01b81526004016119e491815260200190565b60405180910390fd5b601f5460ff1615611531576040516373b9f2c160e11b815260040160405180910390fd5b6000611a2561016083016101408401612729565b6001600160a01b03161480611a5457506000611a496101a083016101808401612729565b6001600160a01b0316145b80611a7957506000611a6e6101c083016101a08401612729565b6001600160a01b0316145b15611a9757604051638474420160e01b815260040160405180910390fd5b80351580611aa757506020810135155b80611ab457506040810135155b15611ad25760405163ad3e811360e01b815260040160405180910390fd5b604051637a5e545960e11b81526101008201356004820152610120820135602482015273bf90a24f24890d8fbfbc4c34542b3ac4cebe04ab9063f4bca8b290604401602060405180830381865af4158015611b31573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b559190612c1d565b611b7257604051637bdf9a2360e01b815260040160405180910390fd5b6276a70081351180611b8a5750621275008160200135115b80611b9b575062f0c8a08160400135115b15611bb957604051630373c09360e51b815260040160405180910390fd5b610e1081351080611bcf5750610e108160200135105b80611bdf5750610e108160400135105b1561118f57604051630373c09360e51b815260040160405180910390fd5b601154421015611531576040516313365f7760e01b815260040160405180910390fd5b6019541561153157601954604051630ce9692f60e41b81526004016119e491815260200190565b601654600003611c6a576040516324f7856360e01b815260040160405180910390fd5b601654811461118f5760405163fda813a360e01b8152600481018290526024016119e4565b601a54610100900460ff1615611531576040516323e6655160e11b815260040160405180910390fd5b6040516001600160a01b03848116602483015283811660448301526064820183905261164c9186918216906323b872dd90608401611875565b601a5460ff1661153157604051639903ed3760e01b815260040160405180910390fd5b60135442101561153157604051631a7fddef60e01b815260040160405180910390fd5b6016541561153157604051630a1bb29160e01b815260040160405180910390fd5b604080516001600160a01b038616602082015290810184905260009060600160408051601f198184030181528282528051602091820120908301520160408051601f1981840301815282825280516020918201206001600160a01b03808a166000908152601b8452849020608086018552805486526001015460ff80821615158786015261010082041615158686015262010000900416606085015282518683028181018401909452868152909450611e3492909187918791829190850190849080828437600092019190915250506019549150859050612384565b611e5c57604051638b68cb5760e01b81526001600160a01b03871660048201526024016119e4565b806040015115611e8a57604051633b8936cf60e11b81526001600160a01b03871660048201526024016119e4565b8051600003610d7d5760405163f224fc4960e01b81526001600160a01b03871660048201526024016119e4565b6040516bffffffffffffffffffffffff1933606090811b8216602084015230901b166034820152466048820152600090611f3790606801604051602081830303815290604052805190602001207f19457468657265756d205369676e6564204d6573736167653a0a3332000000006000908152601c91909152603c902090565b600d549091506001600160a01b0316611f50828461239a565b6001600160a01b03161461076957604051638baa579f60e01b815260040160405180910390fd5b33811461118f576040516381e69d9b60e01b815260040160405180910390fd5b604051637a5e545960e11b815273bf90a24f24890d8fbfbc4c34542b3ac4cebe04ab9063f4bca8b290611fce908490600401612c3f565b602060405180830381865af4158015611feb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061200f9190612c1d565b61202c57604051637bdf9a2360e01b815260040160405180910390fd5b601c54601d5460408051602081019390935282015260600160408051601f198184030181528282528051602091820120845185830151928501529183015290606001604051602081830303815290604052805190602001201461118f57604051637bdf9a2360e01b815260040160405180910390fd5b601154421061153157604051634298ddab60e11b815260040160405180910390fd5b60075481101561118f576040516328c3d6d560e01b8152600481018290526024016119e4565b601254421061153157604051632a65994560e21b815260040160405180910390fd5b600a546001600160a01b031633146121375760405163424e3f9b60e01b815260040160405180910390fd5b61213f611d37565b6111c86117af565b604080516001600160a01b038616602082015290810184905260009060600160408051601f198184030181528282528051602091820120908301520160408051601f1981840301815282825280516020918201206001600160a01b03808a166000908152601b8452849020608086018552805486526001015460ff8082161515878601526101008204161515868601526201000090041660608501528251868302818101840190945286815290945061222392909187918791829190850190849080828437600092019190915250506018549150859050612384565b61224b576040516375774fbf60e11b81526001600160a01b03871660048201526024016119e4565b806020015115611e8a57604051634f051ead60e11b81526001600160a01b03871660048201526024016119e4565b600f54604051636ddc243d60e01b81526001600160a01b03868116600483015267ffffffffffffffff80871660248401528086166044840152841660648301526000921690636ddc243d906084016020604051808303816000875af11580156122e6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061230a9190612aea565b95945050505050565b600080602060008451602086016000885af180612336576040513d6000823e3d81fd5b50506000513d9150811561234e57806001141561235b565b6001600160a01b0384163b155b1561164c57604051635274afe760e01b81526001600160a01b03851660048201526024016119e4565b60008261239185846123c4565b14949350505050565b6000806000806123aa8686612407565b9250925092506123ba8282612454565b5090949350505050565b600081815b84518110156123ff576123f5828683815181106123e8576123e8612c56565b602002602001015161250d565b91506001016123c9565b509392505050565b600080600083516041036124415760208401516040850151606086015160001a6124338882858561253c565b95509550955050505061244d565b50508151600091506002905b9250925092565b600082600381111561246857612468612c6c565b03612471575050565b600182600381111561248557612485612c6c565b036124a35760405163f645eedf60e01b815260040160405180910390fd5b60028260038111156124b7576124b7612c6c565b036124d85760405163fce698f760e01b8152600481018290526024016119e4565b60038260038111156124ec576124ec612c6c565b03610769576040516335e2f38360e21b8152600481018290526024016119e4565b600081831061252957600082815260208490526040902061064a565b600083815260208390526040902061064a565b600080807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411156125775750600091506003905082612601565b604080516000808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa1580156125cb573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166125f757506000925060019150829050612601565b9250600091508190505b9450945094915050565b604051806101a00160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200161266c604051806040016040528060008152602001600081525090565b8152600060208201819052604082018190526060820181905260809091015290565b600080604083850312156126a157600080fd5b50508035926020909101359150565b600080600080608085870312156126c657600080fd5b5050823594602084013594506040840135936060013592509050565b60006101c082840312156126f557600080fd5b50919050565b60006020828403121561270d57600080fd5b5035919050565b6001600160a01b038116811461118f57600080fd5b60006020828403121561273b57600080fd5b813561274681612714565b9392505050565b60006101c082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015160e0830152610100808401516127bd8285018280518252602090810151910152565b50506101208301516101406127dc818501836001600160a01b03169052565b84015190506101606127f8848201836001600160a01b03169052565b8401519050610180612814848201836001600160a01b03169052565b8401516001600160a01b0381166101a085015290505092915050565b60008060006040848603121561284557600080fd5b83359250602084013567ffffffffffffffff8082111561286457600080fd5b818601915086601f83011261287857600080fd5b81358181111561288757600080fd5b8760208260051b850101111561289c57600080fd5b6020830194508093505050509250925092565b634e487b7160e01b600052604160045260246000fd5b6040805190810167ffffffffffffffff811182821017156128e8576128e86128af565b60405290565b6000806000806060858703121561290457600080fd5b8435935060208086013567ffffffffffffffff8082111561292457600080fd5b818801915088601f83011261293857600080fd5b81358181111561294757600080fd5b898482850101111561295857600080fd5b91830195509093506040870135908082111561297357600080fd5b818801915088601f83011261298757600080fd5b813581811115612999576129996128af565b604051601f8201601f19908116603f011681019083821181831017156129c1576129c16128af565b816040528281528b868487010111156129d957600080fd5b8286860187830137600086848301015280965050505050505092959194509250565b600080600060608486031215612a1057600080fd5b8335612a1b81612714565b92506020840135612a2b81612714565b929592945050506040919091013590565b60006101c082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015160e083015261010080840151818401525061012080840151818401525061014080840151818401525061016080840151612ac78285018215159052565b5050610180838101511515908301526101a0928301511515929091019190915290565b600060208284031215612afc57600080fd5b815161274681612714565b600060208284031215612b1957600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b808202811582820484141761064d5761064d612b20565b600082612b6a57634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561064d5761064d612b20565b8082018082111561064d5761064d612b20565b60008060008385036080811215612bab57600080fd5b84359350602085013592506040603f1982011215612bc857600080fd5b50612bd16128c5565b604085013581526060909401356020850152509093909250565b600060408284031215612bfd57600080fd5b612c056128c5565b82518152602083015160208201528091505092915050565b600060208284031215612c2f57600080fd5b8151801515811461274657600080fd5b81518152602080830151908201526040810161064d565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052602160045260246000fdfea2646970667358221220042ee9f46a8144981ecff2d54a1cfb2f0eab4e4e841831783e929ea59535154564736f6c6343000819003300000000000000000000000075c9721a0cbba4bcfbc9905ce5592413942ae0a6

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106100935760003560e01c80638da5cb5b116100665780638da5cb5b1461011f57806392be66a414610130578063b03a465c14610157578063e4029d7b1461016a578063f2fde38b1461017d57600080fd5b80630f0846eb1461009857806318a1fa18146100c7578063715018a6146100ee5780638be135a7146100f8575b600080fd5b6100ab6100a636600461052d565b610190565b6040516001600160a01b03909116815260200160405180910390f35b6100ab7f0000000000000000000000009f0431d3573f003e1719a8c620f3cf6cc64430ce81565b6100f661026a565b005b6100ab7f0000000000000000000000002f8d0e3190b475bd0b90cf679a53938d3d5775e981565b6000546001600160a01b03166100ab565b6100ab7f0000000000000000000000000a6130d480271f0093037cac0f09160dece2c4f881565b6100ab610165366004610546565b61027e565b6100ab610178366004610559565b610321565b6100f661018b366004610588565b6103c4565b600061019a610407565b6101cc7f0000000000000000000000002f8d0e3190b475bd0b90cf679a53938d3d5775e96001600160a01b0316610434565b90507fc885257800d59db61c968e71fd418b0f13fc6856a461fe9d6a609769520f42b881836040516101ff929190610689565b60405180910390a1604051630ad7ad1d60e21b81526001600160a01b03821690632b5eb474906102339085906004016106a7565b600060405180830381600087803b15801561024d57600080fd5b505af1158015610261573d6000803e3d6000fd5b50505050919050565b610272610407565b61027c6000610447565b565b6000610288610407565b6102ba7f0000000000000000000000009f0431d3573f003e1719a8c620f3cf6cc64430ce6001600160a01b0316610434565b90507f6d58823c69470598cccd895c0db67d76a8af14a2fb8f244c91fec83d30e8cd9581836040516102ed92919061077b565b60405180910390a1604051630335759f60e41b81526001600160a01b0382169063335759f090610233908590600401610799565b600061032b610407565b61035d7f0000000000000000000000000a6130d480271f0093037cac0f09160dece2c4f86001600160a01b0316610434565b90507f19b9a3a06c9c0b07cbe0b2dfabfb3071306ffadc16ae66e12a01e0590816e1a5818360405161039092919061082b565b60405180910390a1604051639eaeba1760e01b81526001600160a01b03821690639eaeba1790610233908590600401610849565b6103cc610407565b6001600160a01b0381166103fb57604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b61040481610447565b50565b6000546001600160a01b0316331461027c5760405163118cdaa760e01b81523360048201526024016103f2565b6000610441826000610497565b92915050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6000814710156104c35760405163cf47918160e01b8152476004820152602481018390526044016103f2565b763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b176020526037600983f090506001600160a01b0381166104415760405163b06ebf3d60e01b815260040160405180910390fd5b60006101e0828403121561054057600080fd5b50919050565b60006101c0828403121561054057600080fd5b6000610140828403121561054057600080fd5b80356001600160a01b038116811461058357600080fd5b919050565b60006020828403121561059a57600080fd5b6105a38261056c565b9392505050565b803582526020810135602083015260408101356040830152606081013560608301526080810135608083015260a081013560a083015260c081013560c083015260e081013560e083015261010080820135818401525061012080820135818401525061014080820135818401525061016061062681830161056c565b6001600160a01b03169083015261018061064182820161056c565b6001600160a01b0316908301526101a061065c82820161056c565b6001600160a01b0316908301526101c061067782820161056c565b6001600160a01b031692019190915250565b6001600160a01b038316815261020081016105a360208301846105aa565b6101e0810161044182846105aa565b803582526020810135602083015260408101356040830152606081013560608301526080810135608083015260a081013560a083015260c081013560c083015260e081013560e083015261010061071b81840182840180358252602090810135910152565b5061014061072a81830161056c565b6001600160a01b03169083015261016061074582820161056c565b6001600160a01b03169083015261018061076082820161056c565b6001600160a01b0316908301526101a061067782820161056c565b6001600160a01b03831681526101e081016105a360208301846106b6565b6101c0810161044182846106b6565b803582526020810135602083015260408101356040830152606081013560608301526080810135608083015260a081013560a083015260c081013560c08301526107f460e0820161056c565b6001600160a01b031660e083015261010061081082820161056c565b6001600160a01b03169083015261012061067782820161056c565b6001600160a01b038316815261016081016105a360208301846107a8565b610140810161044182846107a856fea2646970667358221220a13bc061e1361d7808c9c5e310dcae8a9d2cf305315d1e77533669791f59c47564736f6c63430008190033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

00000000000000000000000075c9721a0cbba4bcfbc9905ce5592413942ae0a6

-----Decoded View---------------
Arg [0] : newOwner (address): 0x75C9721A0CbBA4BcFBC9905CE5592413942aE0a6

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 00000000000000000000000075c9721a0cbba4bcfbc9905ce5592413942ae0a6


Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.