// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import…
- 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?
- 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
ownerandmanagerto protect function calls withonlyOwneroronlyManagermodifiers.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
FeesEconomicssetup. -
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.
- 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); }}
- Assistant
In the provided
Curvescontract, 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:-
Initialization: The constructor of the
Curvescontract receives the address of theCurvesERC20Factoryand theFeeSplittercontract, storing these addresses in state variables for later use. -
Buy and Mint Process: A user can trigger the creation of a new ERC20 token by calling either the
buyCurvesTokenWithNameor themintfunction, both of which require the caller to be the subject of the curve—this is verified using theonlyTokenSubjectmodifier. 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).buyCurvesTokenWithNameallows 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.mintcreates 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.
-
Token Deployment (_deployERC20): The actual creation step of the ERC20 token behind the scenes is done in the internal
_deployERC20function. It takes thecurvesTokenSubject, the desiredname, andsymbol, 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
deployfunction from the CurvesERC20Factory instance, which creates a new CurvesERC20 token contract. - The newly deployed ERC20 token contract's address is stored in the
externalCurvesTokensmapping, associating it with thecurvesTokenSubject. Also, mappingsexternalCurvesToSubjectandsymbolToSubjectare updated to track the relationship between the token, its subject, and its symbol. - An
TokenDeployedevent is emitted to log the creation.
-
Token Minting (withdraw): The
withdrawfunction 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
mintfunction of the actualCurvesERC20token 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. -
- 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); }}
- Assistant
The trading process for curve tokens within the
Curvescontract involves buying and selling these tokens based on a bonding curve pricing mechanism. Here's how the process works:Buying Curve Tokens
- A user calls the
buyCurvesTokenfunction, specifying the address of thecurvesTokenSubjectand theamountof curve tokens they wish to purchase. - The contract checks if the sale is open (i.e., it is not a presale period) by comparing the
startTimefrompresalesMetawith the current block timestamp. - The
_buyCurvesTokeninternal function is called, which performs the following operations:- It calculates the price for the specified amount of tokens by calling the
getPricefunction, which uses the current supply fromcurvesTokenSupplyto 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
getFeesfunction. - It checks if the amount of ETH sent (
msg.value) is sufficient to cover the price and the total fees. - It updates the
curvesTokenBalanceandcurvesTokenSupplyto reflect the newly bought tokens. - It calls the
_transferFeesfunction to handle the distribution of fees.
- It calculates the price for the specified amount of tokens by calling the
Selling Curve Tokens
- A user calls the
sellCurvesTokenfunction, specifying the address of thecurvesTokenSubjectand the amount they wish to sell. - 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).
- The
getPricefunction is called to calculate the value of the tokens that the user wishes to sell. - The
_transferFeesfunction is called to handle the distribution of funds.
Fee Distribution
The
_transferFeesinternal function handles fee distribution based on whether the transaction is a buy or a sell:- Calls the
getFeesfunction to calculate the different fees based on the price of the transaction. - 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
FeeSplitteris configured, it callsaddFeeson theFeeSplitterto redistribute those fees to curve token holders and to notify theFeeSplitterof changes affecting the fee distribution.
- It sends the calculated protocol fee (and referral fee, if there's no specific referral) to the
- 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.
- After subtracting the fees from the sale price, the remaining value is sent back to the seller (
Events
A
Tradeevent 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
FeesEconomicsstruct. TheFeeSplittercontract may be involved for redistributing holder fees. - A user calls the
- 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); }}
- Assistant
The
Curvescontract 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
- 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 (onlyTokenSubjectmodifier checks this) and allows them to set:- The
startTimefor the presale. - A
merkleRoot, which enables on-chain verification of off-chain whitelists using Merkle Proofs. - A
maxBuylimit, which is the maximum number of tokens a whitelisted address can purchase during the presale.
- The
Whitelist Updating
- The
setWhitelistfunction allows the subject to update themerkleRootrepresenting the whitelist, changing the set of addresses allowed to participate in the presale.
Presale Participation
- 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 withbytes32[] proof. - The contract verifies the Merkle Proof using the
verifyMerklefunction to check the user's eligibility for the presale based on themerkleRoot. - The contract checks if the amount to be bought does not exceed the user’s
maxBuylimit. - 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
Securitycontract, whichCurvesextends, 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 likeonlyOwner,onlyManager, or similar constructs for enforcing security by allowing only authorized users to perform certain actions.Thus, the
Securitycontract’s role might include:- Restricting presale initiation, fee setting, and other sensitive actions to specific roles, such as owner or manager.
- Ensuring only the subject or authorized accounts can update presale metadata or mint ERC20 tokens.
The
Curvescontract depends on the baseSecuritycontract 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. - A subject, which is typically the creator or an authorized entity of a curve, initiates a presale by calling
- 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); }}
- Assistant
Let's address each vulnerability issue one by one:
Issue 1: Reentrancy Attack
Evidence:
- The
_transferFeesfunction 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
_transferFeesfunction, 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
nonReentrantmodifier.
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
getPricefunction, 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
_transferFeesfunction 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
buyCurvesTokenandsellCurvesTokenhandle financial transactions based on input parameters that may be visible in the transaction pool before being mined.
Vulnerable Line(s):
- The entire functions (
buyCurvesTokenandsellCurvesToken) 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
Securitycontract and uses modifiers likeonlyOwnerandonlyManagerfor access control.
Vulnerable Line(s):
- Any function that uses these modifiers (e.g.,
setMaxFeePercent,setProtocolFeePercent) could be vulnerable if theSecuritycontract is improperly implemented.
Correctness:
- Valid but requires further review. This issue cannot be determined from the provided code alone; the implementation details of the
Securitycontract are crucial. Assuming the access control mechanisms provided by theSecuritycontract 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
Securitycontract to make a definitive assessment. - The
- User
prove with evidence the vulnerabilities are valid or invalid
- Assistant
Let's evaluate each of the vulnerabilities for validity:
Issue 1: Reentrancy Attack
Solidity versions prior to 0.8 introduced
nonReentrantmodifier to guard against reentrancy attacks. Given the contract version is 0.8.7 and nononReentrantmodifier 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 theCurvescontract.Evidence:
- No usage of
nonReentrantmodifier or checks that prevent reentrant calls in the_transferFeesfunction.
Validity:
- Valid. The provided functions like
_transferFeescould 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
Curvescontract 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
_transferFeesfunction 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
Securitycontract source code, we cannot definitively say whether the access control is implemented correctly. However, as an informed assumption, if theSecuritycontract is taken from a reputable source like OpenZeppelin and is correctly used, the access control should be proper.Evidence:
- The contract uses
onlyOwnerandonlyManagermodifiers for sensitive functions.
Validity:
- Cannot be definitively determined without reviewing the
Securitycontract. The presence of access control modifiers implies an attempt at proper access control is made, but without the code forSecurity, 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
Securitycontract.
- No usage of
- User
give the vulnerable line with evidence for the vulnerability are valid
- 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
_transferFeesfunction include multiple.callusage 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
_transferFeesfunction:
(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
_transferFeesfunction.
Issue 4: Front-Running Attack
Vulnerable Line(s):
buyCurvesTokenandsellCurvesTokenfunctions 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
Securitycontract. If theSecuritycontract's access control mechanisms are flawed or not enforced correctly, then lines likesetFeeRedistributor,setMaxFeePercent, andsetProtocolFeePercentusing theonlyOwneroronlyManagermodifiers 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.
- Lines within the