Contract Name:
LuckyOrRekt
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) (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.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
} <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>
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} <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.4;
interface ITaxContract {
function distribute(uint amount) external;
function gather(uint amount) 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: MIT
pragma solidity ^0.8.0;
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint
);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) 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: MIT
pragma solidity ^0.8.0;
interface IUniswapV2Router02 {
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 removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) 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: MIT
pragma solidity =0.8.24;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./interfaces/IUniswapV2Factory.sol";
import "./interfaces/IUniswapV2Router02.sol";
import "./interfaces/ITaxContract.sol";
import "./RandomnessProvider.sol";
/*
Lucky or Rekt ($YOLO)
*/
contract LuckyOrRekt is Context, IERC20, Ownable {
using Address for address payable;
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
address payable public taxContractAddress;
RandomnessProvider public randomnessProvider;
uint private _buyTax = 30;
uint private _sellTax = 30;
uint private _preventSwapBefore = 30;
// Lucky or Rekt Configuration Parameters
uint public lossChance = 60; // 60% chance of loss (rekt)
uint public winChance = 40; // 40% chance of win (lucky)
// Range configuration struct
struct Range {
uint percent; // Percentage of this range within the scenario
uint multiplier; // Penalty percentage (for loss) or bonus percentage (for win)
}
// Loss (Rekt) Configuration - 5 ranges
Range[5] public lossRanges;
// Win (Lucky) Configuration - 5 ranges
Range[5] public winRanges;
// Burn configuration for losses
uint public burnPercentageOnLoss = 30; // 30% of penalty tokens are burned, rest to tax contract
// Minimum balance protection (percentage of bought amount that must remain)
uint public minBalancePercentage = 50; // 50% of bought amount must remain
// Maximum bonus cap (percentage of total supply that can be minted as bonus)
uint public maxBonusPercentage = 10; // 10% of total supply max per bonus
uint8 private constant _decimals = 8;
uint private _totalSupply = 1_000_000_000 * 10 ** _decimals;
string private constant _name = unicode"Lucky or Rekt";
string private constant _symbol = unicode"YOLO";
uint public _maxTxAmount = (_totalSupply * 135) / 10000; // 1.35%
uint public _maxWalletSize = (_totalSupply * 135) / 10000; // 1.35%
uint public _swapThreshold = _totalSupply / 1000;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
address public routerAddress;
bool private tradingOpen;
uint public launchBlock;
bool private inSwap = false;
bool private swapEnabled = false;
bool private inLuckyOrRekt = false; // Reentrancy protection for Lucky or Rekt
// Emergency controls - starts disabled by default
bool public luckyOrRektPaused = true;
address public lastBuyer;
uint public lastBoughtAmount;
// Track minimum balance required for pending lucky or rekt effects
mapping(address => uint) public pendingMinBalance;
// Track total tokens burned and minted from Lucky or Rekt effects
uint public totalBurned = 0; // Total tokens burned from Rekt effects
uint public totalMinted = 0; // Total tokens minted from Lucky effects
event MaxTxAmountUpdated(uint _maxTxAmount);
event LuckyOrRekted(
address indexed buyer,
uint boughtAmount,
int256 percentageModifier,
uint modifiedAmount,
bool isLucky
);
event TaxContractCallFailed(address indexed buyer, uint amount);
modifier lockTheSwap() {
inSwap = true;
_;
inSwap = false;
}
constructor(address _taxContractAddress, address _randomnessProvider) {
taxContractAddress = payable(_taxContractAddress);
randomnessProvider = RandomnessProvider(_randomnessProvider);
_balances[_msgSender()] = _totalSupply;
// Set default router address for Ethereum Sepolia
// Update this for different networks:
// BASE: 0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24
// ETHEREUM MAINNET: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
_isExcludedFromFee[_msgSender()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_taxContractAddress] = true;
// Initialize loss ranges with default values (more likely to lose big)
lossRanges[0] = Range(10, 5); // 10% chance, -5% penalty (small loss, rare)
lossRanges[1] = Range(20, 15); // 20% chance, -15% penalty
lossRanges[2] = Range(30, 25); // 30% chance, -25% penalty
lossRanges[3] = Range(25, 35); // 25% chance, -35% penalty
lossRanges[4] = Range(15, 50); // 15% chance, -50% penalty (big loss, more common)
// Initialize win ranges with default values (less likely to win big)
winRanges[0] = Range(40, 5); // 40% chance, +5% bonus (small win, common)
winRanges[1] = Range(30, 10); // 30% chance, +10% bonus
winRanges[2] = Range(20, 20); // 20% chance, +20% bonus
winRanges[3] = Range(8, 50); // 8% chance, +50% bonus (rare)
winRanges[4] = Range(2, 100); // 2% chance, +100% bonus (very rare jackpot)
// Validate that ranges add up to 100%
uint totalLossPercent = 0;
uint totalWinPercent = 0;
for (uint i = 0; i < 5; i++) {
totalLossPercent += lossRanges[i].percent;
totalWinPercent += winRanges[i].percent;
}
require(totalLossPercent == 100, "Loss ranges must add up to 100%");
require(totalWinPercent == 100, "Win ranges must add up to 100%");
emit Transfer(address(0), _msgSender(), _totalSupply);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint) {
return _balances[account];
}
function transfer(
address recipient,
uint amount
) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(
address owner,
address spender
) public view override returns (uint) {
return _allowances[owner][spender];
}
function approve(
address spender,
uint amount
) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function _approve(address owner, address spender, uint amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
// Determine if current transaction is a buy to check against lastBuyer
// Note: This detection works for Uniswap V2 direct swaps, may need adjustment for V3 or aggregators
address currentBuyer;
bool isSell = (to == uniswapV2Pair && from != address(this));
// Improved buy detection with additional safety checks
if (
from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
to != address(this) &&
to != uniswapV2Pair &&
to != taxContractAddress &&
!Address.isContract(to) &&
to != address(0) // Additional safety check
) {
// this is a buy - from pair to EOA (not router or other contract)
currentBuyer = to;
}
// Check if sender has pending lucky or rekt effect and prevent draining below minimum
// Exception: Allow sells - they will clear the pending status
if (
pendingMinBalance[from] > 0 && !_isExcludedFromFee[from] && !isSell
) {
uint balanceAfterTransfer = _balances[from].sub(amount);
require(
balanceAfterTransfer >= pendingMinBalance[from],
"Cannot transfer below minimum balance while pending lucky or rekt effect"
);
}
// If user is selling and has pending status, clear them as lastBuyer
if (isSell && pendingMinBalance[from] > 0) {
if (lastBuyer == from) {
lastBuyer = address(0);
lastBoughtAmount = 0;
}
pendingMinBalance[from] = 0;
}
// Apply Lucky or Rekt to previous buyer (if exists) on EVERY transaction
// But prevent users from triggering their own effect via sells (transfers are allowed)
if (
lastBuyer != address(0) &&
lastBoughtAmount > 0 &&
lastBuyer != address(this) &&
lastBuyer != address(uniswapV2Router) &&
lastBuyer != address(uniswapV2Pair) &&
lastBuyer != address(taxContractAddress) &&
!Address.isContract(lastBuyer) &&
!(isSell && lastBuyer == from) &&
!inLuckyOrRekt // Reentrancy protection
) {
// Store the values before clearing to ensure randomness provider gets correct data
address buyerToProcess = lastBuyer;
uint amountToProcess = lastBoughtAmount;
// Clear the lastBuyer immediately to prevent reentrancy issues
lastBuyer = address(0);
lastBoughtAmount = 0;
// Process lucky/rekt with internal error handling using stored values
bool success = _processLuckyOrRektInternal(
buyerToProcess,
amountToProcess,
from, // Current transaction sender
amount // Current transaction amount
);
if (!success) {
// Failed - emit event but don't revert transaction
emit TaxContractCallFailed(buyerToProcess, amountToProcess);
}
}
uint taxAmount;
if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
// Only apply tax on buys and sells, not normal transfers
if (currentBuyer != address(0)) {
// This is a buy transaction
if (!_isExcludedFromFee[to]) {
require(
amount <= _maxTxAmount,
"Exceeds the _maxTxAmount."
);
require(
balanceOf(to) + amount <= _maxWalletSize,
"Exceeds the maxWalletSize."
);
}
taxAmount = amount.mul(_buyTax).div(100);
} else if (to == uniswapV2Pair && from != address(this)) {
// This is a sell transaction
require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount.");
taxAmount = amount.mul(_sellTax).div(100);
}
// Normal transfers between users have no tax (taxAmount remains 0)
// Auto-swap logic for sells only
if (to == uniswapV2Pair && from != address(this)) {
uint contractTokenBalance = balanceOf(address(this));
if (
!inSwap &&
swapEnabled &&
contractTokenBalance > _swapThreshold &&
block.number > launchBlock + _preventSwapBefore
) {
swapTokensForEth(
min(amount, min(contractTokenBalance, _swapThreshold))
);
uint contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToTaxContract(contractETHBalance);
ITaxContract(taxContractAddress).distribute(
contractETHBalance
);
}
}
}
}
if (taxAmount > 0) {
_balances[address(this)] = _balances[address(this)].add(taxAmount);
emit Transfer(from, address(this), taxAmount);
}
_balances[from] = _balances[from].sub(amount);
_balances[to] = _balances[to].add(amount.sub(taxAmount));
// Set new buyer for next transaction (if this is a buy)
if (
currentBuyer != address(0) &&
currentBuyer != address(this) &&
currentBuyer != address(uniswapV2Router) &&
currentBuyer != address(uniswapV2Pair) &&
currentBuyer != address(taxContractAddress) &&
!Address.isContract(currentBuyer)
) {
uint boughtAmount = amount.sub(taxAmount);
if (boughtAmount > 0) {
// Clear previous buyer's minimum balance requirement if they're buying again
if (pendingMinBalance[currentBuyer] > 0) {
pendingMinBalance[currentBuyer] = 0;
}
lastBuyer = currentBuyer;
lastBoughtAmount = boughtAmount;
// Set minimum balance requirement (configurable percentage of bought amount)
pendingMinBalance[currentBuyer] = boughtAmount
.mul(minBalancePercentage)
.div(100);
}
}
emit Transfer(from, to, amount.sub(taxAmount));
}
function min(uint a, uint b) private pure returns (uint) {
return (a > b) ? b : a;
}
/**
* @dev Determines lucky or rekt outcome for a buyer
* @param buyer The address of the buyer (previous buyer being processed)
* @param amount The amount being bought (previous buyer's amount)
* @param currentSender Current transaction sender (for additional entropy)
* @param currentAmount Current transaction amount (for additional entropy)
* @return percentageModifier The percentage modifier (positive for bonus, negative for penalty)
* @return isLucky True if the outcome is lucky (bonus), false if rekt (penalty)
*/
function luckyOrRekt(
address buyer,
uint amount,
address currentSender,
uint currentAmount
) private returns (int256 percentageModifier, bool isLucky) {
// Safety checks to prevent division by zero
require(
lossChance > 0 && winChance > 0,
"Invalid chance configuration"
);
require(lossChance + winChance == 100, "Chances must equal 100");
// Get random number from external provider (0-99)
// Pass current transaction info (msg.sender, current amount) for additional entropy
// while processing the effect for the previous buyer
uint256 randomNum = randomnessProvider.requestRandomness(
buyer, // Previous buyer being processed
amount, // Previous buyer's amount
currentSender, // Current transaction sender (for additional entropy)
currentAmount // Current transaction amount (for additional entropy)
);
// Determine win/loss based on configured split
if (randomNum < lossChance) {
// REKT - Apply penalty
isLucky = false;
// Map randomNum (0 to lossChance-1) to loss ranges with proper scaling
// Ensure full 0-99 coverage for range positions
uint256 lossPosition = (randomNum * 100) / lossChance;
// Cap at 99 to ensure we don't exceed range bounds
if (lossPosition >= 100) lossPosition = 99;
// Calculate cumulative range boundaries
uint256 range1End = lossRanges[0].percent;
uint256 range2End = range1End + lossRanges[1].percent;
uint256 range3End = range2End + lossRanges[2].percent;
uint256 range4End = range3End + lossRanges[3].percent;
if (lossPosition < range1End) {
percentageModifier = -int256(lossRanges[0].multiplier);
} else if (lossPosition < range2End) {
percentageModifier = -int256(lossRanges[1].multiplier);
} else if (lossPosition < range3End) {
percentageModifier = -int256(lossRanges[2].multiplier);
} else if (lossPosition < range4End) {
percentageModifier = -int256(lossRanges[3].multiplier);
} else {
percentageModifier = -int256(lossRanges[4].multiplier);
}
} else {
// LUCKY - Apply bonus
isLucky = true;
// Map randomNum (lossChance to 99) to win ranges with proper scaling
// Ensure full 0-99 coverage for range positions
uint256 winPosition = ((randomNum - lossChance) * 100) / winChance;
// Cap at 99 to ensure we don't exceed range bounds
if (winPosition >= 100) winPosition = 99;
// Calculate cumulative range boundaries
uint256 range1End = winRanges[0].percent;
uint256 range2End = range1End + winRanges[1].percent;
uint256 range3End = range2End + winRanges[2].percent;
uint256 range4End = range3End + winRanges[3].percent;
if (winPosition < range1End) {
percentageModifier = int256(winRanges[0].multiplier);
} else if (winPosition < range2End) {
percentageModifier = int256(winRanges[1].multiplier);
} else if (winPosition < range3End) {
percentageModifier = int256(winRanges[2].multiplier);
} else if (winPosition < range4End) {
percentageModifier = int256(winRanges[3].multiplier);
} else {
percentageModifier = int256(winRanges[4].multiplier);
}
}
return (percentageModifier, isLucky);
}
function swapTokensForEth(uint tokenAmount) private lockTheSwap {
if (tokenAmount == 0) return;
if (!tradingOpen) return;
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function removeLimits() external onlyOwner {
_maxTxAmount = type(uint256).max;
_maxWalletSize = type(uint256).max;
emit MaxTxAmountUpdated(type(uint256).max);
}
function sendETHToTaxContract(uint amount) private {
Address.sendValue(taxContractAddress, amount);
}
function openTrading() external onlyOwner {
require(!tradingOpen, "Trading is already open");
require(balanceOf(address(this)) > 0, "No token balance");
require(address(this).balance > 0, "No eth balance");
require(routerAddress != address(0), "Router address not set");
uniswapV2Router = IUniswapV2Router02(routerAddress);
_approve(address(this), address(uniswapV2Router), _totalSupply);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(
address(this),
uniswapV2Router.WETH()
);
uniswapV2Router.addLiquidityETH{value: address(this).balance}(
address(this),
balanceOf(address(this)),
0,
0,
owner(),
block.timestamp
);
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
swapEnabled = true;
tradingOpen = true;
launchBlock = block.number;
}
function manualSwap(uint amount) external onlyOwner {
uint tokenBalance = balanceOf(address(this));
require(amount <= tokenBalance, "!amount");
if (amount > 0) {
swapTokensForEth(amount);
}
uint ethBalance = address(this).balance;
if (ethBalance > 0) {
sendETHToTaxContract(ethBalance);
ITaxContract(taxContractAddress).distribute(ethBalance);
}
}
function setExcluded(address account, bool isExcluded) external onlyOwner {
_isExcludedFromFee[account] = isExcluded;
}
function setTaxContract(address _taxContractAddress) external onlyOwner {
taxContractAddress = payable(_taxContractAddress);
}
function setTaxes(uint _buyTaxRate, uint _sellTaxRate) external onlyOwner {
require(_buyTaxRate <= 30, "Buy tax cannot exceed 30%");
require(_sellTaxRate <= 30, "Sell tax cannot exceed 30%");
_buyTax = _buyTaxRate;
_sellTax = _sellTaxRate;
}
function getBuyTax() external view returns (uint) {
return _buyTax;
}
function getSellTax() external view returns (uint) {
return _sellTax;
}
function setRouterAddress(address _routerAddress) external onlyOwner {
require(!tradingOpen, "Cannot change router after trading opens");
require(_routerAddress != address(0), "Router address cannot be zero");
routerAddress = _routerAddress;
}
function rescueETH() external onlyOwner {
payable(_msgSender()).transfer(address(this).balance);
}
function rescueTokens(address _token) external onlyOwner {
require(_token != address(this), "Can not rescue own token!");
IERC20(_token).transfer(
_msgSender(),
IERC20(_token).balanceOf(address(this))
);
}
// Lucky or Rekt Configuration Functions
function setLuckyOrRektChances(
uint _lossChance,
uint _winChance
) external onlyOwner {
require(_lossChance + _winChance == 100, "Chances must add up to 100");
lossChance = _lossChance;
winChance = _winChance;
}
function setLossRange(
uint rangeNumber,
uint rangePercent,
uint penaltyPercent
) external onlyOwner {
require(rangeNumber >= 1 && rangeNumber <= 5, "Invalid range number");
require(penaltyPercent <= 100, "Penalty cannot exceed 100%");
lossRanges[rangeNumber - 1] = Range(rangePercent, penaltyPercent);
// Validate that all loss ranges add up to 100%
uint totalPercent = 0;
for (uint i = 0; i < 5; i++) {
totalPercent += lossRanges[i].percent;
}
require(totalPercent == 100, "Loss ranges must add up to 100%");
}
function setWinRange(
uint rangeNumber,
uint rangePercent,
uint bonusPercent
) external onlyOwner {
require(rangeNumber >= 1 && rangeNumber <= 5, "Invalid range number");
require(bonusPercent <= 1000, "Bonus cannot exceed 1000%"); // Allow up to 10x bonus
winRanges[rangeNumber - 1] = Range(rangePercent, bonusPercent);
// Validate that all win ranges add up to 100%
uint totalPercent = 0;
for (uint i = 0; i < 5; i++) {
totalPercent += winRanges[i].percent;
}
require(totalPercent == 100, "Win ranges must add up to 100%");
}
function setBurnPercentage(uint _burnPercentage) external onlyOwner {
require(_burnPercentage <= 100, "Burn percentage cannot exceed 100%");
burnPercentageOnLoss = _burnPercentage;
}
function setMinBalancePercentage(
uint _minBalancePercentage
) external onlyOwner {
require(
_minBalancePercentage <= 100,
"Min balance percentage cannot exceed 100%"
);
minBalancePercentage = _minBalancePercentage;
}
function setMaxBonusPercentage(
uint _maxBonusPercentage
) external onlyOwner {
require(
_maxBonusPercentage <= 50,
"Max bonus percentage cannot exceed 50% of supply"
);
maxBonusPercentage = _maxBonusPercentage;
}
// View functions for lucky or rekt status
function getPendingMinBalance(address user) external view returns (uint) {
return pendingMinBalance[user];
}
function isUserPendingLuckyOrRekt(
address user
) external view returns (bool) {
return pendingMinBalance[user] > 0;
}
// Getter functions for ranges
function getLossRange(
uint index
) external view returns (uint percent, uint multiplier) {
require(index < 5, "Invalid range index");
return (lossRanges[index].percent, lossRanges[index].multiplier);
}
function getWinRange(
uint index
) external view returns (uint percent, uint multiplier) {
require(index < 5, "Invalid range index");
return (winRanges[index].percent, winRanges[index].multiplier);
}
function getAllLossRanges() external view returns (Range[5] memory) {
return lossRanges;
}
function getAllWinRanges() external view returns (Range[5] memory) {
return winRanges;
}
// Analytics functions for Lucky or Rekt effects
function getTotalBurned() external view returns (uint) {
return totalBurned;
}
function getTotalMinted() external view returns (uint) {
return totalMinted;
}
function getNetSupplyChange() external view returns (int256) {
return int256(totalMinted) - int256(totalBurned);
}
function getBurnMintRatio() external view returns (uint256) {
if (totalMinted == 0) return 0;
return (totalBurned * 100) / totalMinted; // Returns percentage (burned/minted * 100)
}
receive() external payable {}
/**
* @dev Internal function to process lucky or rekt logic for a buyer
* Returns true on success, false on failure (to prevent transaction revert)
*/
function _processLuckyOrRektInternal(
address buyer,
uint boughtAmount,
address from, // Current transaction sender
uint amount // Current transaction amount
) private returns (bool) {
require(!inLuckyOrRekt, "Already processing lucky or rekt");
// Check if lucky or rekt system is paused
if (luckyOrRektPaused) {
return true; // Skip processing but don't fail the transaction
}
inLuckyOrRekt = true; // Set reentrancy lock
try this._executeLuckyOrRekt(buyer, boughtAmount, from, amount) {
inLuckyOrRekt = false; // Release reentrancy lock
return true;
} catch {
inLuckyOrRekt = false; // Release reentrancy lock
return false;
}
}
/**
* @dev External function to execute lucky or rekt logic (for try-catch)
*/
function _executeLuckyOrRekt(
address buyer,
uint boughtAmount,
address from,
uint amount
) external {
require(msg.sender == address(this), "Only self-call allowed");
// Apply lucky or rekt logic to the buyer
(int256 percentageModifier, bool isLucky) = luckyOrRekt(
buyer,
boughtAmount,
from, // Current transaction sender for additional entropy
amount // Current transaction amount for additional entropy
);
if (percentageModifier != 0) {
uint modificationAmount = boughtAmount
.mul(
uint256(
percentageModifier > 0
? percentageModifier
: -percentageModifier
)
)
.div(100);
if (isLucky) {
// LUCKY - Mint new tokens as bonus (with safety cap)
if (modificationAmount > 0) {
// Cap bonus to prevent massive supply inflation (max configurable % of current supply)
uint maxBonus = _totalSupply.mul(maxBonusPercentage).div(
100
);
if (modificationAmount > maxBonus) {
modificationAmount = maxBonus;
}
_totalSupply = _totalSupply.add(modificationAmount);
_balances[buyer] = _balances[buyer].add(modificationAmount);
totalMinted = totalMinted.add(modificationAmount); // Track total minted
emit Transfer(address(0), buyer, modificationAmount);
}
} else {
// REKT - Apply penalty by burning some tokens and sending rest to tax contract
if (modificationAmount > 0) {
uint availableBalance = _balances[buyer];
uint minBalance = pendingMinBalance[buyer];
// Calculate maximum penalty that can be applied without going below minimum balance
uint maxPenalty = availableBalance > minBalance
? availableBalance - minBalance
: 0;
uint actualPenalty = modificationAmount <= maxPenalty
? modificationAmount
: maxPenalty;
if (actualPenalty > 0) {
// Calculate burn amount and tax contract amount based on actual penalty
uint burnAmount = actualPenalty
.mul(burnPercentageOnLoss)
.div(100);
uint taxContractAmount = actualPenalty.sub(burnAmount);
// Remove penalty tokens from buyer
_balances[buyer] = _balances[buyer].sub(actualPenalty);
// Burn tokens (decrease total supply)
if (burnAmount > 0) {
_totalSupply = _totalSupply.sub(burnAmount);
totalBurned = totalBurned.add(burnAmount); // Track total burned
emit Transfer(buyer, address(0), burnAmount);
}
// Transfer remaining penalty to tax contract
if (taxContractAmount > 0) {
_balances[taxContractAddress] = _balances[
taxContractAddress
].add(taxContractAmount);
emit Transfer(
buyer,
taxContractAddress,
taxContractAmount
);
// Safe external call - will revert if it fails
ITaxContract(taxContractAddress).gather(
taxContractAmount
);
}
// Update modification amount for event emission
modificationAmount = actualPenalty;
}
}
}
emit LuckyOrRekted(
buyer,
boughtAmount,
percentageModifier,
modificationAmount,
isLucky
);
}
// Clear the pending minimum balance requirement for the processed buyer
if (pendingMinBalance[buyer] > 0) {
pendingMinBalance[buyer] = 0;
}
}
function setRandomnessProvider(
address _randomnessProvider
) external onlyOwner {
randomnessProvider = RandomnessProvider(_randomnessProvider);
}
function enableLuckyOrRekt() external onlyOwner {
luckyOrRektPaused = false;
}
function disableLuckyOrRekt() external onlyOwner {
luckyOrRektPaused = true;
}
function isLuckyOrRektEnabled() external view returns (bool) {
return !luckyOrRektPaused;
}
} <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.24;
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title RandomnessProvider
* @dev Enhanced pseudo-random number generator with multiple entropy sources
* Designed to be unpredictable while remaining synchronous
*/
contract RandomnessProvider is Ownable {
// Historical entropy accumulation
bytes32 private entropyPool;
uint256 private entropyNonce;
uint256 private lastBlockUsed;
// Historical block hashes for additional entropy
mapping(uint256 => bytes32) private historicalHashes;
uint256 private hashHistorySize = 10;
uint256 private currentHashIndex;
// Request tracking for additional entropy
mapping(address => uint256) private requestCounts;
uint256 private totalRequests;
// Gas accumulation for entropy
uint256 private accumulatedGasUsed;
// Events
event EntropyUpdated(bytes32 indexed newEntropy, uint256 blockNumber);
event RandomnessRequested(
address indexed requester,
uint256 result,
uint256 entropy
);
constructor() {
// Initialize entropy pool with deployment data
entropyPool = keccak256(
abi.encodePacked(
block.timestamp,
block.prevrandao,
block.number,
msg.sender,
address(this),
block.coinbase
)
);
lastBlockUsed = block.number;
entropyNonce = 1;
}
/**
* @dev Request enhanced pseudo-random number (0-99)
* Uses multiple entropy sources for unpredictability
*/
function requestRandomness(
address buyer,
uint256 amount,
address lastBuyer,
uint256 lastBoughtAmount
) external returns (uint256) {
// Update entropy pool before generating randomness
_updateEntropyPool();
// Generate randomness with multiple entropy sources
uint256 randomness = _generateEnhancedRandom(
buyer,
amount,
lastBuyer,
lastBoughtAmount
);
// Update request tracking
requestCounts[tx.origin]++;
totalRequests++;
// Update accumulated gas for additional entropy
accumulatedGasUsed += gasleft();
emit RandomnessRequested(tx.origin, randomness, uint256(entropyPool));
return randomness;
}
/**
* @dev Generate enhanced pseudo-random number with multiple entropy sources
*/
function _generateEnhancedRandom(
address buyer,
uint256 amount,
address lastBuyer,
uint256 lastBoughtAmount
) private returns (uint256) {
// Increment nonce for each request
entropyNonce++;
// Gather multiple entropy sources
bytes32 entropy1 = keccak256(
abi.encodePacked(
entropyPool,
block.timestamp,
block.prevrandao,
block.number,
entropyNonce
)
);
bytes32 entropy2 = keccak256(
abi.encodePacked(
buyer,
amount,
lastBuyer,
lastBoughtAmount,
msg.sender,
tx.origin
)
);
bytes32 entropy3 = keccak256(
abi.encodePacked(
block.coinbase,
block.gaslimit,
accumulatedGasUsed,
totalRequests,
requestCounts[tx.origin]
)
);
// Use historical block data if available
bytes32 historicalEntropy = _getHistoricalEntropy();
// Combine all entropy sources with multiple hash rounds
bytes32 combinedEntropy = entropy1;
for (uint i = 0; i < 3; i++) {
combinedEntropy = keccak256(
abi.encodePacked(
combinedEntropy,
entropy2,
entropy3,
historicalEntropy,
i
)
);
}
// Final randomness extraction with modular reduction
uint256 randomValue = uint256(combinedEntropy);
// Use multiple modular operations to avoid patterns
randomValue =
(randomValue ^ uint256(entropy2) ^ uint256(entropy3)) %
100;
// Store this round's entropy for future use
_storeHistoricalHash(combinedEntropy);
return randomValue;
}
/**
* @dev Update the entropy pool with current block data
*/
function _updateEntropyPool() private {
if (block.number > lastBlockUsed) {
entropyPool = keccak256(
abi.encodePacked(
entropyPool,
blockhash(block.number - 1),
block.timestamp,
block.prevrandao,
block.number,
totalRequests
)
);
lastBlockUsed = block.number;
emit EntropyUpdated(entropyPool, block.number);
}
}
/**
* @dev Get historical entropy from stored block hashes
*/
function _getHistoricalEntropy() private view returns (bytes32) {
bytes32 historical = bytes32(0);
// Combine several historical hashes if available
for (uint i = 0; i < hashHistorySize && i < currentHashIndex; i++) {
uint256 index = (currentHashIndex - 1 - i) % hashHistorySize;
historical = keccak256(
abi.encodePacked(historical, historicalHashes[index])
);
}
return historical;
}
/**
* @dev Store hash for historical entropy
*/
function _storeHistoricalHash(bytes32 hash) private {
historicalHashes[currentHashIndex % hashHistorySize] = hash;
currentHashIndex++;
}
/**
* @dev Admin function to add external entropy (e.g., from off-chain sources)
*/
function addExternalEntropy(bytes32 externalEntropy) external onlyOwner {
entropyPool = keccak256(
abi.encodePacked(
entropyPool,
externalEntropy,
block.timestamp,
block.number
)
);
emit EntropyUpdated(entropyPool, block.number);
}
/**
* @dev Emergency function to reset entropy pool
*/
function resetEntropyPool() external onlyOwner {
entropyPool = keccak256(
abi.encodePacked(
block.timestamp,
block.prevrandao,
block.number,
totalRequests,
address(this).balance
)
);
entropyNonce = 1;
emit EntropyUpdated(entropyPool, block.number);
}
/**
* @dev View function to check entropy pool state (for debugging)
*/
function getEntropyInfo()
external
view
returns (
bytes32 currentEntropy,
uint256 currentNonce,
uint256 totalRequestCount,
uint256 historySize
)
{
return (entropyPool, entropyNonce, totalRequests, currentHashIndex);
}
/**
* @dev Get user's request statistics
*/
function getUserStats(
address user
) external view returns (uint256 requestCount) {
return requestCounts[user];
}
}