Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· OpenAIAi2 WildChat-4.8M (AI2)

// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import…

  1. User

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

    import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

    import "./CurvesERC20.sol"; import "./CurvesERC20Factory.sol";

    import "./FeeSplitter.sol"; import "./Security.sol";

    interface CurvesErrors { // Access-related error UnauthorizedCurvesTokenSubject(); // Balance-related error InsufficientPayment(); error CannotSendFunds(); error InsufficientBalance(); // ERC20-related error InvalidERC20Metadata(); error ERC20TokenAlreadyMinted(); // State-related error TokenAbsentForCurvesTokenSubject(); error CurveAlreadyExists(); // Transaction-related error LastTokenCannotBeSold(); error ContractCannotReceiveTransfer(); error ExceededMaxBuyAmount(); error NonIntegerDepositAmount(); // Proof-related error UnverifiedProof(); // Presale-related error PresaleUnavailable(); error InvalidPresaleStartTime(); error SaleNotOpen(); // Fee related error InvalidFeeDefinition(); }

    contract Curves is CurvesErrors, Security { address public curvesERC20Factory; FeeSplitter public feeRedistributor; string public constant DEFAULT_NAME = "Curves"; string public constant DEFAULT_SYMBOL = "CURVES"; // Counter for CURVES tokens minted uint256 private _curvesTokenCounter = 0;

    struct ExternalTokenMeta {
        string name;
        string symbol;
        address token;
    }
    
    struct PresaleMeta {
        uint256 startTime;
        bytes32 merkleRoot;
        uint256 maxBuy;
    }
    
    mapping(address => ExternalTokenMeta) public externalCurvesTokens;
    mapping(address => address) public externalCurvesToSubject;
    mapping(string => address) public symbolToSubject;
    
    mapping(address => PresaleMeta) public presalesMeta;
    mapping(address => mapping(address => uint256)) public presalesBuys;
    
    struct FeesEconomics {
        address protocolFeeDestination;
        uint256 protocolFeePercent;
        uint256 subjectFeePercent;
        uint256 referralFeePercent;
        uint256 holdersFeePercent;
        uint256 maxFeePercent;
    }
    
    FeesEconomics public feesEconomics;
    mapping(address => address) public referralFeeDestination;
    
    event Trade(
        address trader,
        address subject,
        bool isBuy,
        uint256 tokenAmount,
        uint256 ethAmount,
        uint256 protocolEthAmount,
        uint256 subjectEthAmount,
        uint256 supply
    );
    
    event Transfer(address indexed curvesTokenSubject, address indexed from, address indexed to, uint256 value);
    event WhitelistUpdated(address indexed presale, bytes32 indexed root);
    event TokenDeployed(address indexed curvesTokenSubject, address indexed erc20token, string name, string symbol);
    
    // TokenSubject => (Holder => Balance)
    mapping(address => mapping(address => uint256)) public curvesTokenBalance;
    
    // TokenSubject => Supply
    mapping(address => uint256) public curvesTokenSupply;
    
    mapping(address => address[]) private ownedCurvesTokenSubjects;
    
    modifier onlyTokenSubject(address curvesTokenSubject) {
        if (curvesTokenSubject != msg.sender) revert UnauthorizedCurvesTokenSubject();
        _;
    }
    
    constructor(address curvesERC20Factory_, address feeRedistributor_) Security() {
        curvesERC20Factory = curvesERC20Factory_;
        feeRedistributor = FeeSplitter(payable(feeRedistributor_));
    }
    
    function setFeeRedistributor(address feeRedistributor_) external onlyOwner {
        feeRedistributor = FeeSplitter(payable(feeRedistributor_));
    }
    
    function setMaxFeePercent(uint256 maxFeePercent_) external onlyManager {
        if (
            feesEconomics.protocolFeePercent +
                feesEconomics.subjectFeePercent +
                feesEconomics.referralFeePercent +
                feesEconomics.holdersFeePercent >
            maxFeePercent_
        ) revert InvalidFeeDefinition();
        feesEconomics.maxFeePercent = maxFeePercent_;
    }
    
    function setProtocolFeePercent(uint256 protocolFeePercent_, address protocolFeeDestination_) external onlyOwner {
        if (
            protocolFeePercent_ +
                feesEconomics.subjectFeePercent +
                feesEconomics.referralFeePercent +
                feesEconomics.holdersFeePercent >
            feesEconomics.maxFeePercent ||
            protocolFeeDestination_ == address(0)
        ) revert InvalidFeeDefinition();
        feesEconomics.protocolFeePercent = protocolFeePercent_;
        feesEconomics.protocolFeeDestination = protocolFeeDestination_;
    }
    
    function setExternalFeePercent(
        uint256 subjectFeePercent_,
        uint256 referralFeePercent_,
        uint256 holdersFeePercent_
    ) external onlyManager {
        if (
            feesEconomics.protocolFeePercent + subjectFeePercent_ + referralFeePercent_ + holdersFeePercent_ >
            feesEconomics.maxFeePercent
        ) revert InvalidFeeDefinition();
        feesEconomics.subjectFeePercent = subjectFeePercent_;
        feesEconomics.referralFeePercent = referralFeePercent_;
        feesEconomics.holdersFeePercent = holdersFeePercent_;
    }
    
    function setReferralFeeDestination(
        address curvesTokenSubject,
        address referralFeeDestination_
    ) public onlyTokenSubject(curvesTokenSubject) {
        referralFeeDestination[curvesTokenSubject] = referralFeeDestination_;
    }
    
    function setERC20Factory(address factory_) external onlyOwner {
        curvesERC20Factory = factory_;
    }
    
    function getFees(
        uint256 price
    )
        public
        view
        returns (uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holdersFee, uint256 totalFee)
    {
        protocolFee = (price * feesEconomics.protocolFeePercent) / 1 ether;
        subjectFee = (price * feesEconomics.subjectFeePercent) / 1 ether;
        referralFee = (price * feesEconomics.referralFeePercent) / 1 ether;
        holdersFee = (price * feesEconomics.holdersFeePercent) / 1 ether;
        totalFee = protocolFee + subjectFee + referralFee + holdersFee;
    }
    
    function getPrice(uint256 supply, uint256 amount) public pure returns (uint256) {
        uint256 sum1 = supply == 0 ? 0 : ((supply - 1) * (supply) * (2 * (supply - 1) + 1)) / 6;
        uint256 sum2 = supply == 0 && amount == 1
            ? 0
            : ((supply - 1 + amount) * (supply + amount) * (2 * (supply - 1 + amount) + 1)) / 6;
        uint256 summation = sum2 - sum1;
        return (summation * 1 ether) / 16000;
    }
    
    function getBuyPrice(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        return getPrice(curvesTokenSupply[curvesTokenSubject], amount);
    }
    
    function getSellPrice(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        return getPrice(curvesTokenSupply[curvesTokenSubject] - amount, amount);
    }
    
    function getBuyPriceAfterFee(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        uint256 price = getBuyPrice(curvesTokenSubject, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        return price + totalFee;
    }
    
    function getSellPriceAfterFee(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        uint256 price = getSellPrice(curvesTokenSubject, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        return price - totalFee;
    }
    
    function buyCurvesToken(address curvesTokenSubject, uint256 amount) public payable {
        uint256 startTime = presalesMeta[curvesTokenSubject].startTime;
        if (startTime != 0 && startTime >= block.timestamp) revert SaleNotOpen();
    
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function _transferFees(
        address curvesTokenSubject,
        bool isBuy,
        uint256 price,
        uint256 amount,
        uint256 supply
    ) internal {
        (uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holderFee, ) = getFees(price);
        {
            bool referralDefined = referralFeeDestination[curvesTokenSubject] != address(0);
            {
                address firstDestination = isBuy ? feesEconomics.protocolFeeDestination : msg.sender;
                uint256 buyValue = referralDefined ? protocolFee : protocolFee + referralFee;
                uint256 sellValue = price - protocolFee - subjectFee - referralFee - holderFee;
                (bool success1, ) = firstDestination.call{value: isBuy ? buyValue : sellValue}("");
                if (!success1) revert CannotSendFunds();
            }
            {
                (bool success2, ) = curvesTokenSubject.call{value: subjectFee}("");
                if (!success2) revert CannotSendFunds();
            }
            {
                (bool success3, ) = referralDefined
                    ? referralFeeDestination[curvesTokenSubject].call{value: referralFee}("")
                    : (true, bytes(""));
                if (!success3) revert CannotSendFunds();
            }
    
            if (feesEconomics.holdersFeePercent > 0 && address(feeRedistributor) != address(0)) {
                feeRedistributor.onBalanceChange(curvesTokenSubject, msg.sender);
                feeRedistributor.addFees{value: holderFee}(curvesTokenSubject);
            }
        }
        emit Trade(
            msg.sender,
            curvesTokenSubject,
            isBuy,
            amount,
            price,
            protocolFee,
            subjectFee,
            isBuy ? supply + amount : supply - amount
        );
    }
    
    function _buyCurvesToken(address curvesTokenSubject, uint256 amount) internal {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (!(supply > 0 || curvesTokenSubject == msg.sender)) revert UnauthorizedCurvesTokenSubject();
    
        uint256 price = getPrice(supply, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        if (msg.value < price + totalFee) revert InsufficientPayment();
    
        curvesTokenBalance[curvesTokenSubject][msg.sender] += amount;
        curvesTokenSupply[curvesTokenSubject] = supply + amount;
        _transferFees(curvesTokenSubject, true, price, amount, supply);
    
        // If is the first token bought, add to the list of owned tokens
        if (curvesTokenBalance[curvesTokenSubject][msg.sender] - amount == 0) {
            _addOwnedCurvesTokenSubject(msg.sender, curvesTokenSubject);
        }
    }
    
    function sellCurvesToken(address curvesTokenSubject, uint256 amount) public {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply <= amount) revert LastTokenCannotBeSold();
        if (curvesTokenBalance[curvesTokenSubject][msg.sender] < amount) revert InsufficientBalance();
    
        uint256 price = getPrice(supply - amount, amount);
    
        curvesTokenBalance[curvesTokenSubject][msg.sender] -= amount;
        curvesTokenSupply[curvesTokenSubject] = supply - amount;
    
        _transferFees(curvesTokenSubject, false, price, amount, supply);
    }
    
    // Transfers tokens from current owner to receiver. Can be used for gifting or distributing tokens.
    function transferCurvesToken(address curvesTokenSubject, address to, uint256 amount) external {
        if (to == address(this)) revert ContractCannotReceiveTransfer();
        _transfer(curvesTokenSubject, msg.sender, to, amount);
    }
    
    // Transfer the total balance of all my tokens to another address. Can be used for migrating tokens.
    function transferAllCurvesTokens(address to) external {
        if (to == address(this)) revert ContractCannotReceiveTransfer();
        address[] storage subjects = ownedCurvesTokenSubjects[msg.sender];
        for (uint256 i = 0; i < subjects.length; i++) {
            uint256 amount = curvesTokenBalance[subjects[i]][msg.sender];
            if (amount > 0) {
                _transfer(subjects[i], msg.sender, to, amount);
            }
        }
    }
    
    function _transfer(address curvesTokenSubject, address from, address to, uint256 amount) internal {
        if (amount > curvesTokenBalance[curvesTokenSubject][from]) revert InsufficientBalance();
    
        // If transferring from oneself, skip adding to the list
        if (from != to) {
            _addOwnedCurvesTokenSubject(to, curvesTokenSubject);
        }
    
        curvesTokenBalance[curvesTokenSubject][from] = curvesTokenBalance[curvesTokenSubject][from] - amount;
        curvesTokenBalance[curvesTokenSubject][to] = curvesTokenBalance[curvesTokenSubject][to] + amount;
    
        emit Transfer(curvesTokenSubject, from, to, amount);
    }
    
    // Internal function to add a curvesTokenSubject to the list if not already present
    function _addOwnedCurvesTokenSubject(address owner_, address curvesTokenSubject) internal {
        address[] storage subjects = ownedCurvesTokenSubjects[owner_];
        for (uint256 i = 0; i < subjects.length; i++) {
            if (subjects[i] == curvesTokenSubject) {
                return;
            }
        }
        subjects.push(curvesTokenSubject);
    }
    
    function _deployERC20(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) internal returns (address) {
        // If the token's symbol is CURVES, append a counter value
        if (keccak256(bytes(symbol)) == keccak256(bytes(DEFAULT_SYMBOL))) {
            _curvesTokenCounter += 1;
            name = string(abi.encodePacked(name, " ", Strings.toString(_curvesTokenCounter)));
            symbol = string(abi.encodePacked(symbol, Strings.toString(_curvesTokenCounter)));
        }
    
        if (symbolToSubject[symbol] != address(0)) revert InvalidERC20Metadata();
    
        address tokenContract = CurvesERC20Factory(curvesERC20Factory).deploy(name, symbol, address(this));
    
        externalCurvesTokens[curvesTokenSubject].token = tokenContract;
        externalCurvesTokens[curvesTokenSubject].name = name;
        externalCurvesTokens[curvesTokenSubject].symbol = symbol;
        externalCurvesToSubject[tokenContract] = curvesTokenSubject;
        symbolToSubject[symbol] = curvesTokenSubject;
    
        emit TokenDeployed(curvesTokenSubject, tokenContract, name, symbol);
        return address(tokenContract);
    }
    
    function buyCurvesTokenWithName(
        address curvesTokenSubject,
        uint256 amount,
        string memory name,
        string memory symbol
    ) public payable {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply != 0) revert CurveAlreadyExists();
    
        _buyCurvesToken(curvesTokenSubject, amount);
        _mint(curvesTokenSubject, name, symbol);
    }
    
    function buyCurvesTokenForPresale(
        address curvesTokenSubject,
        uint256 amount,
        uint256 startTime,
        bytes32 merkleRoot,
        uint256 maxBuy
    ) public payable onlyTokenSubject(curvesTokenSubject) {
        if (startTime <= block.timestamp) revert InvalidPresaleStartTime();
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply != 0) revert CurveAlreadyExists();
        presalesMeta[curvesTokenSubject].startTime = startTime;
        presalesMeta[curvesTokenSubject].merkleRoot = merkleRoot;
        presalesMeta[curvesTokenSubject].maxBuy = (maxBuy == 0 ? type(uint256).max : maxBuy);
    
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function setWhitelist(bytes32 merkleRoot) external {
        uint256 supply = curvesTokenSupply[msg.sender];
        if (supply > 1) revert CurveAlreadyExists();
    
        if (presalesMeta[msg.sender].merkleRoot != merkleRoot) {
            presalesMeta[msg.sender].merkleRoot = merkleRoot;
            emit WhitelistUpdated(msg.sender, merkleRoot);
        }
    }
    
    function buyCurvesTokenWhitelisted(
        address curvesTokenSubject,
        uint256 amount,
        bytes32[] memory proof
    ) public payable {
        if (
            presalesMeta[curvesTokenSubject].startTime == 0 ||
            presalesMeta[curvesTokenSubject].startTime <= block.timestamp
        ) revert PresaleUnavailable();
    
        presalesBuys[curvesTokenSubject][msg.sender] += amount;
        uint256 tokenBought = presalesBuys[curvesTokenSubject][msg.sender];
        if (tokenBought > presalesMeta[curvesTokenSubject].maxBuy) revert ExceededMaxBuyAmount();
    
        verifyMerkle(curvesTokenSubject, msg.sender, proof);
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function verifyMerkle(address curvesTokenSubject, address caller, bytes32[] memory proof) public view {
        // Verify merkle proof
        bytes32 leaf = keccak256(abi.encodePacked(caller));
        if (!MerkleProof.verify(proof, presalesMeta[curvesTokenSubject].merkleRoot, leaf)) revert UnverifiedProof();
    }
    
    function setNameAndSymbol(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) external onlyTokenSubject(curvesTokenSubject) {
        if (externalCurvesTokens[curvesTokenSubject].token != address(0)) revert ERC20TokenAlreadyMinted();
        if (symbolToSubject[symbol] != address(0)) revert InvalidERC20Metadata();
        externalCurvesTokens[curvesTokenSubject].name = name;
        externalCurvesTokens[curvesTokenSubject].symbol = symbol;
    }
    
    function mint(address curvesTokenSubject) external onlyTokenSubject(curvesTokenSubject) {
        if (
            keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].name)) ==
            keccak256(abi.encodePacked("")) ||
            keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].symbol)) ==
            keccak256(abi.encodePacked(""))
        ) {
            externalCurvesTokens[curvesTokenSubject].name = DEFAULT_NAME;
            externalCurvesTokens[curvesTokenSubject].symbol = DEFAULT_SYMBOL;
        }
        _mint(
            curvesTokenSubject,
            externalCurvesTokens[curvesTokenSubject].name,
            externalCurvesTokens[curvesTokenSubject].symbol
        );
    }
    
    function _mint(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) internal onlyTokenSubject(curvesTokenSubject) {
        if (externalCurvesTokens[curvesTokenSubject].token != address(0)) revert ERC20TokenAlreadyMinted();
        _deployERC20(curvesTokenSubject, name, symbol);
    }
    
    function withdraw(address curvesTokenSubject, uint256 amount) public {
        if (amount > curvesTokenBalance[curvesTokenSubject][msg.sender]) revert InsufficientBalance();
    
        address externalToken = externalCurvesTokens[curvesTokenSubject].token;
        if (externalToken == address(0)) {
            if (
                keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].name)) ==
                keccak256(abi.encodePacked("")) ||
                keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].symbol)) ==
                keccak256(abi.encodePacked(""))
            ) {
                externalCurvesTokens[curvesTokenSubject].name = DEFAULT_NAME;
                externalCurvesTokens[curvesTokenSubject].symbol = DEFAULT_SYMBOL;
            }
            _deployERC20(
                curvesTokenSubject,
                externalCurvesTokens[curvesTokenSubject].name,
                externalCurvesTokens[curvesTokenSubject].symbol
            );
            externalToken = externalCurvesTokens[curvesTokenSubject].token;
        }
        _transfer(curvesTokenSubject, msg.sender, address(this), amount);
        CurvesERC20(externalToken).mint(msg.sender, amount * 1 ether);
    }
    
    function deposit(address curvesTokenSubject, uint256 amount) public {
        if (amount % 1 ether != 0) revert NonIntegerDepositAmount();
    
        address externalToken = externalCurvesTokens[curvesTokenSubject].token;
        uint256 tokenAmount = amount / 1 ether;
    
        if (externalToken == address(0)) revert TokenAbsentForCurvesTokenSubject();
        if (amount > CurvesERC20(externalToken).balanceOf(msg.sender)) revert InsufficientBalance();
        if (tokenAmount > curvesTokenBalance[curvesTokenSubject][address(this)]) revert InsufficientBalance();
    
        CurvesERC20(externalToken).burn(msg.sender, amount);
        _transfer(curvesTokenSubject, address(this), msg.sender, tokenAmount);
    }
    
    function sellExternalCurvesToken(address curvesTokenSubject, uint256 amount) public {
        if (externalCurvesTokens[curvesTokenSubject].token == address(0)) revert TokenAbsentForCurvesTokenSubject();
    
        deposit(curvesTokenSubject, amount);
        sellCurvesToken(curvesTokenSubject, amount / 1 ether);
    }
    

    } This contract seems to involve an ERC20 token factory, fee redistribution, and presale mechanisms. Let's start diagramming the architecture.

    Could you describe the main components and how they interact with each other? For instance, what role does the CurvesERC20Factory play in the system?

  2. Assistant

    The provided smart contract code describes a system that incorporates several interacting components. At a high level, this system seems to govern the creation, trading, and fee distribution of a set of ERC20 tokens. Below are the main components and their interactions:

    1. Curves Contract

    The main contract that appears to govern the behavior of trading "Curve" tokens which are associated with respective "subject" addresses. Each "curve" represents a bonding curve used for pricing the tokens as the supply increases. It's responsible for:

    • Buying and selling curve tokens.
    • Calculates prices according to a bonding curve.
    • Transfers tokens.
    • Manages fees and fee redistribution.
    • Manages presales and merkle proofs for whitelisting.
    • Deploys ERC20 tokens for each curve.

    2. CurvesERC20Factory (CurvesERC20Factory.sol)

    The contract acts as a factory to create instances of ERC20 tokens. It's referenced by the Curves contract to mint new ERC20 tokens when a new curve is created, or when someone initiates a withdraw from the curve to get the underlying ERC20 token.

    3. FeeSplitter (FeeSplitter.sol)

    This contract seems to be responsible for handling the redistribution of fees collected from trading the curve tokens. It distributes the fees to various stakeholders, such as:

    • The protocol itself (by accumulating fees to its address).
    • Referral fee destination (if any referral fee is defined).
    • Holders of the curve tokens.

    4. Security (Security.sol)

    This appears to be a base contract implementing access control features. It likely defines roles and permissions such as owner and manager to protect function calls with onlyOwner or onlyManager modifiers.

    5. ExternalTokenMeta Struct

    Stores metadata for external ERC20 tokens associated with a curve. It includes the token's name, symbol, and contract address.

    6. PresaleMeta Struct

    Contains information about presales for a curve, like the start time, merkle root for whitelisting, and the maximum amount that can be bought.

    7. FeesEconomics Struct

    Defines the fee structure for the protocol, including the percentages for protocol, subject, referral, and holder fees, as well as the destination for these fees.

    Interactions:

    • Deployment and ERC20 Creation: Users can create new curves and associated ERC20 tokens. The Curves contract interacts with the CurvesERC20Factory to deploy a new ERC20 token with the specified name and symbol. Once created, the token's metadata is stored, and it's mapped to its subject curve.

    • Trading: Users can buy or sell their curve tokens via the Curves contract, which calculates the price based on a mathematical formula and the current supply. During each trade, part of the ETH paid is distributed as fees according to the FeesEconomics setup.

    • Fee Redistribution: Upon a trade, fees are split among various parties, and the FeeSplitter is called upon to handle the redistribution to token holders.

    • Presales: The contract supports presale mechanisms, where certain addresses can be whitelisted to buy curve tokens before the general sale begins. This is managed using a merkle proof to verify the eligibility of presale participants.

    • Withdrawals and Deposits: Users can withdraw their curve tokens, receiving the ERC20 token, or deposit their ERC20 tokens to receive curve tokens back.

    In summary, the Curves contract serves as the centerpiece of this ecosystem, orchestrating the minting of ERC20 tokens via the factory, managing trades against a bonding curve, handling fee distributions, and managing presales through whitelisting. The other components support these functions with the necessary infrastructure for token creation, access control, and fee management.

  3. User

    the core interactions between the Curves contract, the CurvesERC20Factory, and the FeeSplitter. We'll represent the creation of ERC20 tokens, the trading process, and the fee distribution mechanism.

    Let's begin with the ERC20 token creation process. Could you explain how a new ERC20 token is created in the system? What triggers the creation, and what are the steps involved? // SPDX-License-Identifier: MIT pragma solidity 0.8.7;

    import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

    import "./CurvesERC20.sol"; import "./CurvesERC20Factory.sol";

    import "./FeeSplitter.sol"; import "./Security.sol";

    interface CurvesErrors { // Access-related error UnauthorizedCurvesTokenSubject(); // Balance-related error InsufficientPayment(); error CannotSendFunds(); error InsufficientBalance(); // ERC20-related error InvalidERC20Metadata(); error ERC20TokenAlreadyMinted(); // State-related error TokenAbsentForCurvesTokenSubject(); error CurveAlreadyExists(); // Transaction-related error LastTokenCannotBeSold(); error ContractCannotReceiveTransfer(); error ExceededMaxBuyAmount(); error NonIntegerDepositAmount(); // Proof-related error UnverifiedProof(); // Presale-related error PresaleUnavailable(); error InvalidPresaleStartTime(); error SaleNotOpen(); // Fee related error InvalidFeeDefinition(); }

    contract Curves is CurvesErrors, Security { address public curvesERC20Factory; FeeSplitter public feeRedistributor; string public constant DEFAULT_NAME = "Curves"; string public constant DEFAULT_SYMBOL = "CURVES"; // Counter for CURVES tokens minted uint256 private _curvesTokenCounter = 0;

    struct ExternalTokenMeta {
        string name;
        string symbol;
        address token;
    }
    
    struct PresaleMeta {
        uint256 startTime;
        bytes32 merkleRoot;
        uint256 maxBuy;
    }
    
    mapping(address => ExternalTokenMeta) public externalCurvesTokens;
    mapping(address => address) public externalCurvesToSubject;
    mapping(string => address) public symbolToSubject;
    
    mapping(address => PresaleMeta) public presalesMeta;
    mapping(address => mapping(address => uint256)) public presalesBuys;
    
    struct FeesEconomics {
        address protocolFeeDestination;
        uint256 protocolFeePercent;
        uint256 subjectFeePercent;
        uint256 referralFeePercent;
        uint256 holdersFeePercent;
        uint256 maxFeePercent;
    }
    
    FeesEconomics public feesEconomics;
    mapping(address => address) public referralFeeDestination;
    
    event Trade(
        address trader,
        address subject,
        bool isBuy,
        uint256 tokenAmount,
        uint256 ethAmount,
        uint256 protocolEthAmount,
        uint256 subjectEthAmount,
        uint256 supply
    );
    
    event Transfer(address indexed curvesTokenSubject, address indexed from, address indexed to, uint256 value);
    event WhitelistUpdated(address indexed presale, bytes32 indexed root);
    event TokenDeployed(address indexed curvesTokenSubject, address indexed erc20token, string name, string symbol);
    
    // TokenSubject => (Holder => Balance)
    mapping(address => mapping(address => uint256)) public curvesTokenBalance;
    
    // TokenSubject => Supply
    mapping(address => uint256) public curvesTokenSupply;
    
    mapping(address => address[]) private ownedCurvesTokenSubjects;
    
    modifier onlyTokenSubject(address curvesTokenSubject) {
        if (curvesTokenSubject != msg.sender) revert UnauthorizedCurvesTokenSubject();
        _;
    }
    
    constructor(address curvesERC20Factory_, address feeRedistributor_) Security() {
        curvesERC20Factory = curvesERC20Factory_;
        feeRedistributor = FeeSplitter(payable(feeRedistributor_));
    }
    
    function setFeeRedistributor(address feeRedistributor_) external onlyOwner {
        feeRedistributor = FeeSplitter(payable(feeRedistributor_));
    }
    
    function setMaxFeePercent(uint256 maxFeePercent_) external onlyManager {
        if (
            feesEconomics.protocolFeePercent +
                feesEconomics.subjectFeePercent +
                feesEconomics.referralFeePercent +
                feesEconomics.holdersFeePercent >
            maxFeePercent_
        ) revert InvalidFeeDefinition();
        feesEconomics.maxFeePercent = maxFeePercent_;
    }
    
    function setProtocolFeePercent(uint256 protocolFeePercent_, address protocolFeeDestination_) external onlyOwner {
        if (
            protocolFeePercent_ +
                feesEconomics.subjectFeePercent +
                feesEconomics.referralFeePercent +
                feesEconomics.holdersFeePercent >
            feesEconomics.maxFeePercent ||
            protocolFeeDestination_ == address(0)
        ) revert InvalidFeeDefinition();
        feesEconomics.protocolFeePercent = protocolFeePercent_;
        feesEconomics.protocolFeeDestination = protocolFeeDestination_;
    }
    
    function setExternalFeePercent(
        uint256 subjectFeePercent_,
        uint256 referralFeePercent_,
        uint256 holdersFeePercent_
    ) external onlyManager {
        if (
            feesEconomics.protocolFeePercent + subjectFeePercent_ + referralFeePercent_ + holdersFeePercent_ >
            feesEconomics.maxFeePercent
        ) revert InvalidFeeDefinition();
        feesEconomics.subjectFeePercent = subjectFeePercent_;
        feesEconomics.referralFeePercent = referralFeePercent_;
        feesEconomics.holdersFeePercent = holdersFeePercent_;
    }
    
    function setReferralFeeDestination(
        address curvesTokenSubject,
        address referralFeeDestination_
    ) public onlyTokenSubject(curvesTokenSubject) {
        referralFeeDestination[curvesTokenSubject] = referralFeeDestination_;
    }
    
    function setERC20Factory(address factory_) external onlyOwner {
        curvesERC20Factory = factory_;
    }
    
    function getFees(
        uint256 price
    )
        public
        view
        returns (uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holdersFee, uint256 totalFee)
    {
        protocolFee = (price * feesEconomics.protocolFeePercent) / 1 ether;
        subjectFee = (price * feesEconomics.subjectFeePercent) / 1 ether;
        referralFee = (price * feesEconomics.referralFeePercent) / 1 ether;
        holdersFee = (price * feesEconomics.holdersFeePercent) / 1 ether;
        totalFee = protocolFee + subjectFee + referralFee + holdersFee;
    }
    
    function getPrice(uint256 supply, uint256 amount) public pure returns (uint256) {
        uint256 sum1 = supply == 0 ? 0 : ((supply - 1) * (supply) * (2 * (supply - 1) + 1)) / 6;
        uint256 sum2 = supply == 0 && amount == 1
            ? 0
            : ((supply - 1 + amount) * (supply + amount) * (2 * (supply - 1 + amount) + 1)) / 6;
        uint256 summation = sum2 - sum1;
        return (summation * 1 ether) / 16000;
    }
    
    function getBuyPrice(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        return getPrice(curvesTokenSupply[curvesTokenSubject], amount);
    }
    
    function getSellPrice(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        return getPrice(curvesTokenSupply[curvesTokenSubject] - amount, amount);
    }
    
    function getBuyPriceAfterFee(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        uint256 price = getBuyPrice(curvesTokenSubject, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        return price + totalFee;
    }
    
    function getSellPriceAfterFee(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        uint256 price = getSellPrice(curvesTokenSubject, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        return price - totalFee;
    }
    
    function buyCurvesToken(address curvesTokenSubject, uint256 amount) public payable {
        uint256 startTime = presalesMeta[curvesTokenSubject].startTime;
        if (startTime != 0 && startTime >= block.timestamp) revert SaleNotOpen();
    
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function _transferFees(
        address curvesTokenSubject,
        bool isBuy,
        uint256 price,
        uint256 amount,
        uint256 supply
    ) internal {
        (uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holderFee, ) = getFees(price);
        {
            bool referralDefined = referralFeeDestination[curvesTokenSubject] != address(0);
            {
                address firstDestination = isBuy ? feesEconomics.protocolFeeDestination : msg.sender;
                uint256 buyValue = referralDefined ? protocolFee : protocolFee + referralFee;
                uint256 sellValue = price - protocolFee - subjectFee - referralFee - holderFee;
                (bool success1, ) = firstDestination.call{value: isBuy ? buyValue : sellValue}("");
                if (!success1) revert CannotSendFunds();
            }
            {
                (bool success2, ) = curvesTokenSubject.call{value: subjectFee}("");
                if (!success2) revert CannotSendFunds();
            }
            {
                (bool success3, ) = referralDefined
                    ? referralFeeDestination[curvesTokenSubject].call{value: referralFee}("")
                    : (true, bytes(""));
                if (!success3) revert CannotSendFunds();
            }
    
            if (feesEconomics.holdersFeePercent > 0 && address(feeRedistributor) != address(0)) {
                feeRedistributor.onBalanceChange(curvesTokenSubject, msg.sender);
                feeRedistributor.addFees{value: holderFee}(curvesTokenSubject);
            }
        }
        emit Trade(
            msg.sender,
            curvesTokenSubject,
            isBuy,
            amount,
            price,
            protocolFee,
            subjectFee,
            isBuy ? supply + amount : supply - amount
        );
    }
    
    function _buyCurvesToken(address curvesTokenSubject, uint256 amount) internal {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (!(supply > 0 || curvesTokenSubject == msg.sender)) revert UnauthorizedCurvesTokenSubject();
    
        uint256 price = getPrice(supply, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        if (msg.value < price + totalFee) revert InsufficientPayment();
    
        curvesTokenBalance[curvesTokenSubject][msg.sender] += amount;
        curvesTokenSupply[curvesTokenSubject] = supply + amount;
        _transferFees(curvesTokenSubject, true, price, amount, supply);
    
        // If is the first token bought, add to the list of owned tokens
        if (curvesTokenBalance[curvesTokenSubject][msg.sender] - amount == 0) {
            _addOwnedCurvesTokenSubject(msg.sender, curvesTokenSubject);
        }
    }
    
    function sellCurvesToken(address curvesTokenSubject, uint256 amount) public {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply <= amount) revert LastTokenCannotBeSold();
        if (curvesTokenBalance[curvesTokenSubject][msg.sender] < amount) revert InsufficientBalance();
    
        uint256 price = getPrice(supply - amount, amount);
    
        curvesTokenBalance[curvesTokenSubject][msg.sender] -= amount;
        curvesTokenSupply[curvesTokenSubject] = supply - amount;
    
        _transferFees(curvesTokenSubject, false, price, amount, supply);
    }
    
    // Transfers tokens from current owner to receiver. Can be used for gifting or distributing tokens.
    function transferCurvesToken(address curvesTokenSubject, address to, uint256 amount) external {
        if (to == address(this)) revert ContractCannotReceiveTransfer();
        _transfer(curvesTokenSubject, msg.sender, to, amount);
    }
    
    // Transfer the total balance of all my tokens to another address. Can be used for migrating tokens.
    function transferAllCurvesTokens(address to) external {
        if (to == address(this)) revert ContractCannotReceiveTransfer();
        address[] storage subjects = ownedCurvesTokenSubjects[msg.sender];
        for (uint256 i = 0; i < subjects.length; i++) {
            uint256 amount = curvesTokenBalance[subjects[i]][msg.sender];
            if (amount > 0) {
                _transfer(subjects[i], msg.sender, to, amount);
            }
        }
    }
    
    function _transfer(address curvesTokenSubject, address from, address to, uint256 amount) internal {
        if (amount > curvesTokenBalance[curvesTokenSubject][from]) revert InsufficientBalance();
    
        // If transferring from oneself, skip adding to the list
        if (from != to) {
            _addOwnedCurvesTokenSubject(to, curvesTokenSubject);
        }
    
        curvesTokenBalance[curvesTokenSubject][from] = curvesTokenBalance[curvesTokenSubject][from] - amount;
        curvesTokenBalance[curvesTokenSubject][to] = curvesTokenBalance[curvesTokenSubject][to] + amount;
    
        emit Transfer(curvesTokenSubject, from, to, amount);
    }
    
    // Internal function to add a curvesTokenSubject to the list if not already present
    function _addOwnedCurvesTokenSubject(address owner_, address curvesTokenSubject) internal {
        address[] storage subjects = ownedCurvesTokenSubjects[owner_];
        for (uint256 i = 0; i < subjects.length; i++) {
            if (subjects[i] == curvesTokenSubject) {
                return;
            }
        }
        subjects.push(curvesTokenSubject);
    }
    
    function _deployERC20(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) internal returns (address) {
        // If the token's symbol is CURVES, append a counter value
        if (keccak256(bytes(symbol)) == keccak256(bytes(DEFAULT_SYMBOL))) {
            _curvesTokenCounter += 1;
            name = string(abi.encodePacked(name, " ", Strings.toString(_curvesTokenCounter)));
            symbol = string(abi.encodePacked(symbol, Strings.toString(_curvesTokenCounter)));
        }
    
        if (symbolToSubject[symbol] != address(0)) revert InvalidERC20Metadata();
    
        address tokenContract = CurvesERC20Factory(curvesERC20Factory).deploy(name, symbol, address(this));
    
        externalCurvesTokens[curvesTokenSubject].token = tokenContract;
        externalCurvesTokens[curvesTokenSubject].name = name;
        externalCurvesTokens[curvesTokenSubject].symbol = symbol;
        externalCurvesToSubject[tokenContract] = curvesTokenSubject;
        symbolToSubject[symbol] = curvesTokenSubject;
    
        emit TokenDeployed(curvesTokenSubject, tokenContract, name, symbol);
        return address(tokenContract);
    }
    
    function buyCurvesTokenWithName(
        address curvesTokenSubject,
        uint256 amount,
        string memory name,
        string memory symbol
    ) public payable {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply != 0) revert CurveAlreadyExists();
    
        _buyCurvesToken(curvesTokenSubject, amount);
        _mint(curvesTokenSubject, name, symbol);
    }
    
    function buyCurvesTokenForPresale(
        address curvesTokenSubject,
        uint256 amount,
        uint256 startTime,
        bytes32 merkleRoot,
        uint256 maxBuy
    ) public payable onlyTokenSubject(curvesTokenSubject) {
        if (startTime <= block.timestamp) revert InvalidPresaleStartTime();
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply != 0) revert CurveAlreadyExists();
        presalesMeta[curvesTokenSubject].startTime = startTime;
        presalesMeta[curvesTokenSubject].merkleRoot = merkleRoot;
        presalesMeta[curvesTokenSubject].maxBuy = (maxBuy == 0 ? type(uint256).max : maxBuy);
    
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function setWhitelist(bytes32 merkleRoot) external {
        uint256 supply = curvesTokenSupply[msg.sender];
        if (supply > 1) revert CurveAlreadyExists();
    
        if (presalesMeta[msg.sender].merkleRoot != merkleRoot) {
            presalesMeta[msg.sender].merkleRoot = merkleRoot;
            emit WhitelistUpdated(msg.sender, merkleRoot);
        }
    }
    
    function buyCurvesTokenWhitelisted(
        address curvesTokenSubject,
        uint256 amount,
        bytes32[] memory proof
    ) public payable {
        if (
            presalesMeta[curvesTokenSubject].startTime == 0 ||
            presalesMeta[curvesTokenSubject].startTime <= block.timestamp
        ) revert PresaleUnavailable();
    
        presalesBuys[curvesTokenSubject][msg.sender] += amount;
        uint256 tokenBought = presalesBuys[curvesTokenSubject][msg.sender];
        if (tokenBought > presalesMeta[curvesTokenSubject].maxBuy) revert ExceededMaxBuyAmount();
    
        verifyMerkle(curvesTokenSubject, msg.sender, proof);
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function verifyMerkle(address curvesTokenSubject, address caller, bytes32[] memory proof) public view {
        // Verify merkle proof
        bytes32 leaf = keccak256(abi.encodePacked(caller));
        if (!MerkleProof.verify(proof, presalesMeta[curvesTokenSubject].merkleRoot, leaf)) revert UnverifiedProof();
    }
    
    function setNameAndSymbol(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) external onlyTokenSubject(curvesTokenSubject) {
        if (externalCurvesTokens[curvesTokenSubject].token != address(0)) revert ERC20TokenAlreadyMinted();
        if (symbolToSubject[symbol] != address(0)) revert InvalidERC20Metadata();
        externalCurvesTokens[curvesTokenSubject].name = name;
        externalCurvesTokens[curvesTokenSubject].symbol = symbol;
    }
    
    function mint(address curvesTokenSubject) external onlyTokenSubject(curvesTokenSubject) {
        if (
            keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].name)) ==
            keccak256(abi.encodePacked("")) ||
            keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].symbol)) ==
            keccak256(abi.encodePacked(""))
        ) {
            externalCurvesTokens[curvesTokenSubject].name = DEFAULT_NAME;
            externalCurvesTokens[curvesTokenSubject].symbol = DEFAULT_SYMBOL;
        }
        _mint(
            curvesTokenSubject,
            externalCurvesTokens[curvesTokenSubject].name,
            externalCurvesTokens[curvesTokenSubject].symbol
        );
    }
    
    function _mint(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) internal onlyTokenSubject(curvesTokenSubject) {
        if (externalCurvesTokens[curvesTokenSubject].token != address(0)) revert ERC20TokenAlreadyMinted();
        _deployERC20(curvesTokenSubject, name, symbol);
    }
    
    function withdraw(address curvesTokenSubject, uint256 amount) public {
        if (amount > curvesTokenBalance[curvesTokenSubject][msg.sender]) revert InsufficientBalance();
    
        address externalToken = externalCurvesTokens[curvesTokenSubject].token;
        if (externalToken == address(0)) {
            if (
                keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].name)) ==
                keccak256(abi.encodePacked("")) ||
                keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].symbol)) ==
                keccak256(abi.encodePacked(""))
            ) {
                externalCurvesTokens[curvesTokenSubject].name = DEFAULT_NAME;
                externalCurvesTokens[curvesTokenSubject].symbol = DEFAULT_SYMBOL;
            }
            _deployERC20(
                curvesTokenSubject,
                externalCurvesTokens[curvesTokenSubject].name,
                externalCurvesTokens[curvesTokenSubject].symbol
            );
            externalToken = externalCurvesTokens[curvesTokenSubject].token;
        }
        _transfer(curvesTokenSubject, msg.sender, address(this), amount);
        CurvesERC20(externalToken).mint(msg.sender, amount * 1 ether);
    }
    
    function deposit(address curvesTokenSubject, uint256 amount) public {
        if (amount % 1 ether != 0) revert NonIntegerDepositAmount();
    
        address externalToken = externalCurvesTokens[curvesTokenSubject].token;
        uint256 tokenAmount = amount / 1 ether;
    
        if (externalToken == address(0)) revert TokenAbsentForCurvesTokenSubject();
        if (amount > CurvesERC20(externalToken).balanceOf(msg.sender)) revert InsufficientBalance();
        if (tokenAmount > curvesTokenBalance[curvesTokenSubject][address(this)]) revert InsufficientBalance();
    
        CurvesERC20(externalToken).burn(msg.sender, amount);
        _transfer(curvesTokenSubject, address(this), msg.sender, tokenAmount);
    }
    
    function sellExternalCurvesToken(address curvesTokenSubject, uint256 amount) public {
        if (externalCurvesTokens[curvesTokenSubject].token == address(0)) revert TokenAbsentForCurvesTokenSubject();
    
        deposit(curvesTokenSubject, amount);
        sellCurvesToken(curvesTokenSubject, amount / 1 ether);
    }
    

    }

  4. Assistant

    In the provided Curves contract, ERC20 tokens are created through a process triggered by users interacting with the contract. The steps involved in creating a new ERC20 token are as follows:

    1. Initialization: The constructor of the Curves contract receives the address of the CurvesERC20Factory and the FeeSplitter contract, storing these addresses in state variables for later use.

    2. Buy and Mint Process: A user can trigger the creation of a new ERC20 token by calling either the buyCurvesTokenWithName or the mint function, both of which require the caller to be the subject of the curve—this is verified using the onlyTokenSubject modifier. A subject is an entity that has special privileges, such as deploying an ERC20 token representing their curve (the subject's identity is usually verified off-chain).

      • buyCurvesTokenWithName allows a user to simultaneously buy the first curve token and create an associated ERC20 token with a specified name and symbol, effectively launching a new curve.
      • mint creates the ERC20 token for an existing subject if no token has been previously minted, and initializes it with default name and symbol if none have been provided.
    3. Token Deployment (_deployERC20): The actual creation step of the ERC20 token behind the scenes is done in the internal _deployERC20 function. It takes the curvesTokenSubject, the desired name, and symbol, and proceeds with the following steps:

      • If the symbol is the default ("CURVES"), it appends a counter to it to ensure uniqueness.
      • A check is performed to see if the symbol is already in use, which will revert the transaction in case of a conflict.
      • The actual deployment of the ERC20 contract is done using the deploy function from the CurvesERC20Factory instance, which creates a new CurvesERC20 token contract.
      • The newly deployed ERC20 token contract's address is stored in the externalCurvesTokens mapping, associating it with the curvesTokenSubject. Also, mappings externalCurvesToSubject and symbolToSubject are updated to track the relationship between the token, its subject, and its symbol.
      • An TokenDeployed event is emitted to log the creation.
    4. Token Minting (withdraw): The withdraw function enables users to exchange their curve tokens for the actual ERC20 tokens. This is the process where ERC20 tokens are minted and sent to users:

      • The function first validates that the user has enough curve tokens to withdraw.
      • It checks to ensure that an ERC20 token has already been deployed for the subject; if not, it triggers the deployment.
      • The curve tokens are transferred from the user to the contract.
      • The corresponding amount of ERC20 tokens is minted by calling the mint function of the actual CurvesERC20 token contract and transfers them to the user.

    The overall process of creating an ERC20 token in this system requires the involvement of an entity that acts as a subject for the curve, and the token creation is part of an ecosystem that includes trading curve tokens, managing special access rights (subjects), and a predefined fee distribution mechanism through the FeeSplitter.

  5. User

    need to detail the trading process and how the fees are handled. Could you explain how a user would buy or sell curve tokens and how the fees are distributed during these transactions?// SPDX-License-Identifier: MIT pragma solidity 0.8.7;

    import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

    import "./CurvesERC20.sol"; import "./CurvesERC20Factory.sol";

    import "./FeeSplitter.sol"; import "./Security.sol";

    interface CurvesErrors { // Access-related error UnauthorizedCurvesTokenSubject(); // Balance-related error InsufficientPayment(); error CannotSendFunds(); error InsufficientBalance(); // ERC20-related error InvalidERC20Metadata(); error ERC20TokenAlreadyMinted(); // State-related error TokenAbsentForCurvesTokenSubject(); error CurveAlreadyExists(); // Transaction-related error LastTokenCannotBeSold(); error ContractCannotReceiveTransfer(); error ExceededMaxBuyAmount(); error NonIntegerDepositAmount(); // Proof-related error UnverifiedProof(); // Presale-related error PresaleUnavailable(); error InvalidPresaleStartTime(); error SaleNotOpen(); // Fee related error InvalidFeeDefinition(); }

    contract Curves is CurvesErrors, Security { address public curvesERC20Factory; FeeSplitter public feeRedistributor; string public constant DEFAULT_NAME = "Curves"; string public constant DEFAULT_SYMBOL = "CURVES"; // Counter for CURVES tokens minted uint256 private _curvesTokenCounter = 0;

    struct ExternalTokenMeta {
        string name;
        string symbol;
        address token;
    }
    
    struct PresaleMeta {
        uint256 startTime;
        bytes32 merkleRoot;
        uint256 maxBuy;
    }
    
    mapping(address => ExternalTokenMeta) public externalCurvesTokens;
    mapping(address => address) public externalCurvesToSubject;
    mapping(string => address) public symbolToSubject;
    
    mapping(address => PresaleMeta) public presalesMeta;
    mapping(address => mapping(address => uint256)) public presalesBuys;
    
    struct FeesEconomics {
        address protocolFeeDestination;
        uint256 protocolFeePercent;
        uint256 subjectFeePercent;
        uint256 referralFeePercent;
        uint256 holdersFeePercent;
        uint256 maxFeePercent;
    }
    
    FeesEconomics public feesEconomics;
    mapping(address => address) public referralFeeDestination;
    
    event Trade(
        address trader,
        address subject,
        bool isBuy,
        uint256 tokenAmount,
        uint256 ethAmount,
        uint256 protocolEthAmount,
        uint256 subjectEthAmount,
        uint256 supply
    );
    
    event Transfer(address indexed curvesTokenSubject, address indexed from, address indexed to, uint256 value);
    event WhitelistUpdated(address indexed presale, bytes32 indexed root);
    event TokenDeployed(address indexed curvesTokenSubject, address indexed erc20token, string name, string symbol);
    
    // TokenSubject => (Holder => Balance)
    mapping(address => mapping(address => uint256)) public curvesTokenBalance;
    
    // TokenSubject => Supply
    mapping(address => uint256) public curvesTokenSupply;
    
    mapping(address => address[]) private ownedCurvesTokenSubjects;
    
    modifier onlyTokenSubject(address curvesTokenSubject) {
        if (curvesTokenSubject != msg.sender) revert UnauthorizedCurvesTokenSubject();
        _;
    }
    
    constructor(address curvesERC20Factory_, address feeRedistributor_) Security() {
        curvesERC20Factory = curvesERC20Factory_;
        feeRedistributor = FeeSplitter(payable(feeRedistributor_));
    }
    
    function setFeeRedistributor(address feeRedistributor_) external onlyOwner {
        feeRedistributor = FeeSplitter(payable(feeRedistributor_));
    }
    
    function setMaxFeePercent(uint256 maxFeePercent_) external onlyManager {
        if (
            feesEconomics.protocolFeePercent +
                feesEconomics.subjectFeePercent +
                feesEconomics.referralFeePercent +
                feesEconomics.holdersFeePercent >
            maxFeePercent_
        ) revert InvalidFeeDefinition();
        feesEconomics.maxFeePercent = maxFeePercent_;
    }
    
    function setProtocolFeePercent(uint256 protocolFeePercent_, address protocolFeeDestination_) external onlyOwner {
        if (
            protocolFeePercent_ +
                feesEconomics.subjectFeePercent +
                feesEconomics.referralFeePercent +
                feesEconomics.holdersFeePercent >
            feesEconomics.maxFeePercent ||
            protocolFeeDestination_ == address(0)
        ) revert InvalidFeeDefinition();
        feesEconomics.protocolFeePercent = protocolFeePercent_;
        feesEconomics.protocolFeeDestination = protocolFeeDestination_;
    }
    
    function setExternalFeePercent(
        uint256 subjectFeePercent_,
        uint256 referralFeePercent_,
        uint256 holdersFeePercent_
    ) external onlyManager {
        if (
            feesEconomics.protocolFeePercent + subjectFeePercent_ + referralFeePercent_ + holdersFeePercent_ >
            feesEconomics.maxFeePercent
        ) revert InvalidFeeDefinition();
        feesEconomics.subjectFeePercent = subjectFeePercent_;
        feesEconomics.referralFeePercent = referralFeePercent_;
        feesEconomics.holdersFeePercent = holdersFeePercent_;
    }
    
    function setReferralFeeDestination(
        address curvesTokenSubject,
        address referralFeeDestination_
    ) public onlyTokenSubject(curvesTokenSubject) {
        referralFeeDestination[curvesTokenSubject] = referralFeeDestination_;
    }
    
    function setERC20Factory(address factory_) external onlyOwner {
        curvesERC20Factory = factory_;
    }
    
    function getFees(
        uint256 price
    )
        public
        view
        returns (uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holdersFee, uint256 totalFee)
    {
        protocolFee = (price * feesEconomics.protocolFeePercent) / 1 ether;
        subjectFee = (price * feesEconomics.subjectFeePercent) / 1 ether;
        referralFee = (price * feesEconomics.referralFeePercent) / 1 ether;
        holdersFee = (price * feesEconomics.holdersFeePercent) / 1 ether;
        totalFee = protocolFee + subjectFee + referralFee + holdersFee;
    }
    
    function getPrice(uint256 supply, uint256 amount) public pure returns (uint256) {
        uint256 sum1 = supply == 0 ? 0 : ((supply - 1) * (supply) * (2 * (supply - 1) + 1)) / 6;
        uint256 sum2 = supply == 0 && amount == 1
            ? 0
            : ((supply - 1 + amount) * (supply + amount) * (2 * (supply - 1 + amount) + 1)) / 6;
        uint256 summation = sum2 - sum1;
        return (summation * 1 ether) / 16000;
    }
    
    function getBuyPrice(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        return getPrice(curvesTokenSupply[curvesTokenSubject], amount);
    }
    
    function getSellPrice(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        return getPrice(curvesTokenSupply[curvesTokenSubject] - amount, amount);
    }
    
    function getBuyPriceAfterFee(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        uint256 price = getBuyPrice(curvesTokenSubject, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        return price + totalFee;
    }
    
    function getSellPriceAfterFee(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        uint256 price = getSellPrice(curvesTokenSubject, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        return price - totalFee;
    }
    
    function buyCurvesToken(address curvesTokenSubject, uint256 amount) public payable {
        uint256 startTime = presalesMeta[curvesTokenSubject].startTime;
        if (startTime != 0 && startTime >= block.timestamp) revert SaleNotOpen();
    
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function _transferFees(
        address curvesTokenSubject,
        bool isBuy,
        uint256 price,
        uint256 amount,
        uint256 supply
    ) internal {
        (uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holderFee, ) = getFees(price);
        {
            bool referralDefined = referralFeeDestination[curvesTokenSubject] != address(0);
            {
                address firstDestination = isBuy ? feesEconomics.protocolFeeDestination : msg.sender;
                uint256 buyValue = referralDefined ? protocolFee : protocolFee + referralFee;
                uint256 sellValue = price - protocolFee - subjectFee - referralFee - holderFee;
                (bool success1, ) = firstDestination.call{value: isBuy ? buyValue : sellValue}("");
                if (!success1) revert CannotSendFunds();
            }
            {
                (bool success2, ) = curvesTokenSubject.call{value: subjectFee}("");
                if (!success2) revert CannotSendFunds();
            }
            {
                (bool success3, ) = referralDefined
                    ? referralFeeDestination[curvesTokenSubject].call{value: referralFee}("")
                    : (true, bytes(""));
                if (!success3) revert CannotSendFunds();
            }
    
            if (feesEconomics.holdersFeePercent > 0 && address(feeRedistributor) != address(0)) {
                feeRedistributor.onBalanceChange(curvesTokenSubject, msg.sender);
                feeRedistributor.addFees{value: holderFee}(curvesTokenSubject);
            }
        }
        emit Trade(
            msg.sender,
            curvesTokenSubject,
            isBuy,
            amount,
            price,
            protocolFee,
            subjectFee,
            isBuy ? supply + amount : supply - amount
        );
    }
    
    function _buyCurvesToken(address curvesTokenSubject, uint256 amount) internal {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (!(supply > 0 || curvesTokenSubject == msg.sender)) revert UnauthorizedCurvesTokenSubject();
    
        uint256 price = getPrice(supply, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        if (msg.value < price + totalFee) revert InsufficientPayment();
    
        curvesTokenBalance[curvesTokenSubject][msg.sender] += amount;
        curvesTokenSupply[curvesTokenSubject] = supply + amount;
        _transferFees(curvesTokenSubject, true, price, amount, supply);
    
        // If is the first token bought, add to the list of owned tokens
        if (curvesTokenBalance[curvesTokenSubject][msg.sender] - amount == 0) {
            _addOwnedCurvesTokenSubject(msg.sender, curvesTokenSubject);
        }
    }
    
    function sellCurvesToken(address curvesTokenSubject, uint256 amount) public {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply <= amount) revert LastTokenCannotBeSold();
        if (curvesTokenBalance[curvesTokenSubject][msg.sender] < amount) revert InsufficientBalance();
    
        uint256 price = getPrice(supply - amount, amount);
    
        curvesTokenBalance[curvesTokenSubject][msg.sender] -= amount;
        curvesTokenSupply[curvesTokenSubject] = supply - amount;
    
        _transferFees(curvesTokenSubject, false, price, amount, supply);
    }
    
    // Transfers tokens from current owner to receiver. Can be used for gifting or distributing tokens.
    function transferCurvesToken(address curvesTokenSubject, address to, uint256 amount) external {
        if (to == address(this)) revert ContractCannotReceiveTransfer();
        _transfer(curvesTokenSubject, msg.sender, to, amount);
    }
    
    // Transfer the total balance of all my tokens to another address. Can be used for migrating tokens.
    function transferAllCurvesTokens(address to) external {
        if (to == address(this)) revert ContractCannotReceiveTransfer();
        address[] storage subjects = ownedCurvesTokenSubjects[msg.sender];
        for (uint256 i = 0; i < subjects.length; i++) {
            uint256 amount = curvesTokenBalance[subjects[i]][msg.sender];
            if (amount > 0) {
                _transfer(subjects[i], msg.sender, to, amount);
            }
        }
    }
    
    function _transfer(address curvesTokenSubject, address from, address to, uint256 amount) internal {
        if (amount > curvesTokenBalance[curvesTokenSubject][from]) revert InsufficientBalance();
    
        // If transferring from oneself, skip adding to the list
        if (from != to) {
            _addOwnedCurvesTokenSubject(to, curvesTokenSubject);
        }
    
        curvesTokenBalance[curvesTokenSubject][from] = curvesTokenBalance[curvesTokenSubject][from] - amount;
        curvesTokenBalance[curvesTokenSubject][to] = curvesTokenBalance[curvesTokenSubject][to] + amount;
    
        emit Transfer(curvesTokenSubject, from, to, amount);
    }
    
    // Internal function to add a curvesTokenSubject to the list if not already present
    function _addOwnedCurvesTokenSubject(address owner_, address curvesTokenSubject) internal {
        address[] storage subjects = ownedCurvesTokenSubjects[owner_];
        for (uint256 i = 0; i < subjects.length; i++) {
            if (subjects[i] == curvesTokenSubject) {
                return;
            }
        }
        subjects.push(curvesTokenSubject);
    }
    
    function _deployERC20(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) internal returns (address) {
        // If the token's symbol is CURVES, append a counter value
        if (keccak256(bytes(symbol)) == keccak256(bytes(DEFAULT_SYMBOL))) {
            _curvesTokenCounter += 1;
            name = string(abi.encodePacked(name, " ", Strings.toString(_curvesTokenCounter)));
            symbol = string(abi.encodePacked(symbol, Strings.toString(_curvesTokenCounter)));
        }
    
        if (symbolToSubject[symbol] != address(0)) revert InvalidERC20Metadata();
    
        address tokenContract = CurvesERC20Factory(curvesERC20Factory).deploy(name, symbol, address(this));
    
        externalCurvesTokens[curvesTokenSubject].token = tokenContract;
        externalCurvesTokens[curvesTokenSubject].name = name;
        externalCurvesTokens[curvesTokenSubject].symbol = symbol;
        externalCurvesToSubject[tokenContract] = curvesTokenSubject;
        symbolToSubject[symbol] = curvesTokenSubject;
    
        emit TokenDeployed(curvesTokenSubject, tokenContract, name, symbol);
        return address(tokenContract);
    }
    
    function buyCurvesTokenWithName(
        address curvesTokenSubject,
        uint256 amount,
        string memory name,
        string memory symbol
    ) public payable {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply != 0) revert CurveAlreadyExists();
    
        _buyCurvesToken(curvesTokenSubject, amount);
        _mint(curvesTokenSubject, name, symbol);
    }
    
    function buyCurvesTokenForPresale(
        address curvesTokenSubject,
        uint256 amount,
        uint256 startTime,
        bytes32 merkleRoot,
        uint256 maxBuy
    ) public payable onlyTokenSubject(curvesTokenSubject) {
        if (startTime <= block.timestamp) revert InvalidPresaleStartTime();
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply != 0) revert CurveAlreadyExists();
        presalesMeta[curvesTokenSubject].startTime = startTime;
        presalesMeta[curvesTokenSubject].merkleRoot = merkleRoot;
        presalesMeta[curvesTokenSubject].maxBuy = (maxBuy == 0 ? type(uint256).max : maxBuy);
    
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function setWhitelist(bytes32 merkleRoot) external {
        uint256 supply = curvesTokenSupply[msg.sender];
        if (supply > 1) revert CurveAlreadyExists();
    
        if (presalesMeta[msg.sender].merkleRoot != merkleRoot) {
            presalesMeta[msg.sender].merkleRoot = merkleRoot;
            emit WhitelistUpdated(msg.sender, merkleRoot);
        }
    }
    
    function buyCurvesTokenWhitelisted(
        address curvesTokenSubject,
        uint256 amount,
        bytes32[] memory proof
    ) public payable {
        if (
            presalesMeta[curvesTokenSubject].startTime == 0 ||
            presalesMeta[curvesTokenSubject].startTime <= block.timestamp
        ) revert PresaleUnavailable();
    
        presalesBuys[curvesTokenSubject][msg.sender] += amount;
        uint256 tokenBought = presalesBuys[curvesTokenSubject][msg.sender];
        if (tokenBought > presalesMeta[curvesTokenSubject].maxBuy) revert ExceededMaxBuyAmount();
    
        verifyMerkle(curvesTokenSubject, msg.sender, proof);
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function verifyMerkle(address curvesTokenSubject, address caller, bytes32[] memory proof) public view {
        // Verify merkle proof
        bytes32 leaf = keccak256(abi.encodePacked(caller));
        if (!MerkleProof.verify(proof, presalesMeta[curvesTokenSubject].merkleRoot, leaf)) revert UnverifiedProof();
    }
    
    function setNameAndSymbol(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) external onlyTokenSubject(curvesTokenSubject) {
        if (externalCurvesTokens[curvesTokenSubject].token != address(0)) revert ERC20TokenAlreadyMinted();
        if (symbolToSubject[symbol] != address(0)) revert InvalidERC20Metadata();
        externalCurvesTokens[curvesTokenSubject].name = name;
        externalCurvesTokens[curvesTokenSubject].symbol = symbol;
    }
    
    function mint(address curvesTokenSubject) external onlyTokenSubject(curvesTokenSubject) {
        if (
            keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].name)) ==
            keccak256(abi.encodePacked("")) ||
            keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].symbol)) ==
            keccak256(abi.encodePacked(""))
        ) {
            externalCurvesTokens[curvesTokenSubject].name = DEFAULT_NAME;
            externalCurvesTokens[curvesTokenSubject].symbol = DEFAULT_SYMBOL;
        }
        _mint(
            curvesTokenSubject,
            externalCurvesTokens[curvesTokenSubject].name,
            externalCurvesTokens[curvesTokenSubject].symbol
        );
    }
    
    function _mint(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) internal onlyTokenSubject(curvesTokenSubject) {
        if (externalCurvesTokens[curvesTokenSubject].token != address(0)) revert ERC20TokenAlreadyMinted();
        _deployERC20(curvesTokenSubject, name, symbol);
    }
    
    function withdraw(address curvesTokenSubject, uint256 amount) public {
        if (amount > curvesTokenBalance[curvesTokenSubject][msg.sender]) revert InsufficientBalance();
    
        address externalToken = externalCurvesTokens[curvesTokenSubject].token;
        if (externalToken == address(0)) {
            if (
                keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].name)) ==
                keccak256(abi.encodePacked("")) ||
                keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].symbol)) ==
                keccak256(abi.encodePacked(""))
            ) {
                externalCurvesTokens[curvesTokenSubject].name = DEFAULT_NAME;
                externalCurvesTokens[curvesTokenSubject].symbol = DEFAULT_SYMBOL;
            }
            _deployERC20(
                curvesTokenSubject,
                externalCurvesTokens[curvesTokenSubject].name,
                externalCurvesTokens[curvesTokenSubject].symbol
            );
            externalToken = externalCurvesTokens[curvesTokenSubject].token;
        }
        _transfer(curvesTokenSubject, msg.sender, address(this), amount);
        CurvesERC20(externalToken).mint(msg.sender, amount * 1 ether);
    }
    
    function deposit(address curvesTokenSubject, uint256 amount) public {
        if (amount % 1 ether != 0) revert NonIntegerDepositAmount();
    
        address externalToken = externalCurvesTokens[curvesTokenSubject].token;
        uint256 tokenAmount = amount / 1 ether;
    
        if (externalToken == address(0)) revert TokenAbsentForCurvesTokenSubject();
        if (amount > CurvesERC20(externalToken).balanceOf(msg.sender)) revert InsufficientBalance();
        if (tokenAmount > curvesTokenBalance[curvesTokenSubject][address(this)]) revert InsufficientBalance();
    
        CurvesERC20(externalToken).burn(msg.sender, amount);
        _transfer(curvesTokenSubject, address(this), msg.sender, tokenAmount);
    }
    
    function sellExternalCurvesToken(address curvesTokenSubject, uint256 amount) public {
        if (externalCurvesTokens[curvesTokenSubject].token == address(0)) revert TokenAbsentForCurvesTokenSubject();
    
        deposit(curvesTokenSubject, amount);
        sellCurvesToken(curvesTokenSubject, amount / 1 ether);
    }
    

    }

  6. Assistant

    The trading process for curve tokens within the Curves contract involves buying and selling these tokens based on a bonding curve pricing mechanism. Here's how the process works:

    Buying Curve Tokens

    1. A user calls the buyCurvesToken function, specifying the address of the curvesTokenSubject and the amount of curve tokens they wish to purchase.
    2. The contract checks if the sale is open (i.e., it is not a presale period) by comparing the startTime from presalesMeta with the current block timestamp.
    3. The _buyCurvesToken internal function is called, which performs the following operations:
      • It calculates the price for the specified amount of tokens by calling the getPrice function, which uses the current supply from curvesTokenSupply to determine the cost according to the bonding curve.
      • It calculates the total fees (protocol fee, subject fee, referral fee, and holders fee) associated with the transaction, by calling the getFees function.
      • It checks if the amount of ETH sent (msg.value) is sufficient to cover the price and the total fees.
      • It updates the curvesTokenBalance and curvesTokenSupply to reflect the newly bought tokens.
      • It calls the _transferFees function to handle the distribution of fees.

    Selling Curve Tokens

    1. A user calls the sellCurvesToken function, specifying the address of the curvesTokenSubject and the amount they wish to sell.
    2. The contract checks if the user has enough curve tokens to sell and ensures that the sale will not reduce the supply to zero (as zero-supply curve must not be sold completely).
    3. The getPrice function is called to calculate the value of the tokens that the user wishes to sell.
    4. The _transferFees function is called to handle the distribution of funds.

    Fee Distribution

    The _transferFees internal function handles fee distribution based on whether the transaction is a buy or a sell:

    1. Calls the getFees function to calculate the different fees based on the price of the transaction.
    2. For a buy transaction:
      • It sends the calculated protocol fee (and referral fee, if there's no specific referral) to the protocolFeeDestination.
      • Subsequent fees (subject, referral, and holder fees) are sent to their respective destinations.
      • If there are holder fees and the FeeSplitter is configured, it calls addFees on the FeeSplitter to redistribute those fees to curve token holders and to notify the FeeSplitter of changes affecting the fee distribution.
    3. For a sell transaction:
      • After subtracting the fees from the sale price, the remaining value is sent back to the seller (msg.sender).
      • Subject and referral fees are distributed similarly to the buy transaction.

    Events

    A Trade event is emitted after the transaction concludes, providing details of the trade and the updated supply of curve tokens.

    In summary, the trading process allows users to buy and sell curve tokens, calculating the appropriate prices via a bonding curve formula and ensuring fees are appropriately distributed to protocol, subject, referral, and holders as defined in the FeesEconomics struct. The FeeSplitter contract may be involved for redistributing holder fees.

  7. User

    now show the presale mechanism and the role of the Security contract? // SPDX-License-Identifier: MIT pragma solidity 0.8.7;

    import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

    import "./CurvesERC20.sol"; import "./CurvesERC20Factory.sol";

    import "./FeeSplitter.sol"; import "./Security.sol";

    interface CurvesErrors { // Access-related error UnauthorizedCurvesTokenSubject(); // Balance-related error InsufficientPayment(); error CannotSendFunds(); error InsufficientBalance(); // ERC20-related error InvalidERC20Metadata(); error ERC20TokenAlreadyMinted(); // State-related error TokenAbsentForCurvesTokenSubject(); error CurveAlreadyExists(); // Transaction-related error LastTokenCannotBeSold(); error ContractCannotReceiveTransfer(); error ExceededMaxBuyAmount(); error NonIntegerDepositAmount(); // Proof-related error UnverifiedProof(); // Presale-related error PresaleUnavailable(); error InvalidPresaleStartTime(); error SaleNotOpen(); // Fee related error InvalidFeeDefinition(); }

    contract Curves is CurvesErrors, Security { address public curvesERC20Factory; FeeSplitter public feeRedistributor; string public constant DEFAULT_NAME = "Curves"; string public constant DEFAULT_SYMBOL = "CURVES"; // Counter for CURVES tokens minted uint256 private _curvesTokenCounter = 0;

    struct ExternalTokenMeta {
        string name;
        string symbol;
        address token;
    }
    
    struct PresaleMeta {
        uint256 startTime;
        bytes32 merkleRoot;
        uint256 maxBuy;
    }
    
    mapping(address => ExternalTokenMeta) public externalCurvesTokens;
    mapping(address => address) public externalCurvesToSubject;
    mapping(string => address) public symbolToSubject;
    
    mapping(address => PresaleMeta) public presalesMeta;
    mapping(address => mapping(address => uint256)) public presalesBuys;
    
    struct FeesEconomics {
        address protocolFeeDestination;
        uint256 protocolFeePercent;
        uint256 subjectFeePercent;
        uint256 referralFeePercent;
        uint256 holdersFeePercent;
        uint256 maxFeePercent;
    }
    
    FeesEconomics public feesEconomics;
    mapping(address => address) public referralFeeDestination;
    
    event Trade(
        address trader,
        address subject,
        bool isBuy,
        uint256 tokenAmount,
        uint256 ethAmount,
        uint256 protocolEthAmount,
        uint256 subjectEthAmount,
        uint256 supply
    );
    
    event Transfer(address indexed curvesTokenSubject, address indexed from, address indexed to, uint256 value);
    event WhitelistUpdated(address indexed presale, bytes32 indexed root);
    event TokenDeployed(address indexed curvesTokenSubject, address indexed erc20token, string name, string symbol);
    
    // TokenSubject => (Holder => Balance)
    mapping(address => mapping(address => uint256)) public curvesTokenBalance;
    
    // TokenSubject => Supply
    mapping(address => uint256) public curvesTokenSupply;
    
    mapping(address => address[]) private ownedCurvesTokenSubjects;
    
    modifier onlyTokenSubject(address curvesTokenSubject) {
        if (curvesTokenSubject != msg.sender) revert UnauthorizedCurvesTokenSubject();
        _;
    }
    
    constructor(address curvesERC20Factory_, address feeRedistributor_) Security() {
        curvesERC20Factory = curvesERC20Factory_;
        feeRedistributor = FeeSplitter(payable(feeRedistributor_));
    }
    
    function setFeeRedistributor(address feeRedistributor_) external onlyOwner {
        feeRedistributor = FeeSplitter(payable(feeRedistributor_));
    }
    
    function setMaxFeePercent(uint256 maxFeePercent_) external onlyManager {
        if (
            feesEconomics.protocolFeePercent +
                feesEconomics.subjectFeePercent +
                feesEconomics.referralFeePercent +
                feesEconomics.holdersFeePercent >
            maxFeePercent_
        ) revert InvalidFeeDefinition();
        feesEconomics.maxFeePercent = maxFeePercent_;
    }
    
    function setProtocolFeePercent(uint256 protocolFeePercent_, address protocolFeeDestination_) external onlyOwner {
        if (
            protocolFeePercent_ +
                feesEconomics.subjectFeePercent +
                feesEconomics.referralFeePercent +
                feesEconomics.holdersFeePercent >
            feesEconomics.maxFeePercent ||
            protocolFeeDestination_ == address(0)
        ) revert InvalidFeeDefinition();
        feesEconomics.protocolFeePercent = protocolFeePercent_;
        feesEconomics.protocolFeeDestination = protocolFeeDestination_;
    }
    
    function setExternalFeePercent(
        uint256 subjectFeePercent_,
        uint256 referralFeePercent_,
        uint256 holdersFeePercent_
    ) external onlyManager {
        if (
            feesEconomics.protocolFeePercent + subjectFeePercent_ + referralFeePercent_ + holdersFeePercent_ >
            feesEconomics.maxFeePercent
        ) revert InvalidFeeDefinition();
        feesEconomics.subjectFeePercent = subjectFeePercent_;
        feesEconomics.referralFeePercent = referralFeePercent_;
        feesEconomics.holdersFeePercent = holdersFeePercent_;
    }
    
    function setReferralFeeDestination(
        address curvesTokenSubject,
        address referralFeeDestination_
    ) public onlyTokenSubject(curvesTokenSubject) {
        referralFeeDestination[curvesTokenSubject] = referralFeeDestination_;
    }
    
    function setERC20Factory(address factory_) external onlyOwner {
        curvesERC20Factory = factory_;
    }
    
    function getFees(
        uint256 price
    )
        public
        view
        returns (uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holdersFee, uint256 totalFee)
    {
        protocolFee = (price * feesEconomics.protocolFeePercent) / 1 ether;
        subjectFee = (price * feesEconomics.subjectFeePercent) / 1 ether;
        referralFee = (price * feesEconomics.referralFeePercent) / 1 ether;
        holdersFee = (price * feesEconomics.holdersFeePercent) / 1 ether;
        totalFee = protocolFee + subjectFee + referralFee + holdersFee;
    }
    
    function getPrice(uint256 supply, uint256 amount) public pure returns (uint256) {
        uint256 sum1 = supply == 0 ? 0 : ((supply - 1) * (supply) * (2 * (supply - 1) + 1)) / 6;
        uint256 sum2 = supply == 0 && amount == 1
            ? 0
            : ((supply - 1 + amount) * (supply + amount) * (2 * (supply - 1 + amount) + 1)) / 6;
        uint256 summation = sum2 - sum1;
        return (summation * 1 ether) / 16000;
    }
    
    function getBuyPrice(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        return getPrice(curvesTokenSupply[curvesTokenSubject], amount);
    }
    
    function getSellPrice(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        return getPrice(curvesTokenSupply[curvesTokenSubject] - amount, amount);
    }
    
    function getBuyPriceAfterFee(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        uint256 price = getBuyPrice(curvesTokenSubject, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        return price + totalFee;
    }
    
    function getSellPriceAfterFee(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        uint256 price = getSellPrice(curvesTokenSubject, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        return price - totalFee;
    }
    
    function buyCurvesToken(address curvesTokenSubject, uint256 amount) public payable {
        uint256 startTime = presalesMeta[curvesTokenSubject].startTime;
        if (startTime != 0 && startTime >= block.timestamp) revert SaleNotOpen();
    
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function _transferFees(
        address curvesTokenSubject,
        bool isBuy,
        uint256 price,
        uint256 amount,
        uint256 supply
    ) internal {
        (uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holderFee, ) = getFees(price);
        {
            bool referralDefined = referralFeeDestination[curvesTokenSubject] != address(0);
            {
                address firstDestination = isBuy ? feesEconomics.protocolFeeDestination : msg.sender;
                uint256 buyValue = referralDefined ? protocolFee : protocolFee + referralFee;
                uint256 sellValue = price - protocolFee - subjectFee - referralFee - holderFee;
                (bool success1, ) = firstDestination.call{value: isBuy ? buyValue : sellValue}("");
                if (!success1) revert CannotSendFunds();
            }
            {
                (bool success2, ) = curvesTokenSubject.call{value: subjectFee}("");
                if (!success2) revert CannotSendFunds();
            }
            {
                (bool success3, ) = referralDefined
                    ? referralFeeDestination[curvesTokenSubject].call{value: referralFee}("")
                    : (true, bytes(""));
                if (!success3) revert CannotSendFunds();
            }
    
            if (feesEconomics.holdersFeePercent > 0 && address(feeRedistributor) != address(0)) {
                feeRedistributor.onBalanceChange(curvesTokenSubject, msg.sender);
                feeRedistributor.addFees{value: holderFee}(curvesTokenSubject);
            }
        }
        emit Trade(
            msg.sender,
            curvesTokenSubject,
            isBuy,
            amount,
            price,
            protocolFee,
            subjectFee,
            isBuy ? supply + amount : supply - amount
        );
    }
    
    function _buyCurvesToken(address curvesTokenSubject, uint256 amount) internal {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (!(supply > 0 || curvesTokenSubject == msg.sender)) revert UnauthorizedCurvesTokenSubject();
    
        uint256 price = getPrice(supply, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        if (msg.value < price + totalFee) revert InsufficientPayment();
    
        curvesTokenBalance[curvesTokenSubject][msg.sender] += amount;
        curvesTokenSupply[curvesTokenSubject] = supply + amount;
        _transferFees(curvesTokenSubject, true, price, amount, supply);
    
        // If is the first token bought, add to the list of owned tokens
        if (curvesTokenBalance[curvesTokenSubject][msg.sender] - amount == 0) {
            _addOwnedCurvesTokenSubject(msg.sender, curvesTokenSubject);
        }
    }
    
    function sellCurvesToken(address curvesTokenSubject, uint256 amount) public {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply <= amount) revert LastTokenCannotBeSold();
        if (curvesTokenBalance[curvesTokenSubject][msg.sender] < amount) revert InsufficientBalance();
    
        uint256 price = getPrice(supply - amount, amount);
    
        curvesTokenBalance[curvesTokenSubject][msg.sender] -= amount;
        curvesTokenSupply[curvesTokenSubject] = supply - amount;
    
        _transferFees(curvesTokenSubject, false, price, amount, supply);
    }
    
    // Transfers tokens from current owner to receiver. Can be used for gifting or distributing tokens.
    function transferCurvesToken(address curvesTokenSubject, address to, uint256 amount) external {
        if (to == address(this)) revert ContractCannotReceiveTransfer();
        _transfer(curvesTokenSubject, msg.sender, to, amount);
    }
    
    // Transfer the total balance of all my tokens to another address. Can be used for migrating tokens.
    function transferAllCurvesTokens(address to) external {
        if (to == address(this)) revert ContractCannotReceiveTransfer();
        address[] storage subjects = ownedCurvesTokenSubjects[msg.sender];
        for (uint256 i = 0; i < subjects.length; i++) {
            uint256 amount = curvesTokenBalance[subjects[i]][msg.sender];
            if (amount > 0) {
                _transfer(subjects[i], msg.sender, to, amount);
            }
        }
    }
    
    function _transfer(address curvesTokenSubject, address from, address to, uint256 amount) internal {
        if (amount > curvesTokenBalance[curvesTokenSubject][from]) revert InsufficientBalance();
    
        // If transferring from oneself, skip adding to the list
        if (from != to) {
            _addOwnedCurvesTokenSubject(to, curvesTokenSubject);
        }
    
        curvesTokenBalance[curvesTokenSubject][from] = curvesTokenBalance[curvesTokenSubject][from] - amount;
        curvesTokenBalance[curvesTokenSubject][to] = curvesTokenBalance[curvesTokenSubject][to] + amount;
    
        emit Transfer(curvesTokenSubject, from, to, amount);
    }
    
    // Internal function to add a curvesTokenSubject to the list if not already present
    function _addOwnedCurvesTokenSubject(address owner_, address curvesTokenSubject) internal {
        address[] storage subjects = ownedCurvesTokenSubjects[owner_];
        for (uint256 i = 0; i < subjects.length; i++) {
            if (subjects[i] == curvesTokenSubject) {
                return;
            }
        }
        subjects.push(curvesTokenSubject);
    }
    
    function _deployERC20(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) internal returns (address) {
        // If the token's symbol is CURVES, append a counter value
        if (keccak256(bytes(symbol)) == keccak256(bytes(DEFAULT_SYMBOL))) {
            _curvesTokenCounter += 1;
            name = string(abi.encodePacked(name, " ", Strings.toString(_curvesTokenCounter)));
            symbol = string(abi.encodePacked(symbol, Strings.toString(_curvesTokenCounter)));
        }
    
        if (symbolToSubject[symbol] != address(0)) revert InvalidERC20Metadata();
    
        address tokenContract = CurvesERC20Factory(curvesERC20Factory).deploy(name, symbol, address(this));
    
        externalCurvesTokens[curvesTokenSubject].token = tokenContract;
        externalCurvesTokens[curvesTokenSubject].name = name;
        externalCurvesTokens[curvesTokenSubject].symbol = symbol;
        externalCurvesToSubject[tokenContract] = curvesTokenSubject;
        symbolToSubject[symbol] = curvesTokenSubject;
    
        emit TokenDeployed(curvesTokenSubject, tokenContract, name, symbol);
        return address(tokenContract);
    }
    
    function buyCurvesTokenWithName(
        address curvesTokenSubject,
        uint256 amount,
        string memory name,
        string memory symbol
    ) public payable {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply != 0) revert CurveAlreadyExists();
    
        _buyCurvesToken(curvesTokenSubject, amount);
        _mint(curvesTokenSubject, name, symbol);
    }
    
    function buyCurvesTokenForPresale(
        address curvesTokenSubject,
        uint256 amount,
        uint256 startTime,
        bytes32 merkleRoot,
        uint256 maxBuy
    ) public payable onlyTokenSubject(curvesTokenSubject) {
        if (startTime <= block.timestamp) revert InvalidPresaleStartTime();
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply != 0) revert CurveAlreadyExists();
        presalesMeta[curvesTokenSubject].startTime = startTime;
        presalesMeta[curvesTokenSubject].merkleRoot = merkleRoot;
        presalesMeta[curvesTokenSubject].maxBuy = (maxBuy == 0 ? type(uint256).max : maxBuy);
    
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function setWhitelist(bytes32 merkleRoot) external {
        uint256 supply = curvesTokenSupply[msg.sender];
        if (supply > 1) revert CurveAlreadyExists();
    
        if (presalesMeta[msg.sender].merkleRoot != merkleRoot) {
            presalesMeta[msg.sender].merkleRoot = merkleRoot;
            emit WhitelistUpdated(msg.sender, merkleRoot);
        }
    }
    
    function buyCurvesTokenWhitelisted(
        address curvesTokenSubject,
        uint256 amount,
        bytes32[] memory proof
    ) public payable {
        if (
            presalesMeta[curvesTokenSubject].startTime == 0 ||
            presalesMeta[curvesTokenSubject].startTime <= block.timestamp
        ) revert PresaleUnavailable();
    
        presalesBuys[curvesTokenSubject][msg.sender] += amount;
        uint256 tokenBought = presalesBuys[curvesTokenSubject][msg.sender];
        if (tokenBought > presalesMeta[curvesTokenSubject].maxBuy) revert ExceededMaxBuyAmount();
    
        verifyMerkle(curvesTokenSubject, msg.sender, proof);
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function verifyMerkle(address curvesTokenSubject, address caller, bytes32[] memory proof) public view {
        // Verify merkle proof
        bytes32 leaf = keccak256(abi.encodePacked(caller));
        if (!MerkleProof.verify(proof, presalesMeta[curvesTokenSubject].merkleRoot, leaf)) revert UnverifiedProof();
    }
    
    function setNameAndSymbol(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) external onlyTokenSubject(curvesTokenSubject) {
        if (externalCurvesTokens[curvesTokenSubject].token != address(0)) revert ERC20TokenAlreadyMinted();
        if (symbolToSubject[symbol] != address(0)) revert InvalidERC20Metadata();
        externalCurvesTokens[curvesTokenSubject].name = name;
        externalCurvesTokens[curvesTokenSubject].symbol = symbol;
    }
    
    function mint(address curvesTokenSubject) external onlyTokenSubject(curvesTokenSubject) {
        if (
            keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].name)) ==
            keccak256(abi.encodePacked("")) ||
            keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].symbol)) ==
            keccak256(abi.encodePacked(""))
        ) {
            externalCurvesTokens[curvesTokenSubject].name = DEFAULT_NAME;
            externalCurvesTokens[curvesTokenSubject].symbol = DEFAULT_SYMBOL;
        }
        _mint(
            curvesTokenSubject,
            externalCurvesTokens[curvesTokenSubject].name,
            externalCurvesTokens[curvesTokenSubject].symbol
        );
    }
    
    function _mint(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) internal onlyTokenSubject(curvesTokenSubject) {
        if (externalCurvesTokens[curvesTokenSubject].token != address(0)) revert ERC20TokenAlreadyMinted();
        _deployERC20(curvesTokenSubject, name, symbol);
    }
    
    function withdraw(address curvesTokenSubject, uint256 amount) public {
        if (amount > curvesTokenBalance[curvesTokenSubject][msg.sender]) revert InsufficientBalance();
    
        address externalToken = externalCurvesTokens[curvesTokenSubject].token;
        if (externalToken == address(0)) {
            if (
                keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].name)) ==
                keccak256(abi.encodePacked("")) ||
                keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].symbol)) ==
                keccak256(abi.encodePacked(""))
            ) {
                externalCurvesTokens[curvesTokenSubject].name = DEFAULT_NAME;
                externalCurvesTokens[curvesTokenSubject].symbol = DEFAULT_SYMBOL;
            }
            _deployERC20(
                curvesTokenSubject,
                externalCurvesTokens[curvesTokenSubject].name,
                externalCurvesTokens[curvesTokenSubject].symbol
            );
            externalToken = externalCurvesTokens[curvesTokenSubject].token;
        }
        _transfer(curvesTokenSubject, msg.sender, address(this), amount);
        CurvesERC20(externalToken).mint(msg.sender, amount * 1 ether);
    }
    
    function deposit(address curvesTokenSubject, uint256 amount) public {
        if (amount % 1 ether != 0) revert NonIntegerDepositAmount();
    
        address externalToken = externalCurvesTokens[curvesTokenSubject].token;
        uint256 tokenAmount = amount / 1 ether;
    
        if (externalToken == address(0)) revert TokenAbsentForCurvesTokenSubject();
        if (amount > CurvesERC20(externalToken).balanceOf(msg.sender)) revert InsufficientBalance();
        if (tokenAmount > curvesTokenBalance[curvesTokenSubject][address(this)]) revert InsufficientBalance();
    
        CurvesERC20(externalToken).burn(msg.sender, amount);
        _transfer(curvesTokenSubject, address(this), msg.sender, tokenAmount);
    }
    
    function sellExternalCurvesToken(address curvesTokenSubject, uint256 amount) public {
        if (externalCurvesTokens[curvesTokenSubject].token == address(0)) revert TokenAbsentForCurvesTokenSubject();
    
        deposit(curvesTokenSubject, amount);
        sellCurvesToken(curvesTokenSubject, amount / 1 ether);
    }
    

    }

  8. Assistant

    The Curves contract provides a mechanism for conducting presales of curve tokens. A presale allows specific users to buy tokens before the general public sale opens. Here's how the presale mechanism works:

    Presale Setup

    1. A subject, which is typically the creator or an authorized entity of a curve, initiates a presale by calling buyCurvesTokenForPresale. This function requires the caller to be the subject of the curve (onlyTokenSubject modifier checks this) and allows them to set:
      • The startTime for the presale.
      • A merkleRoot, which enables on-chain verification of off-chain whitelists using Merkle Proofs.
      • A maxBuy limit, which is the maximum number of tokens a whitelisted address can purchase during the presale.

    Whitelist Updating

    1. The setWhitelist function allows the subject to update the merkleRoot representing the whitelist, changing the set of addresses allowed to participate in the presale.

    Presale Participation

    1. A whitelisted user participates in the presale by calling buyCurvesTokenWhitelisted. They must send enough ETH to cover the cost and fees of the requested number of tokens and provide a valid Merkle Proof with bytes32[] proof.
    2. The contract verifies the Merkle Proof using the verifyMerkle function to check the user's eligibility for the presale based on the merkleRoot.
    3. The contract checks if the amount to be bought does not exceed the user’s maxBuy limit.
    4. If all checks pass, the user can purchase the tokens at the presale price, and the contract handles the buy similarly to non-presale buys, including any fees distribution.

    Security Contract Role

    The Security contract, which Curves extends, appears to employ an access control pattern used for role-based access restrictions. Although its detailed contents are not provided, it likely features modifiers or functions like onlyOwner, onlyManager, or similar constructs for enforcing security by allowing only authorized users to perform certain actions.

    Thus, the Security contract’s role might include:

    1. Restricting presale initiation, fee setting, and other sensitive actions to specific roles, such as owner or manager.
    2. Ensuring only the subject or authorized accounts can update presale metadata or mint ERC20 tokens.

    The Curves contract depends on the base Security contract to provide a security model, ensuring operations that can impact the economics of curve tokens are accessed only by permitted roles. This helps maintain the integrity and fairness of the token ecosystem, especially during sensitive periods like presales.

  9. User

    so i review the contract and i find some vulnerabilities confirm with evidence that are valid and correct or they are valid and not correct give evidence and give the vulnerable lines for every valid vulnerabilities -issue 1 eentrancy Attackhigh

    The contract functions that transfer Ether, such as _transferFees, do not follow the Checks-Effects-Interactions pattern, which could potentially make them vulnerable to reentrancy attacks. In a reentrancy attack, a malicious contract could call back into the Curves contract before the initial execution is finished, possibly leading to unexpected behavior like withdrawing funds multiple times.

    Does the contract implement reentrancy guards such as the nonReentrant modifier for functions that transfer Ether? issue 2 Integer Overflow and Underflowmedium

    The contract functions that perform arithmetic operations, such as getPrice, do not appear to use SafeMath or check for overflows and underflows. This could lead to integer overflow or underflow, where the actual value of a variable wraps around the maximum or minimum value it can store, resulting in incorrect calculations and potentially allowing an attacker to exploit the contract logic to their advantage.

    Are arithmetic operations in the contract protected against integer overflow and underflow using libraries like SafeMath?- -issue 3Denial of Service (DoS) via Block Gas Limitmedium

    The contract's _transferFees function includes multiple Ether transfers and external calls to potentially untrusted contracts, which could lead to a Denial of Service (DoS) attack if any of these calls consume too much gas or always fail. An attacker could exploit this by becoming a fee recipient and creating a contract that always reverts or consumes all the gas, preventing the Curves contract from successfully completing transactions.

    Are there any safeguards in place to prevent external calls in the _transferFees function from failing due to excessive gas consumption or always reverting, which could lead to a DoS condition? -issue 4Front-Running Attackmedium

    The contract's trading functions, such as buyCurvesToken and sellCurvesToken, are vulnerable to front-running attacks. In a front-running attack, a malicious actor observes a pending transaction and then issues their own transaction with a higher gas price to have it included in the blockchain first. This can be exploited in trading scenarios to gain an advantage, for example, by buying tokens just before a large buy order is processed, and then selling them at a higher price immediately after.

    Does the contract have any mechanisms in place to prevent front-running attacks, such as transaction ordering or commit-reveal schemes? -issue 5 Improper Access Controlhigh

    The contract functions that should be restricted to certain roles, such as setFeeRedistributor, setMaxFeePercent, and setProtocolFeePercent, may be improperly protected. If the Security contract's access control is not correctly implemented or if there are flaws in how these functions check permissions, an unauthorized user could potentially change critical contract settings, leading to loss of funds or disruption of the contract's intended behavior.

    Are all administrative functions in the contract, such as those for setting fees and redistributors, properly protected by the Security contract's access control mechanisms? here is the contract // SPDX-License-Identifier: MIT pragma solidity 0.8.7;

    import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

    import "./CurvesERC20.sol"; import "./CurvesERC20Factory.sol";

    import "./FeeSplitter.sol"; import "./Security.sol";

    interface CurvesErrors { // Access-related error UnauthorizedCurvesTokenSubject(); // Balance-related error InsufficientPayment(); error CannotSendFunds(); error InsufficientBalance(); // ERC20-related error InvalidERC20Metadata(); error ERC20TokenAlreadyMinted(); // State-related error TokenAbsentForCurvesTokenSubject(); error CurveAlreadyExists(); // Transaction-related error LastTokenCannotBeSold(); error ContractCannotReceiveTransfer(); error ExceededMaxBuyAmount(); error NonIntegerDepositAmount(); // Proof-related error UnverifiedProof(); // Presale-related error PresaleUnavailable(); error InvalidPresaleStartTime(); error SaleNotOpen(); // Fee related error InvalidFeeDefinition(); }

    contract Curves is CurvesErrors, Security { address public curvesERC20Factory; FeeSplitter public feeRedistributor; string public constant DEFAULT_NAME = "Curves"; string public constant DEFAULT_SYMBOL = "CURVES"; // Counter for CURVES tokens minted uint256 private _curvesTokenCounter = 0;

    struct ExternalTokenMeta {
        string name;
        string symbol;
        address token;
    }
    
    struct PresaleMeta {
        uint256 startTime;
        bytes32 merkleRoot;
        uint256 maxBuy;
    }
    
    mapping(address => ExternalTokenMeta) public externalCurvesTokens;
    mapping(address => address) public externalCurvesToSubject;
    mapping(string => address) public symbolToSubject;
    
    mapping(address => PresaleMeta) public presalesMeta;
    mapping(address => mapping(address => uint256)) public presalesBuys;
    
    struct FeesEconomics {
        address protocolFeeDestination;
        uint256 protocolFeePercent;
        uint256 subjectFeePercent;
        uint256 referralFeePercent;
        uint256 holdersFeePercent;
        uint256 maxFeePercent;
    }
    
    FeesEconomics public feesEconomics;
    mapping(address => address) public referralFeeDestination;
    
    event Trade(
        address trader,
        address subject,
        bool isBuy,
        uint256 tokenAmount,
        uint256 ethAmount,
        uint256 protocolEthAmount,
        uint256 subjectEthAmount,
        uint256 supply
    );
    
    event Transfer(address indexed curvesTokenSubject, address indexed from, address indexed to, uint256 value);
    event WhitelistUpdated(address indexed presale, bytes32 indexed root);
    event TokenDeployed(address indexed curvesTokenSubject, address indexed erc20token, string name, string symbol);
    
    // TokenSubject => (Holder => Balance)
    mapping(address => mapping(address => uint256)) public curvesTokenBalance;
    
    // TokenSubject => Supply
    mapping(address => uint256) public curvesTokenSupply;
    
    mapping(address => address[]) private ownedCurvesTokenSubjects;
    
    modifier onlyTokenSubject(address curvesTokenSubject) {
        if (curvesTokenSubject != msg.sender) revert UnauthorizedCurvesTokenSubject();
        _;
    }
    
    constructor(address curvesERC20Factory_, address feeRedistributor_) Security() {
        curvesERC20Factory = curvesERC20Factory_;
        feeRedistributor = FeeSplitter(payable(feeRedistributor_));
    }
    
    function setFeeRedistributor(address feeRedistributor_) external onlyOwner {
        feeRedistributor = FeeSplitter(payable(feeRedistributor_));
    }
    
    function setMaxFeePercent(uint256 maxFeePercent_) external onlyManager {
        if (
            feesEconomics.protocolFeePercent +
                feesEconomics.subjectFeePercent +
                feesEconomics.referralFeePercent +
                feesEconomics.holdersFeePercent >
            maxFeePercent_
        ) revert InvalidFeeDefinition();
        feesEconomics.maxFeePercent = maxFeePercent_;
    }
    
    function setProtocolFeePercent(uint256 protocolFeePercent_, address protocolFeeDestination_) external onlyOwner {
        if (
            protocolFeePercent_ +
                feesEconomics.subjectFeePercent +
                feesEconomics.referralFeePercent +
                feesEconomics.holdersFeePercent >
            feesEconomics.maxFeePercent ||
            protocolFeeDestination_ == address(0)
        ) revert InvalidFeeDefinition();
        feesEconomics.protocolFeePercent = protocolFeePercent_;
        feesEconomics.protocolFeeDestination = protocolFeeDestination_;
    }
    
    function setExternalFeePercent(
        uint256 subjectFeePercent_,
        uint256 referralFeePercent_,
        uint256 holdersFeePercent_
    ) external onlyManager {
        if (
            feesEconomics.protocolFeePercent + subjectFeePercent_ + referralFeePercent_ + holdersFeePercent_ >
            feesEconomics.maxFeePercent
        ) revert InvalidFeeDefinition();
        feesEconomics.subjectFeePercent = subjectFeePercent_;
        feesEconomics.referralFeePercent = referralFeePercent_;
        feesEconomics.holdersFeePercent = holdersFeePercent_;
    }
    
    function setReferralFeeDestination(
        address curvesTokenSubject,
        address referralFeeDestination_
    ) public onlyTokenSubject(curvesTokenSubject) {
        referralFeeDestination[curvesTokenSubject] = referralFeeDestination_;
    }
    
    function setERC20Factory(address factory_) external onlyOwner {
        curvesERC20Factory = factory_;
    }
    
    function getFees(
        uint256 price
    )
        public
        view
        returns (uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holdersFee, uint256 totalFee)
    {
        protocolFee = (price * feesEconomics.protocolFeePercent) / 1 ether;
        subjectFee = (price * feesEconomics.subjectFeePercent) / 1 ether;
        referralFee = (price * feesEconomics.referralFeePercent) / 1 ether;
        holdersFee = (price * feesEconomics.holdersFeePercent) / 1 ether;
        totalFee = protocolFee + subjectFee + referralFee + holdersFee;
    }
    
    function getPrice(uint256 supply, uint256 amount) public pure returns (uint256) {
        uint256 sum1 = supply == 0 ? 0 : ((supply - 1) * (supply) * (2 * (supply - 1) + 1)) / 6;
        uint256 sum2 = supply == 0 && amount == 1
            ? 0
            : ((supply - 1 + amount) * (supply + amount) * (2 * (supply - 1 + amount) + 1)) / 6;
        uint256 summation = sum2 - sum1;
        return (summation * 1 ether) / 16000;
    }
    
    function getBuyPrice(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        return getPrice(curvesTokenSupply[curvesTokenSubject], amount);
    }
    
    function getSellPrice(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        return getPrice(curvesTokenSupply[curvesTokenSubject] - amount, amount);
    }
    
    function getBuyPriceAfterFee(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        uint256 price = getBuyPrice(curvesTokenSubject, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        return price + totalFee;
    }
    
    function getSellPriceAfterFee(address curvesTokenSubject, uint256 amount) public view returns (uint256) {
        uint256 price = getSellPrice(curvesTokenSubject, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        return price - totalFee;
    }
    
    function buyCurvesToken(address curvesTokenSubject, uint256 amount) public payable {
        uint256 startTime = presalesMeta[curvesTokenSubject].startTime;
        if (startTime != 0 && startTime >= block.timestamp) revert SaleNotOpen();
    
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function _transferFees(
        address curvesTokenSubject,
        bool isBuy,
        uint256 price,
        uint256 amount,
        uint256 supply
    ) internal {
        (uint256 protocolFee, uint256 subjectFee, uint256 referralFee, uint256 holderFee, ) = getFees(price);
        {
            bool referralDefined = referralFeeDestination[curvesTokenSubject] != address(0);
            {
                address firstDestination = isBuy ? feesEconomics.protocolFeeDestination : msg.sender;
                uint256 buyValue = referralDefined ? protocolFee : protocolFee + referralFee;
                uint256 sellValue = price - protocolFee - subjectFee - referralFee - holderFee;
                (bool success1, ) = firstDestination.call{value: isBuy ? buyValue : sellValue}("");
                if (!success1) revert CannotSendFunds();
            }
            {
                (bool success2, ) = curvesTokenSubject.call{value: subjectFee}("");
                if (!success2) revert CannotSendFunds();
            }
            {
                (bool success3, ) = referralDefined
                    ? referralFeeDestination[curvesTokenSubject].call{value: referralFee}("")
                    : (true, bytes(""));
                if (!success3) revert CannotSendFunds();
            }
    
            if (feesEconomics.holdersFeePercent > 0 && address(feeRedistributor) != address(0)) {
                feeRedistributor.onBalanceChange(curvesTokenSubject, msg.sender);
                feeRedistributor.addFees{value: holderFee}(curvesTokenSubject);
            }
        }
        emit Trade(
            msg.sender,
            curvesTokenSubject,
            isBuy,
            amount,
            price,
            protocolFee,
            subjectFee,
            isBuy ? supply + amount : supply - amount
        );
    }
    
    function _buyCurvesToken(address curvesTokenSubject, uint256 amount) internal {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (!(supply > 0 || curvesTokenSubject == msg.sender)) revert UnauthorizedCurvesTokenSubject();
    
        uint256 price = getPrice(supply, amount);
        (, , , , uint256 totalFee) = getFees(price);
    
        if (msg.value < price + totalFee) revert InsufficientPayment();
    
        curvesTokenBalance[curvesTokenSubject][msg.sender] += amount;
        curvesTokenSupply[curvesTokenSubject] = supply + amount;
        _transferFees(curvesTokenSubject, true, price, amount, supply);
    
        // If is the first token bought, add to the list of owned tokens
        if (curvesTokenBalance[curvesTokenSubject][msg.sender] - amount == 0) {
            _addOwnedCurvesTokenSubject(msg.sender, curvesTokenSubject);
        }
    }
    
    function sellCurvesToken(address curvesTokenSubject, uint256 amount) public {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply <= amount) revert LastTokenCannotBeSold();
        if (curvesTokenBalance[curvesTokenSubject][msg.sender] < amount) revert InsufficientBalance();
    
        uint256 price = getPrice(supply - amount, amount);
    
        curvesTokenBalance[curvesTokenSubject][msg.sender] -= amount;
        curvesTokenSupply[curvesTokenSubject] = supply - amount;
    
        _transferFees(curvesTokenSubject, false, price, amount, supply);
    }
    
    // Transfers tokens from current owner to receiver. Can be used for gifting or distributing tokens.
    function transferCurvesToken(address curvesTokenSubject, address to, uint256 amount) external {
        if (to == address(this)) revert ContractCannotReceiveTransfer();
        _transfer(curvesTokenSubject, msg.sender, to, amount);
    }
    
    // Transfer the total balance of all my tokens to another address. Can be used for migrating tokens.
    function transferAllCurvesTokens(address to) external {
        if (to == address(this)) revert ContractCannotReceiveTransfer();
        address[] storage subjects = ownedCurvesTokenSubjects[msg.sender];
        for (uint256 i = 0; i < subjects.length; i++) {
            uint256 amount = curvesTokenBalance[subjects[i]][msg.sender];
            if (amount > 0) {
                _transfer(subjects[i], msg.sender, to, amount);
            }
        }
    }
    
    function _transfer(address curvesTokenSubject, address from, address to, uint256 amount) internal {
        if (amount > curvesTokenBalance[curvesTokenSubject][from]) revert InsufficientBalance();
    
        // If transferring from oneself, skip adding to the list
        if (from != to) {
            _addOwnedCurvesTokenSubject(to, curvesTokenSubject);
        }
    
        curvesTokenBalance[curvesTokenSubject][from] = curvesTokenBalance[curvesTokenSubject][from] - amount;
        curvesTokenBalance[curvesTokenSubject][to] = curvesTokenBalance[curvesTokenSubject][to] + amount;
    
        emit Transfer(curvesTokenSubject, from, to, amount);
    }
    
    // Internal function to add a curvesTokenSubject to the list if not already present
    function _addOwnedCurvesTokenSubject(address owner_, address curvesTokenSubject) internal {
        address[] storage subjects = ownedCurvesTokenSubjects[owner_];
        for (uint256 i = 0; i < subjects.length; i++) {
            if (subjects[i] == curvesTokenSubject) {
                return;
            }
        }
        subjects.push(curvesTokenSubject);
    }
    
    function _deployERC20(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) internal returns (address) {
        // If the token's symbol is CURVES, append a counter value
        if (keccak256(bytes(symbol)) == keccak256(bytes(DEFAULT_SYMBOL))) {
            _curvesTokenCounter += 1;
            name = string(abi.encodePacked(name, " ", Strings.toString(_curvesTokenCounter)));
            symbol = string(abi.encodePacked(symbol, Strings.toString(_curvesTokenCounter)));
        }
    
        if (symbolToSubject[symbol] != address(0)) revert InvalidERC20Metadata();
    
        address tokenContract = CurvesERC20Factory(curvesERC20Factory).deploy(name, symbol, address(this));
    
        externalCurvesTokens[curvesTokenSubject].token = tokenContract;
        externalCurvesTokens[curvesTokenSubject].name = name;
        externalCurvesTokens[curvesTokenSubject].symbol = symbol;
        externalCurvesToSubject[tokenContract] = curvesTokenSubject;
        symbolToSubject[symbol] = curvesTokenSubject;
    
        emit TokenDeployed(curvesTokenSubject, tokenContract, name, symbol);
        return address(tokenContract);
    }
    
    function buyCurvesTokenWithName(
        address curvesTokenSubject,
        uint256 amount,
        string memory name,
        string memory symbol
    ) public payable {
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply != 0) revert CurveAlreadyExists();
    
        _buyCurvesToken(curvesTokenSubject, amount);
        _mint(curvesTokenSubject, name, symbol);
    }
    
    function buyCurvesTokenForPresale(
        address curvesTokenSubject,
        uint256 amount,
        uint256 startTime,
        bytes32 merkleRoot,
        uint256 maxBuy
    ) public payable onlyTokenSubject(curvesTokenSubject) {
        if (startTime <= block.timestamp) revert InvalidPresaleStartTime();
        uint256 supply = curvesTokenSupply[curvesTokenSubject];
        if (supply != 0) revert CurveAlreadyExists();
        presalesMeta[curvesTokenSubject].startTime = startTime;
        presalesMeta[curvesTokenSubject].merkleRoot = merkleRoot;
        presalesMeta[curvesTokenSubject].maxBuy = (maxBuy == 0 ? type(uint256).max : maxBuy);
    
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function setWhitelist(bytes32 merkleRoot) external {
        uint256 supply = curvesTokenSupply[msg.sender];
        if (supply > 1) revert CurveAlreadyExists();
    
        if (presalesMeta[msg.sender].merkleRoot != merkleRoot) {
            presalesMeta[msg.sender].merkleRoot = merkleRoot;
            emit WhitelistUpdated(msg.sender, merkleRoot);
        }
    }
    
    function buyCurvesTokenWhitelisted(
        address curvesTokenSubject,
        uint256 amount,
        bytes32[] memory proof
    ) public payable {
        if (
            presalesMeta[curvesTokenSubject].startTime == 0 ||
            presalesMeta[curvesTokenSubject].startTime <= block.timestamp
        ) revert PresaleUnavailable();
    
        presalesBuys[curvesTokenSubject][msg.sender] += amount;
        uint256 tokenBought = presalesBuys[curvesTokenSubject][msg.sender];
        if (tokenBought > presalesMeta[curvesTokenSubject].maxBuy) revert ExceededMaxBuyAmount();
    
        verifyMerkle(curvesTokenSubject, msg.sender, proof);
        _buyCurvesToken(curvesTokenSubject, amount);
    }
    
    function verifyMerkle(address curvesTokenSubject, address caller, bytes32[] memory proof) public view {
        // Verify merkle proof
        bytes32 leaf = keccak256(abi.encodePacked(caller));
        if (!MerkleProof.verify(proof, presalesMeta[curvesTokenSubject].merkleRoot, leaf)) revert UnverifiedProof();
    }
    
    function setNameAndSymbol(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) external onlyTokenSubject(curvesTokenSubject) {
        if (externalCurvesTokens[curvesTokenSubject].token != address(0)) revert ERC20TokenAlreadyMinted();
        if (symbolToSubject[symbol] != address(0)) revert InvalidERC20Metadata();
        externalCurvesTokens[curvesTokenSubject].name = name;
        externalCurvesTokens[curvesTokenSubject].symbol = symbol;
    }
    
    function mint(address curvesTokenSubject) external onlyTokenSubject(curvesTokenSubject) {
        if (
            keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].name)) ==
            keccak256(abi.encodePacked("")) ||
            keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].symbol)) ==
            keccak256(abi.encodePacked(""))
        ) {
            externalCurvesTokens[curvesTokenSubject].name = DEFAULT_NAME;
            externalCurvesTokens[curvesTokenSubject].symbol = DEFAULT_SYMBOL;
        }
        _mint(
            curvesTokenSubject,
            externalCurvesTokens[curvesTokenSubject].name,
            externalCurvesTokens[curvesTokenSubject].symbol
        );
    }
    
    function _mint(
        address curvesTokenSubject,
        string memory name,
        string memory symbol
    ) internal onlyTokenSubject(curvesTokenSubject) {
        if (externalCurvesTokens[curvesTokenSubject].token != address(0)) revert ERC20TokenAlreadyMinted();
        _deployERC20(curvesTokenSubject, name, symbol);
    }
    
    function withdraw(address curvesTokenSubject, uint256 amount) public {
        if (amount > curvesTokenBalance[curvesTokenSubject][msg.sender]) revert InsufficientBalance();
    
        address externalToken = externalCurvesTokens[curvesTokenSubject].token;
        if (externalToken == address(0)) {
            if (
                keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].name)) ==
                keccak256(abi.encodePacked("")) ||
                keccak256(abi.encodePacked(externalCurvesTokens[curvesTokenSubject].symbol)) ==
                keccak256(abi.encodePacked(""))
            ) {
                externalCurvesTokens[curvesTokenSubject].name = DEFAULT_NAME;
                externalCurvesTokens[curvesTokenSubject].symbol = DEFAULT_SYMBOL;
            }
            _deployERC20(
                curvesTokenSubject,
                externalCurvesTokens[curvesTokenSubject].name,
                externalCurvesTokens[curvesTokenSubject].symbol
            );
            externalToken = externalCurvesTokens[curvesTokenSubject].token;
        }
        _transfer(curvesTokenSubject, msg.sender, address(this), amount);
        CurvesERC20(externalToken).mint(msg.sender, amount * 1 ether);
    }
    
    function deposit(address curvesTokenSubject, uint256 amount) public {
        if (amount % 1 ether != 0) revert NonIntegerDepositAmount();
    
        address externalToken = externalCurvesTokens[curvesTokenSubject].token;
        uint256 tokenAmount = amount / 1 ether;
    
        if (externalToken == address(0)) revert TokenAbsentForCurvesTokenSubject();
        if (amount > CurvesERC20(externalToken).balanceOf(msg.sender)) revert InsufficientBalance();
        if (tokenAmount > curvesTokenBalance[curvesTokenSubject][address(this)]) revert InsufficientBalance();
    
        CurvesERC20(externalToken).burn(msg.sender, amount);
        _transfer(curvesTokenSubject, address(this), msg.sender, tokenAmount);
    }
    
    function sellExternalCurvesToken(address curvesTokenSubject, uint256 amount) public {
        if (externalCurvesTokens[curvesTokenSubject].token == address(0)) revert TokenAbsentForCurvesTokenSubject();
    
        deposit(curvesTokenSubject, amount);
        sellCurvesToken(curvesTokenSubject, amount / 1 ether);
    }
    

    }

  10. Assistant

    Let's address each vulnerability issue one by one:

    Issue 1: Reentrancy Attack

    Evidence:

    • The _transferFees function uses direct calls to send Ether (through .call{value: ...}), which is prone to reentrancy if the recipient is a contract that has a fallback or receive function.

    Vulnerable Line(s):

    • Within _transferFees function, multiple lines have direct Ether transfers without reentrancy protection, such as:
      • (bool success1, ) = firstDestination.call{value: isBuy ? buyValue : sellValue}("");
      • (bool success2, ) = curvesTokenSubject.call{value: subjectFee}("");
      • (bool success3, ) = referralDefined ? referralFeeDestination[curvesTokenSubject].call{value: referralFee}("") : (true, bytes(""));

    Correctness:

    • Valid and Correct. There is no reentrancy guard used, like OpenZeppelin's nonReentrant modifier.

    Issue 2: Integer Overflow and Underflow

    Evidence:

    • The contract utilizes arithmetic operations like multiplication and division to calculate prices and fees.

    Vulnerable Line(s):

    • Within getPrice function, there are arithmetic operations performed without SafeMath, for example:
      • uint256 summation = sum2 - sum1;

    Correctness:

    • Valid but not correct. Since Solidity version 0.8.0 and above, overflows and underflows are checked by default, throwing an error on such conditions. Hence, manual checks or SafeMath are not needed for this contract using Solidity 0.8.7.

    Issue 3: Denial of Service (DoS) via Block Gas Limit

    Evidence:

    • The _transferFees function makes several calls to send Ether which could fail if the recipients are contracts designed to revert transactions or consume all gas.

    Vulnerable Line(s):

    • Same lines as mentioned in Issue 1 can be considered for this issue as well.

    Correctness:

    • Valid and Correct. If an address receiving funds is set to a contract that always reverts or consumes all gas, it can block these calls.

    Issue 4: Front-Running Attack

    Evidence:

    • Functions buyCurvesToken and sellCurvesToken handle financial transactions based on input parameters that may be visible in the transaction pool before being mined.

    Vulnerable Line(s):

    • The entire functions (buyCurvesToken and sellCurvesToken) may be susceptible to front-running due to the nature of public blockchains.

    Correctness:

    • Valid and Correct. No inherent mechanism is implemented in the contract to prevent front-running. It's a limitation of the Ethereum blockchain without additional mitigations like commit-reveal schemes, private transactions, or ordering transactions by other criteria than gas price.

    Issue 5: Improper Access Control

    Evidence:

    • The contract inherits from Security contract and uses modifiers like onlyOwner and onlyManager for access control.

    Vulnerable Line(s):

    • Any function that uses these modifiers (e.g., setMaxFeePercent, setProtocolFeePercent) could be vulnerable if the Security contract is improperly implemented.

    Correctness:

    • Valid but requires further review. This issue cannot be determined from the provided code alone; the implementation details of the Security contract are crucial. Assuming the access control mechanisms provided by the Security contract are correctly implemented and used, the access control would be valid.

    The reported vulnerabilities each point to real concerns that should be addressed, except for Issue 2, since overflows and underflows are automatically checked in Solidity versions 0.8 and above. Issues 1, 3, 4, and 5 are either valid as presented or, in the case of Issue 5, would require further information from the Security contract to make a definitive assessment.

  11. User

    prove with evidence the vulnerabilities are valid or invalid

  12. Assistant

    Let's evaluate each of the vulnerabilities for validity:

    Issue 1: Reentrancy Attack

    Solidity versions prior to 0.8 introduced nonReentrant modifier to guard against reentrancy attacks. Given the contract version is 0.8.7 and no nonReentrant modifier or similar guard is used, the vulnerability is valid if the receiving address of Ether transfers is a contract with fallback or receive function that implements reentrancy. This can lead to reentrancy attacks, where the malicious contract calls back into the Curves contract.

    Evidence:

    • No usage of nonReentrant modifier or checks that prevent reentrant calls in the _transferFees function.

    Validity:

    • Valid. The provided functions like _transferFees could indeed be vulnerable to reentrancy.

    Issue 2: Integer Overflow and Underflow

    Starting from Solidity version 0.8.0, arithmetic operations are checked by default for overflows and underflows, causing a revert if any occur.

    Evidence:

    • Solidity documentation from version 0.8.0 explicitly states arithmetic operations are checked by default.
    • The Curves contract uses Solidity version 0.8.7.

    Validity:

    • Invalid. Arithmetic operations in Solidity 0.8.x automatically check for overflows and underflows, making SafeMath or similar checks unnecessary.

    Issue 3: Denial of Service (DoS) via Block Gas Limit

    The _transferFees function contains multiple Ether transfers, which could potentially be problematic if the called contract consumes excessive gas or always reverts.

    Evidence:

    • Use of .call{value: ...} to transfer Ether without additional checks or fallback mechanisms.

    Validity:

    • Valid. Multiple Ether transfers to external addresses without strict gas limits could potentially result in DoS, especially if these addresses are contracts designed to consume all available gas or revert transactions.

    Issue 4: Front-Running Attack

    The contract's trading functions can be observed in the public mempool before being executed, leading to possible front-running, where an attacker might benefit from seeing pending transactions.

    Evidence:

    • Public blockchain nature and mempool visibility.
    • No commit-reveal scheme or other front-running protection mechanisms in the contract code.

    Validity:

    • Valid. Front-running is an inherent risk due to blockchain transparency, and the contract has not implemented measures to prevent it.

    Issue 5: Improper Access Control

    Without having access to the Security contract source code, we cannot definitively say whether the access control is implemented correctly. However, as an informed assumption, if the Security contract is taken from a reputable source like OpenZeppelin and is correctly used, the access control should be proper.

    Evidence:

    • The contract uses onlyOwner and onlyManager modifiers for sensitive functions.

    Validity:

    • Cannot be definitively determined without reviewing the Security contract. The presence of access control modifiers implies an attempt at proper access control is made, but without the code for Security, the effectiveness of these controls cannot be evaluated.

    In conclusion, after reviewing and analyzing the contract code:

    • Issue 1 (Reentrancy) is valid due to the absence of reentrancy protection mechanisms.
    • Issue 2 (Integer Overflow/Underflow) is invalid, as Solidity 0.8.x performs automatic checks.
    • Issue 3 (DoS via Block Gas Limit) is valid; the contract could be vulnerable to DoS.
    • Issue 4 (Front-Running Attack) is valid due to the public nature of blockchain transactions.
    • Issue 5 (Improper Access Control) cannot be definitively assessed without the Security contract.
  13. User

    give the vulnerable line with evidence for the vulnerability are valid

  14. Assistant

    Let's go through the issues that were determined to be valid and pinpoint the vulnerable lines in the provided contract code, including evidence for each vulnerability:

    Issue 1: Reentrancy Attack

    Vulnerable Line(s):

    _transferFees(curvesTokenSubject, true, price, amount, supply);
    

    Evidence:

    • Lines within the _transferFees function include multiple .call usage for sending Ether, such as (bool success1, ) = firstDestination.call{value: isBuy ? buyValue : sellValue}("");, and others that could potentially allow a reentrancy attack if the recipient is a malicious contract.

    Issue 3: Denial of Service (DoS) via Block Gas Limit

    Vulnerable Line(s):

    • Same as Issue 1, the _transferFees function:
    (bool success1, ) = firstDestination.call{value: isBuy ? buyValue : sellValue}("");
    (bool success2, ) = curvesTokenSubject.call{value: subjectFee}("");
    (bool success3, ) = referralDefined ? referralFeeDestination[curvesTokenSubject].call{value: referralFee}("") : (true, bytes(""));
    

    Evidence:

    • If any of the recipients is a contract designed to consume a lot of gas or always revert transactions, it could lead transactions to fail or run out of gas, blocking the normal processing in the _transferFees function.

    Issue 4: Front-Running Attack

    Vulnerable Line(s):

    • buyCurvesToken and sellCurvesToken functions for buying/selling tokens:
    function buyCurvesToken(address curvesTokenSubject, uint256 amount) public payable { ... }
    function sellCurvesToken(address curvesTokenSubject, uint256 amount) public { ... }
    

    Evidence:

    • These functions do not have any inherent mechanisms to prevent possible front-running attacks, which are a known risk with public blockchain transactions that can be seen in the mempool.

    Note on Issue 5: Improper Access Control

    • As previously mentioned, this issue's validity cannot be assessed without the source code for the Security contract. If the Security contract's access control mechanisms are flawed or not enforced correctly, then lines like setFeeRedistributor, setMaxFeePercent, and setProtocolFeePercent using the onlyOwner or onlyManager modifiers would be vulnerable.

    These are the lines vulnerable to the confirmed issues based on the contract code provided. As a best practice, smart contract developers should ensure that they are using reentrancy guards, consider gas consumption and fail-safeness of external calls, and implement measures to mitigate front-running wherever applicable.