Cryo Explorer Ethereum Mainnet

Address Contract Partially Verified

Address 0x61804D3B0611c9f2d47ba0eDfBecA030d89e4E09
Balance 0 ETH
Nonce 13
Code Size 2190 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

2190 bytes
0x608060405234801561001057600080fd5b50600436106100935760003560e01c80638da5cb5b116100665780638da5cb5b1461011f57806392be66a414610130578063b03a465c14610157578063e4029d7b1461016a578063f2fde38b1461017d57600080fd5b80630f0846eb1461009857806318a1fa18146100c7578063715018a6146100ee5780638be135a7146100f8575b600080fd5b6100ab6100a636600461052d565b610190565b6040516001600160a01b03909116815260200160405180910390f35b6100ab7f0000000000000000000000009f0431d3573f003e1719a8c620f3cf6cc64430ce81565b6100f661026a565b005b6100ab7f0000000000000000000000002f8d0e3190b475bd0b90cf679a53938d3d5775e981565b6000546001600160a01b03166100ab565b6100ab7f0000000000000000000000000a6130d480271f0093037cac0f09160dece2c4f881565b6100ab610165366004610546565b61027e565b6100ab610178366004610559565b610321565b6100f661018b366004610588565b6103c4565b600061019a610407565b6101cc7f0000000000000000000000002f8d0e3190b475bd0b90cf679a53938d3d5775e96001600160a01b0316610434565b90507fc885257800d59db61c968e71fd418b0f13fc6856a461fe9d6a609769520f42b881836040516101ff929190610689565b60405180910390a1604051630ad7ad1d60e21b81526001600160a01b03821690632b5eb474906102339085906004016106a7565b600060405180830381600087803b15801561024d57600080fd5b505af1158015610261573d6000803e3d6000fd5b50505050919050565b610272610407565b61027c6000610447565b565b6000610288610407565b6102ba7f0000000000000000000000009f0431d3573f003e1719a8c620f3cf6cc64430ce6001600160a01b0316610434565b90507f6d58823c69470598cccd895c0db67d76a8af14a2fb8f244c91fec83d30e8cd9581836040516102ed92919061077b565b60405180910390a1604051630335759f60e41b81526001600160a01b0382169063335759f090610233908590600401610799565b600061032b610407565b61035d7f0000000000000000000000000a6130d480271f0093037cac0f09160dece2c4f86001600160a01b0316610434565b90507f19b9a3a06c9c0b07cbe0b2dfabfb3071306ffadc16ae66e12a01e0590816e1a5818360405161039092919061082b565b60405180910390a1604051639eaeba1760e01b81526001600160a01b03821690639eaeba1790610233908590600401610849565b6103cc610407565b6001600160a01b0381166103fb57604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b61040481610447565b50565b6000546001600160a01b0316331461027c5760405163118cdaa760e01b81523360048201526024016103f2565b6000610441826000610497565b92915050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6000814710156104c35760405163cf47918160e01b8152476004820152602481018390526044016103f2565b763d602d80600a3d3981f3363d3d373d3d3d363d730000008360601b60e81c176000526e5af43d82803e903d91602b57fd5bf38360781b176020526037600983f090506001600160a01b0381166104415760405163b06ebf3d60e01b815260040160405180910390fd5b60006101e0828403121561054057600080fd5b50919050565b60006101c0828403121561054057600080fd5b6000610140828403121561054057600080fd5b80356001600160a01b038116811461058357600080fd5b919050565b60006020828403121561059a57600080fd5b6105a38261056c565b9392505050565b803582526020810135602083015260408101356040830152606081013560608301526080810135608083015260a081013560a083015260c081013560c083015260e081013560e083015261010080820135818401525061012080820135818401525061014080820135818401525061016061062681830161056c565b6001600160a01b03169083015261018061064182820161056c565b6001600160a01b0316908301526101a061065c82820161056c565b6001600160a01b0316908301526101c061067782820161056c565b6001600160a01b031692019190915250565b6001600160a01b038316815261020081016105a360208301846105aa565b6101e0810161044182846105aa565b803582526020810135602083015260408101356040830152606081013560608301526080810135608083015260a081013560a083015260c081013560c083015260e081013560e083015261010061071b81840182840180358252602090810135910152565b5061014061072a81830161056c565b6001600160a01b03169083015261016061074582820161056c565b6001600160a01b03169083015261018061076082820161056c565b6001600160a01b0316908301526101a061067782820161056c565b6001600160a01b03831681526101e081016105a360208301846106b6565b6101c0810161044182846106b6565b803582526020810135602083015260408101356040830152606081013560608301526080810135608083015260a081013560a083015260c081013560c08301526107f460e0820161056c565b6001600160a01b031660e083015261010061081082820161056c565b6001600160a01b03169083015261012061067782820161056c565b6001600160a01b038316815261016081016105a360208301846107a8565b610140810161044182846107a856fea2646970667358221220a13bc061e1361d7808c9c5e310dcae8a9d2cf305315d1e77533669791f59c47564736f6c63430008190033

