Contract Name:
CashVerseTreasury
Contract Source Code:
<i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
} <i class='far fa-question-circle text-muted ms-2' data-bs-trigger='hover' data-bs-toggle='tooltip' data-bs-html='true' data-bs-title='Click on the check box to select individual contract to compare. Only 1 contract can be selected from each side.'></i>
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract CashVerseTreasury is Ownable, ReentrancyGuard {
IUniswapV2Router02 public uniswapV2Router;
ISwapRouter public uniswapV3Router;
address public WETH;
address public profitWallet;
uint256 public totalDeposited;
uint256 public totalProfits;
uint256 public totalParticipants;
uint256 public minDeposit = 0.03 ether;
uint256 public maxParticipants = 25;
uint256 public pendingProfitWithdrawal;
struct User {
uint256 deposited;
uint256 claimableProfits;
uint256 depositIndex;
}
struct TokenInfo {
uint256 ethSpent;
uint256 tokensBought;
uint256 tokenPriceAtBuy;
uint256 tokensSold;
uint256 ethReceived;
uint256 totalProfit;
uint256 totalLoss;
}
mapping(address => User) public users;
mapping(address => TokenInfo) public tokenInfo;
address[] public userList;
event Deposited(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event TokenBought(
address indexed user,
uint256 amountSpent,
address tokenAddress,
bool withTax,
bool isV3
);
event TokenSold(
address indexed user,
uint256 amountReceived,
address tokenAddress,
bool initialSell,
bool withTax,
bool isV3
);
event ProfitDistributed(uint256 totalProfit);
event EmergencyWithdrawal(address tokenAddress, uint256 amount);
modifier onlyParticipants() {
require(users[msg.sender].deposited > 0, "Not a participant");
_;
}
constructor(
address _uniswapV2Router,
address _uniswapV3Router,
address _weth,
address _profitWallet
) {
uniswapV2Router = IUniswapV2Router02(_uniswapV2Router);
uniswapV3Router = ISwapRouter(_uniswapV3Router);
WETH = _weth;
profitWallet = _profitWallet;
}
function deposit() external payable nonReentrant {
require(msg.value >= minDeposit, "Minimum deposit not met");
require(
totalParticipants < maxParticipants,
"Participant limit reached"
);
if (users[msg.sender].deposited == 0) {
users[msg.sender].depositIndex = userList.length;
userList.push(msg.sender);
totalParticipants++;
}
users[msg.sender].deposited += msg.value;
totalDeposited += msg.value;
emit Deposited(msg.sender, msg.value);
}
function withdraw(uint256 amount) external nonReentrant onlyParticipants {
User storage user = users[msg.sender];
require(user.deposited >= amount, "Insufficient balance");
uint256 totalLoss = calculateTotalLoss();
uint256 adjustedAmount = (address(this).balance *
(user.deposited - totalLoss)) / totalDeposited;
require(adjustedAmount >= amount, "Insufficient contract balance");
user.deposited -= amount;
totalDeposited -= amount;
if (user.deposited == 0) {
uint256 index = user.depositIndex;
address lastUser = userList[userList.length - 1];
userList[index] = lastUser;
users[lastUser].depositIndex = index;
userList.pop();
totalParticipants--;
}
payable(msg.sender).transfer(amount);
emit Withdrawn(msg.sender, amount);
}
function buyToken(
address tokenAddress,
uint256 percentage,
bool withTax,
bool isV3,
uint24 fee // For Uniswap v3
) external onlyOwner nonReentrant {
require(percentage > 0 && percentage <= 100, "Invalid percentage");
uint256 ethAmount = (address(this).balance * percentage) / 100;
require(ethAmount <= address(this).balance, "Insufficient ETH balance");
uint256 tokensBought = executeBuy(
tokenAddress,
ethAmount,
withTax,
isV3,
fee
);
uint256 tokenPrice = (ethAmount * 1e18) / tokensBought;
tokenInfo[tokenAddress].ethSpent += ethAmount;
tokenInfo[tokenAddress].tokensBought += tokensBought;
tokenInfo[tokenAddress].tokenPriceAtBuy = tokenPrice;
uint256 gasSpent = tx.gasprice * gasleft();
tokenInfo[tokenAddress].totalLoss += gasSpent;
// Deduct ETH spent proportionally from users' deposits
for (uint256 i = 0; i < userList.length; i++) {
address userAddress = userList[i];
User storage user = users[userAddress];
uint256 userShare = (ethAmount * user.deposited) / totalDeposited;
user.deposited -= userShare;
}
totalDeposited -= ethAmount;
emit TokenBought(msg.sender, ethAmount, tokenAddress, withTax, isV3);
}
function sellToken(
address tokenAddress,
uint256 percentage,
bool initialSell,
bool withTax,
bool isV3,
uint24 fee // For Uniswap v3
) external onlyOwner nonReentrant {
require(percentage > 0 && percentage <= 100, "Invalid percentage");
TokenInfo storage info = tokenInfo[tokenAddress];
uint256 tokenAmount;
uint256 ethReceived;
if (initialSell) {
uint256 ethAmount = info.ethSpent;
tokenAmount = (ethAmount * 1e18) / info.tokenPriceAtBuy;
} else {
tokenAmount = (info.tokensBought * percentage) / 100;
}
require(tokenAmount > 0, "Token amount must be greater than zero");
// Ensure allowance is set
uint256 currentAllowance = IERC20(tokenAddress).allowance(
address(this),
address(uniswapV2Router)
);
if (currentAllowance < tokenAmount) {
IERC20(tokenAddress).approve(address(uniswapV2Router), tokenAmount);
}
ethReceived = executeSell(
tokenAddress,
tokenAmount,
withTax,
isV3,
fee
);
info.tokensSold += tokenAmount;
info.ethReceived += ethReceived;
uint256 gasSpent = tx.gasprice * gasleft();
info.totalLoss += gasSpent;
if (initialSell) {
totalDeposited -= ethReceived;
pendingProfitWithdrawal += ethReceived;
} else {
uint256 profit = ethReceived > info.ethSpent
? ethReceived - info.ethSpent
: 0;
uint256 loss = info.ethSpent > ethReceived
? info.ethSpent - ethReceived
: 0;
info.totalProfit += profit;
info.totalLoss += loss;
totalProfits += profit;
distributeProfits(profit);
}
emit TokenSold(
msg.sender,
ethReceived,
tokenAddress,
initialSell,
withTax,
isV3
);
}
function executeBuy(
address tokenAddress,
uint256 ethAmount,
bool withTax,
bool isV3,
uint24 fee
) internal returns (uint256) {
uint256 tokensBought;
if (isV3) {
// Uniswap v3 buy
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
.ExactInputSingleParams({
tokenIn: WETH,
tokenOut: tokenAddress,
fee: fee,
recipient: address(this),
deadline: block.timestamp,
amountIn: ethAmount,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
tokensBought = uniswapV3Router.exactInputSingle{value: ethAmount}(
params
);
} else {
// Uniswap v2 buy
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = tokenAddress;
if (withTax) {
uniswapV2Router
.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: ethAmount
}(0, path, address(this), block.timestamp);
tokensBought = IERC20(tokenAddress).balanceOf(address(this));
} else {
uint256[] memory amounts = uniswapV2Router
.swapExactETHForTokens{value: ethAmount}(
0,
path,
address(this),
block.timestamp
);
tokensBought = amounts[1];
}
}
return tokensBought;
}
function executeSell(
address tokenAddress,
uint256 tokenAmount,
bool withTax,
bool isV3,
uint24 fee
) internal returns (uint256) {
uint256 ethReceived;
if (isV3) {
// Uniswap v3 sell
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
.ExactInputSingleParams({
tokenIn: tokenAddress,
tokenOut: WETH,
fee: fee,
recipient: address(this),
deadline: block.timestamp,
amountIn: tokenAmount,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
ethReceived = uniswapV3Router.exactInputSingle(params);
} else {
// Uniswap v2 sell
address[] memory path = new address[](2);
path[0] = tokenAddress;
path[1] = uniswapV2Router.WETH();
if (withTax) {
uniswapV2Router
.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
ethReceived = address(this).balance;
} else {
uint256[] memory amounts = uniswapV2Router
.swapExactTokensForETH(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
ethReceived = amounts[1];
}
}
return ethReceived;
}
function distributeProfits(uint256 profit) internal {
uint256 profitForDistribution = (profit * 50) / 100;
uint256 profitForContract = (profit * 10) / 100;
uint256 profitForWallet = profit -
profitForDistribution -
profitForContract;
pendingProfitWithdrawal += profitForWallet;
for (uint256 i = 0; i < userList.length; i++) {
address userAddress = userList[i];
User storage user = users[userAddress];
uint256 userShare = (profitForDistribution * user.deposited) /
totalDeposited;
user.claimableProfits += userShare;
}
totalDeposited += profitForContract;
emit ProfitDistributed(profit);
}
function claimProfits() external nonReentrant onlyParticipants {
User storage user = users[msg.sender];
uint256 claimable = user.claimableProfits;
require(claimable > 0, "No profits to claim");
user.claimableProfits = 0;
payable(msg.sender).transfer(claimable);
emit Withdrawn(msg.sender, claimable);
}
function getTokenInfo(
address tokenAddress
) external view returns (TokenInfo memory) {
return tokenInfo[tokenAddress];
}
function getMaxParticipants() external view returns (uint256) {
return maxParticipants;
}
function getRemainingParticipants() external view returns (uint256) {
return maxParticipants - totalParticipants;
}
function setMaxParticipants(uint256 _maxParticipants) external onlyOwner {
maxParticipants = _maxParticipants;
}
function setMinDeposit(uint256 _minDeposit) external onlyOwner {
minDeposit = _minDeposit;
}
function checkWithdrawableAmount()
external
view
onlyParticipants
returns (uint256)
{
User storage user = users[msg.sender];
uint256 totalLoss = calculateTotalLoss();
uint256 withdrawable = user.deposited -
(totalLoss * user.deposited) /
totalDeposited;
return withdrawable;
}
function withdrawExcessETH(
uint256 percentage
) external onlyOwner nonReentrant {
require(percentage > 0 && percentage <= 100, "Invalid percentage");
uint256 totalDepositorBalance = address(this).balance - totalDeposited;
uint256 withdrawAmount = (totalDepositorBalance * percentage) / 100;
require(withdrawAmount > 0, "No excess ETH to withdraw");
payable(owner()).transfer(withdrawAmount);
}
function emergencyWithdrawToken(address tokenAddress) external onlyOwner {
uint256 tokenBalance = IERC20(tokenAddress).balanceOf(address(this));
require(tokenBalance > 0, "No tokens to withdraw");
IERC20(tokenAddress).transfer(owner(), tokenBalance);
emit EmergencyWithdrawal(tokenAddress, tokenBalance);
}
function withdrawAllETH() external onlyOwner nonReentrant {
uint256 balance = address(this).balance;
require(balance > 0, "No ETH to withdraw");
payable(owner()).transfer(balance);
}
function withdrawPendingProfits() external onlyOwner nonReentrant {
require(pendingProfitWithdrawal > 0, "No pending profits to withdraw");
uint256 amountToWithdraw = pendingProfitWithdrawal;
pendingProfitWithdrawal = 0;
payable(profitWallet).transfer(amountToWithdraw);
}
function calculateTotalLoss() internal view returns (uint256) {
uint256 totalLoss = 0;
for (uint256 i = 0; i < userList.length; i++) {
address userAddress = userList[i];
totalLoss +=
users[userAddress].deposited *
tokenInfo[userAddress].totalLoss;
}
return totalLoss;
}
}