Verified Source Code Partial Match

Compiler: v0.8.25+commit.b61c2a91 EVM: paris Optimization: Yes (200 runs)
LegionSaleFactory.sol 101 lines
// 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);
    }
}
Clones.sol 121 lines
// 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));
    }
}
Ownable.sol 100 lines
// 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);
    }
}
ILegionSaleFactory.sol 80 lines
// 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);
}
LegionFixedPriceSale.sol 267 lines
// 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();
    }
}
LegionPreLiquidSale.sol 831 lines
// 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);
    }
}
LegionSealedBidAuction.sol 358 lines
// 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();
    }
}
Errors.sol 34 lines
// 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);
}
Context.sol 28 lines
// 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;
    }
}
ILegionFixedPriceSale.sol 144 lines
// 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);
}
ILegionPreLiquidSale.sol 523 lines
// 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);
}
ILegionSealedBidAuction.sol 211 lines
// 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);
}
ERC20.sol 312 lines
// 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);
            }
        }
    }
}
IERC20.sol 79 lines
// 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);
}
Initializable.sol 228 lines
// 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
        }
    }
}
MerkleProof.sol 514 lines
// 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];
        }
    }
}
SafeERC20.sol 199 lines
// 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);
    }
}
LegionBaseSale.sol 687 lines
// 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();
    }
}
ILegionAddressRegistry.sol 41 lines
// 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);
}
ILegionLinearVesting.sol 70 lines
// 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);
}
ILegionVestingFactory.sol 46 lines
// 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);
}
ECIES.sol 152 lines
// 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)
        }
    }
}
ILegionBaseSale.sol 372 lines
// 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;
}
IERC20Metadata.sol 26 lines
// 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);
}
draft-IERC6093.sol 161 lines
// 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);
}
Hashes.sol 31 lines
// 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)
        }
    }
}
IERC1363.sol 86 lines
// 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);
}
Address.sol 150 lines
// 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();
        }
    }
}
ECDSA.sol 180 lines
// 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);
        }
    }
}
MessageHashUtils.sol 84 lines
// 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)
        }
    }
}
IERC20.sol 6 lines
// 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";
IERC165.sol 6 lines
// 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";
Strings.sol 116 lines
// 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));
    }
}
IERC165.sol 25 lines
// 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);
}
Math.sol 685 lines
// 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;
    }
}
SignedMath.sol 68 lines
// 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);
        }
    }
}
Panic.sol 57 lines
// 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)
        }
    }
}
SafeCast.sol 1162 lines
// 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))
        }
    }
}

Read Contract

fixedPriceSaleTemplate 0x8be135a7 → address
owner 0x8da5cb5b → address
preLiquidSaleTemplate 0x92be66a4 → address
sealedBidAuctionTemplate 0x18a1fa18 → address

Write Contract 5 functions

These functions modify contract state and require a wallet transaction to execute.

createFixedPriceSale 0x205774dc
tuple fixedPriceSaleConfig
returns: address
createPreLiquidSale 0x3223188e
tuple preLiquidSaleConfig
returns: address
createSealedBidAuction 0x80fc462d
tuple sealedBidAuctionConfig
returns: address
renounceOwnership 0x715018a6
No parameters
transferOwnership 0xf2fde38b
address newOwner

Recent Transactions

No transactions found for this address