Feature Tip: Add private address tag to any address under My Name Tag !
Source Code
Loading...
Loading
Contract Name:
WyvernBuyAndBurn
Compiler Version
v0.8.20+commit.a1b79de6
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.20; import "@openzeppelin/contracts/access/Ownable2Step.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@uniswap/v3-periphery/interfaces/ISwapRouter.sol"; import "@uniswap/v3-core/interfaces/IUniswapV3Pool.sol"; import "../interfaces/IWETH.sol"; import "../interfaces/INonfungiblePositionManager.sol"; import "../libs/uniswap/PoolAddress.sol"; import "../libs/uniswap/Oracle.sol"; import "../libs/uniswap/TickMath.sol"; import "../libs/constant.sol"; import "../libs/utilFunctions.sol"; import "./WyvernX.sol"; import "./WyvernVault.sol"; contract WyvernBuyAndBurn is Ownable2Step, ReentrancyGuard { using SafeERC20 for IERC20; using SafeERC20 for IWETH9; using SafeERC20 for WyvernX; address public wyvernAddress; address public wyvernVaultAddress; address public liquidityBondingAddress; /** * @dev Maximum permitted price deviation percentage for buy&burn transactions */ uint256 public slippage; /** * @dev Total WETH used for WyvernX buy&burn transactions */ uint256 public totalWethUsedForBuyAndBurns; /** * @dev Total WyvernX tokens purchased and burned */ uint256 public totalWyvernBurned; /** * @dev Total WyvernX tokens collected as fees */ uint256 public totalWyvernFeesCollected; /** * @dev Total TitanX tokens collected as fees and sent for staking */ uint256 public totalTitanFeesCollected; /** * @dev Cap on WETH amount per buy transaction */ uint256 public capPerBuy; /** * @dev Timestamp of the last buy and burn operation */ uint256 public lastBuyTimestamp; /** * @dev Minimum interval between buy and burn operations */ uint256 public interval; /** * @dev Reference to the WyvernX-TitanX Uniswap V3 pool */ address public wyvernTitanPoolAddress; /** * @dev Stores Uniswap V3 liquidity position details */ TokenLiquidityInfo private tokenLiquidityInfo; /** * @dev Time-weighted average period for TitanX price calculations */ uint32 private titanPriceTwa; /** * @dev Time-weighted average period for WyvernX price calculations */ uint32 private wyvernPriceTwa; /** * @dev Flag for liquidity addition or fee distribution to stakers */ bool private addLiquidityFlag; /** * @dev Flag indicating if Titan staking in WyvernVault is initialized */ bool private titanStakingInitialized; /** * @dev Struct to store Uniswap V3 liquidity position details */ struct TokenLiquidityInfo { uint80 tokenId; // Position token ID in Uniswap V3 pool uint256 liquidity; // Liquidity amount in the position int24 tickLower; // Lower price range for the position int24 tickUpper; // Upper price range for the position } /** * @notice Event emitted when WyvernX tokens are bought and burned * @param weth Amount of WETH used * @param wyvern Amount of WyvernX tokens burned * @param caller Entity executing the operation */ event BoughtAndBurned( uint256 indexed weth, uint256 indexed wyvern, address indexed caller ); /** * @notice Event emitted when fees are collected * @param wyvern Amount of WyvernX collected * @param titan Amount of TitanX collected * @param caller Entity executing the operation */ event CollectedFees( uint256 indexed wyvern, uint256 indexed titan, address indexed caller ); /** * @notice Event emitted when liquidity is added * @param wyvern Amount of WyvernX added * @param titan Amount of TitanX added * @param caller Entity executing the operation */ event LiquidityAdded( uint256 indexed wyvern, uint256 indexed titan, address indexed caller ); error InvalidWyvernAddress(); error InvalidWyvernVaultAddress(); error InvalidAddress(); error InvalidCaller(); error CooldownPeriodActive(); error NoWethBalanceToBuyAndBurnWyvern(); /** * @notice Executes WyvernX buy and burn operation * @dev Swaps WETH for WyvernX and burns the tokens * @return amountOut Amount of WyvernX tokens burned */ function buyAndBurnWyvernX() external nonReentrant returns (uint256 amountOut) { address wyvernAddress_ = wyvernAddress; if (wyvernAddress_ == address(0)) revert InvalidWyvernAddress(); if (msg.sender != tx.origin) revert InvalidCaller(); if (block.timestamp - lastBuyTimestamp <= interval) revert CooldownPeriodActive(); lastBuyTimestamp = block.timestamp; ISwapRouter swapRouter = ISwapRouter(UNI_SWAP_ROUTER); IWETH9 weth = IWETH9(WETH9_ADDRESS); uint256 amountIn = weth.balanceOf(address(this)); uint256 wethCap = capPerBuy; if (amountIn > wethCap) amountIn = wethCap; uint256 incentiveFee = (amountIn * REWARD_FEE) / PERCENTAGE_BASE_VAULT; weth.withdraw(incentiveFee); amountIn -= incentiveFee; if (amountIn == 0) revert NoWethBalanceToBuyAndBurnWyvern(); weth.safeIncreaseAllowance(address(swapRouter), amountIn); bytes memory path = abi.encodePacked( WETH9_ADDRESS, FEE_TIER, TITANX_ADDRESS, FEE_TIER, wyvernAddress_ ); uint256 amountOutMinimum = calculateMinimumWyvernAmount(amountIn); ISwapRouter.ExactInputParams memory params = ISwapRouter .ExactInputParams({ path: path, recipient: address(this), deadline: block.timestamp + 1, amountIn: amountIn, amountOutMinimum: amountOutMinimum }); amountOut = swapRouter.exactInput(params); WyvernX(payable(wyvernAddress_)).burnLPTokens(); totalWethUsedForBuyAndBurns += amountIn; totalWyvernBurned += amountOut; Address.sendValue(payable(_msgSender()), incentiveFee); emit BoughtAndBurned(amountIn, amountOut, msg.sender); } /** * @notice Collects fees from liquidity pool * @dev Handles fee collection and distribution */ function collectFees() external nonReentrant { address wyvernAddress_ = wyvernAddress; address titanAddress_ = TITANX_ADDRESS; address bondingAddress_ = liquidityBondingAddress; if (wyvernAddress_ == address(0)) revert InvalidWyvernAddress(); address sender = _msgSender(); WyvernX wyvernX = WyvernX(payable(wyvernAddress_)); IERC20 titanX = IERC20(TITANX_ADDRESS); (uint256 amount0, uint256 amount1) = _collectFees(); uint256 wyvern; uint256 titan; if (wyvernAddress_ < titanAddress_) { wyvern = amount0; titan = amount1; } else { titan = amount0; wyvern = amount1; } if (addLiquidityFlag) { uint256 price = getCurrentTitanPrice(); if (wyvern != 0 && titan != 0) { wyvernX.safeIncreaseAllowance( UNI_NONFUNGIBLEPOSITIONMANAGER, wyvern ); titanX.safeIncreaseAllowance( UNI_NONFUNGIBLEPOSITIONMANAGER, titan ); if (titanAddress_ < wyvernAddress_) { _increaseLiquidityCurrentRange(titan, wyvern, price); } else { _increaseLiquidityCurrentRange( wyvern, titan, ((1 ether * 1 ether) / price) ); } emit LiquidityAdded(wyvern, titan, sender); } } else { totalWyvernFeesCollected += wyvern; totalTitanFeesCollected += titan; IERC20(titanAddress_).safeTransfer(wyvernAddress_, titan); IERC20(wyvernAddress_).safeTransfer(bondingAddress_, wyvern); emit CollectedFees(wyvern, titan, sender); } } /** * @notice Instantiates the contract. * @dev Initializes contract with default values. */ constructor() Ownable(msg.sender) { capPerBuy = 0.045 ether; slippage = 5; interval = 60 * 60; titanPriceTwa = 15; wyvernPriceTwa = 15; addLiquidityFlag = true; liquidityBondingAddress = LIQUIDITY_BONDING_ADDR; } /** * @notice Initializes liquidity in the pool * @dev Sets up liquidity for WyvernX-TitanX pool using contract's TitanX balance * @param initialWyvernXLiquidityAmount WyvernX liquidity amount to determine price ratio */ function createUniswapLiquidity( uint256 initialWyvernXLiquidityAmount ) external onlyOwner { address wyvernAddress_ = wyvernAddress; if (wyvernAddress_ == address(0)) revert InvalidWyvernAddress(); WyvernX wyvernX = WyvernX(payable(wyvernAddress_)); IERC20 titanX = IERC20(TITANX_ADDRESS); // Get current TitanX balance in the contract uint256 titanContractBalanceForInitialLiquidity = titanX.balanceOf(address(this)); require(titanContractBalanceForInitialLiquidity > 0, "Provide TitanX Liquidity"); wyvernX.mintInitialLiquidity(initialWyvernXLiquidityAmount); titanX.safeIncreaseAllowance( UNI_NONFUNGIBLEPOSITIONMANAGER, titanContractBalanceForInitialLiquidity ); wyvernX.safeIncreaseAllowance( UNI_NONFUNGIBLEPOSITIONMANAGER, initialWyvernXLiquidityAmount ); _createTitanWyvernPool(titanContractBalanceForInitialLiquidity, initialWyvernXLiquidityAmount); _mintLP(titanContractBalanceForInitialLiquidity, initialWyvernXLiquidityAmount); } /** @notice Toggles liquidity addition flag */ function addLiquidity() external onlyOwner { addLiquidityFlag = !addLiquidityFlag; } /** * @notice Enables Titan staking in WyvernVault * @dev Initializes Titan staking in WyvernVault */ function enableTitanStaking() external onlyOwner { require(!titanStakingInitialized, "Already initialized"); WyvernVault wyvernVault = WyvernVault(payable(wyvernVaultAddress)); wyvernVault.allowTitanStaking(); titanStakingInitialized = true; } /** * @notice Retrieves total WETH available for buy and burn * @return balance WETH balance in the contract */ function totalWethForBuyAndBurn() external view returns (uint256 balance) { return IERC20(WETH9_ADDRESS).balanceOf(address(this)); } /** * @notice Calculates caller reward fee for buy and burn operation * @return reward Reward fee amount */ function callerRewardFeeForCallingBuyAndBurnWyvern() external view returns (uint256 reward) { uint256 nextBuySize = calculateWethForNextBuyAndBurn(); reward = (nextBuySize * REWARD_FEE) / PERCENTAGE_BASE_VAULT; } /** * @notice Sets WyvernX contract address * @param wyvernAddress_ New WyvernX contract address */ function setWyvernContractAddress(address wyvernAddress_) external onlyOwner { if (wyvernAddress_ == address(0)) revert InvalidWyvernAddress(); wyvernAddress = wyvernAddress_; } /** * @notice Sets WyvernVault contract address * @param wyvernVaultAddress_ New WyvernVault contract address */ function setWyvernVaultContractAddress(address wyvernVaultAddress_) external onlyOwner { if (wyvernVaultAddress_ == address(0)) revert InvalidWyvernVaultAddress(); wyvernVaultAddress = wyvernVaultAddress_; } /** @notice Set Liquidity Bonding Address * Only owner can call this function * @param newAddress Liquidity Bonding Address */ function setLiquidityBondingAddress(address newAddress) external onlyOwner { if (newAddress == address(0)) revert InvalidAddress(); liquidityBondingAddress = newAddress; } /** * @notice Sets WETH cap per buy * @param amount New cap amount */ function setCapPerBuy(uint256 amount) external onlyOwner { capPerBuy = amount; } /** * @notice Updates price deviation threshold * @param amount New threshold (5-15 range) */ function setSlippage(uint256 amount) external onlyOwner { require(amount >= 5 && amount <= 15, "5-15% only"); slippage = amount; } /** * @notice Sets buy and burn frequency * @param secs New frequency in seconds */ function setBuyAndBurnFrequency(uint256 secs) external onlyOwner { require(secs >= 60 && secs <= 43200, "1m-12h only"); interval = secs; } /** * @notice Updates price averaging period for TitanX * @param mins New TWAP period in minutes */ function setTitanPriceTwa(uint32 mins) external onlyOwner { require(mins >= 5 && mins <= 60, "5m-1h only"); titanPriceTwa = mins; } /** * @notice Updates price averaging period for WyvernX * @param mins New TWAP period in minutes */ function setWyvernPriceTwa(uint32 mins) external onlyOwner { require(mins >= 5 && mins <= 60, "5m-1h only"); wyvernPriceTwa = mins; } /** * @notice Gets TitanX quote for a given ETH amount * @param baseAmount ETH amount * @return quote TitanX quote */ function getTitanQuoteForEth(uint256 baseAmount) public view returns (uint256 quote) { address poolAddress = PoolAddress.computeAddress( UNI_FACTORY, PoolAddress.getPoolKey(WETH9_ADDRESS, TITANX_ADDRESS, FEE_TIER) ); uint160 sqrtPriceX96 = _getSqrtPrice(poolAddress, titanPriceTwa * 60); return OracleLibrary.getQuoteForSqrtRatioX96( sqrtPriceX96, baseAmount, WETH9_ADDRESS, TITANX_ADDRESS ); } /** * @notice Gets current TitanX price in WyvernX * @return TitanX price in WyvernX */ function getCurrentTitanPrice() public view returns (uint256) { uint256 sqrtPriceX96 = _getSqrtPrice(wyvernTitanPoolAddress, titanPriceTwa * 60); uint256 num1 = sqrtPriceX96 * sqrtPriceX96; uint256 num2 = 10 ** 18; uint256 price = Math.mulDiv(num1, num2, 1 << 192); price = TITANX_ADDRESS < wyvernAddress ? (1 ether * 1 ether) / price : price; return price; } /** * @notice Gets WyvernX quote for a given TitanX amount * @param baseAmount TitanX amount * @return quote WyvernX quote */ function getWyvernQuoteForTitan(uint256 baseAmount) public view returns (uint256 quote) { address titanAddress_ = TITANX_ADDRESS; address wyvernAddress_ = wyvernAddress; address poolAddress = PoolAddress.computeAddress( UNI_FACTORY, PoolAddress.getPoolKey(wyvernAddress_, titanAddress_, FEE_TIER) ); uint160 sqrtPriceX96 = _getSqrtPrice(poolAddress, wyvernPriceTwa * 60); return OracleLibrary.getQuoteForSqrtRatioX96( sqrtPriceX96, baseAmount, titanAddress_, wyvernAddress_ ); } /** * @notice Determines WETH amount for next buy and burn * @return nextBuySize WETH amount for next operation */ function calculateWethForNextBuyAndBurn() public view returns (uint256 nextBuySize) { uint256 capPerSwap_ = capPerBuy; IERC20 weth = IERC20(WETH9_ADDRESS); nextBuySize = weth.balanceOf(address(this)); if (nextBuySize > capPerSwap_) nextBuySize = capPerSwap_; } /** * @notice Calculates minimum WyvernX amount for multi-hop swap * @param amountIn WETH amount * @return amountOutMinimum Minimum WyvernX amount */ function calculateMinimumWyvernAmount(uint256 amountIn) public view returns (uint256) { uint256 slippage_ = slippage; uint256 quotedTitanAmount = getTitanQuoteForEth(amountIn); uint256 slippageAdjustedTitanAmount = (quotedTitanAmount * (100 - slippage_)) / 100; uint256 quotedWyvernAmount = getWyvernQuoteForTitan(slippageAdjustedTitanAmount); uint256 amountOutMinimum = (quotedWyvernAmount * (100 - slippage_)) / 100; return amountOutMinimum; } /** @notice Gets WETH balance for a given address * @param account Address to check * @return balance WETH balance */ function getWethBalance(address account) public view returns (uint256) { return IWETH9(WETH9_ADDRESS).balanceOf(account); } /** @notice Gets available buy and burn funds * @return amount WETH amount */ function getBuyAndBurnBalance() public view returns (uint256) { return getWethBalance(address(this)); } /** * @notice Fetches sqrtPriceX96 * @param poolAddress Uniswap pool address * @param secPassed TWAP period in seconds * @return sqrtPriceX96 Square root price */ function _getSqrtPrice(address poolAddress, uint32 secPassed) private view returns (uint160 sqrtPriceX96) { uint32 oldestObservation = OracleLibrary.getOldestObservationSecondsAgo(poolAddress); if (oldestObservation < secPassed) secPassed = oldestObservation; if (secPassed == 0) { IUniswapV3Pool pool = IUniswapV3Pool(poolAddress); (sqrtPriceX96, , , , , , ) = pool.slot0(); } else { (int24 arithmeticMeanTick, ) = OracleLibrary.consult(poolAddress, secPassed); sqrtPriceX96 = TickMath.getSqrtRatioAtTick(arithmeticMeanTick); } return sqrtPriceX96; } /** * @notice Sorts tokens for Uniswap pair * @param initialTitanxLiquidityAmount TitanX liquidity amount * @param initialWyvernxLiquidityAmount WyvernX liquidity amount * @return token0 Smaller token address * @return token1 Larger token address * @return amount0 Liquidity for token0 * @return amount1 Liquidity for token1 */ function _getTokenConfig( uint256 initialTitanxLiquidityAmount, uint256 initialWyvernxLiquidityAmount ) private view returns ( address token0, address token1, uint256 amount0, uint256 amount1) { address wyvernAddress_ = wyvernAddress; address titanAddress_ = TITANX_ADDRESS; (token0, token1) = wyvernAddress_ < titanAddress_ ? (wyvernAddress_, titanAddress_) : (titanAddress_, wyvernAddress_); (amount0, amount1) = token0 == wyvernAddress_ ? (initialWyvernxLiquidityAmount, initialTitanxLiquidityAmount) : (initialTitanxLiquidityAmount, initialWyvernxLiquidityAmount); } /** * @notice Creates liquidity pool with initial price * @param initialTitanxLiquidityAmount TitanX liquidity amount * @param initialWyvernXLiquidityAmount WyvernX liquidity amount */ function _createTitanWyvernPool( uint256 initialTitanxLiquidityAmount, uint256 initialWyvernXLiquidityAmount ) private { (address token0, address token1, uint256 amount0, uint256 amount1) = _getTokenConfig( initialTitanxLiquidityAmount, initialWyvernXLiquidityAmount ); INonfungiblePositionManager manager = INonfungiblePositionManager( UNI_NONFUNGIBLEPOSITIONMANAGER ); uint160 sqrtPX96 = uint160((sqrt((amount1 * 1e18) / amount0) * 2 ** 96) / 1e9); wyvernTitanPoolAddress = manager.createAndInitializePoolIfNecessary( token0, token1, FEE_TIER, sqrtPX96 ); IUniswapV3Pool(wyvernTitanPoolAddress) .increaseObservationCardinalityNext(100); } /** * @notice Mints full range LP token in Uniswap V3 pool * @param initialTitanxLiquidityAmount TitanX liquidity amount * @param initialWyvernXLiquidityAmount WyvernX liquidity amount */ function _mintLP( uint256 initialTitanxLiquidityAmount, uint256 initialWyvernXLiquidityAmount ) private { INonfungiblePositionManager manager = INonfungiblePositionManager( UNI_NONFUNGIBLEPOSITIONMANAGER ); ( address token0, address token1, uint256 amount0Desired, uint256 amount1Desired ) = _getTokenConfig( initialTitanxLiquidityAmount, initialWyvernXLiquidityAmount ); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams({ token0: token0, token1: token1, fee: FEE_TIER, tickLower: MIN_TICK, tickUpper: MAX_TICK, amount0Desired: amount0Desired, amount1Desired: amount1Desired, amount0Min: (amount0Desired * 90) / 100, amount1Min: (amount1Desired * 90) / 100, recipient: address(this), deadline: block.timestamp + 600 }); (uint256 tokenId, uint256 liquidity, , ) = manager.mint(params); tokenLiquidityInfo.tokenId = uint80(tokenId); tokenLiquidityInfo.liquidity = liquidity; tokenLiquidityInfo.tickLower = MIN_TICK; tokenLiquidityInfo.tickUpper = MAX_TICK; } /** * @notice Increases liquidity in current pool range * @param amount0Collected Amount of token0 collected * @param amount1Collected Amount of token1 collected * @param price Current price of token1 in terms of token0 */ function _increaseLiquidityCurrentRange(uint256 amount0Collected, uint256 amount1Collected, uint256 price) private { uint256 desiredAmount0 = Math.mulDiv(amount1Collected, price, 1e18); uint256 desiredAmount1 = Math.mulDiv(amount0Collected, 1e18, price); uint256 amount0ToAdd = amount0Collected < desiredAmount0 ? amount0Collected : desiredAmount0; uint256 amount1ToAdd = amount1Collected < desiredAmount1 ? amount1Collected : desiredAmount1; INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenLiquidityInfo.tokenId, amount0Desired: amount0ToAdd, amount1Desired: amount1ToAdd, amount0Min: (amount0ToAdd * 90) / 100, amount1Min: (amount1ToAdd * 90) / 100, deadline: block.timestamp + 600 }); (uint256 liquidity, , ) = INonfungiblePositionManager( UNI_NONFUNGIBLEPOSITIONMANAGER ).increaseLiquidity(params); tokenLiquidityInfo.liquidity += liquidity; } /** * @notice Collects fees from Uniswap V3 pool * @return amount0 Amount of token0 collected * @return amount1 Amount of token1 collected */ function _collectFees() private returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager manager = INonfungiblePositionManager( UNI_NONFUNGIBLEPOSITIONMANAGER ); INonfungiblePositionManager.CollectParams memory params = INonfungiblePositionManager.CollectParams( tokenLiquidityInfo.tokenId, address(this), type(uint128).max, type(uint128).max ); (amount0, amount1) = manager.collect(params); } // NATIVE TOKEN HANDLING /** * @notice Processes incoming native token deposits * @dev Converts received native tokens to wrapped form, except from wrapper contract */ receive() external payable { if (msg.sender != WETH9_ADDRESS) { IWETH9(WETH9_ADDRESS).deposit{value: msg.value}(); } } /** * @notice Handles unexpected contract interactions * @dev Blocks unintended native token transfers */ fallback() external { revert("Fallback triggered"); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {Context} from "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The initial owner is set to the address provided by the deployer. This can * later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; /** * @dev The caller account is not authorized to perform an operation. */ error OwnableUnauthorizedAccount(address account); /** * @dev The owner is not a valid owner account. (eg. `address(0)`) */ error OwnableInvalidOwner(address owner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the address provided by the deployer as the initial owner. */ constructor(address initialOwner) { if (initialOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(initialOwner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { if (owner() != _msgSender()) { revert OwnableUnauthorizedAccount(_msgSender()); } } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol) pragma solidity ^0.8.20; import {Ownable} from "./Ownable.sol"; /** * @dev Contract module which provides access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The initial owner is specified at deployment time in the constructor for `Ownable`. This * can later be changed with {transferOwnership} and {acceptOwnership}. * * This module is used through inheritance. It will make available all functions * from parent (Ownable). */ abstract contract Ownable2Step is Ownable { address private _pendingOwner; event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view virtual returns (address) { return _pendingOwner; } /** * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual override onlyOwner { _pendingOwner = newOwner; emit OwnershipTransferStarted(owner(), newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner. * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual override { delete _pendingOwner; super._transferOwnership(newOwner); } /** * @dev The new owner accepts the ownership transfer. */ function acceptOwnership() public virtual { address sender = _msgSender(); if (pendingOwner() != sender) { revert OwnableUnauthorizedAccount(sender); } _transferOwnership(sender); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol) pragma solidity ^0.8.20; /** * @dev Standard ERC20 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens. */ interface IERC20Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC20InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC20InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. * @param spender Address that may be allowed to operate on tokens without being their owner. * @param allowance Amount of tokens a `spender` is allowed to operate with. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC20InvalidApprover(address approver); /** * @dev Indicates a failure with the `spender` to be approved. Used in approvals. * @param spender Address that may be allowed to operate on tokens without being their owner. */ error ERC20InvalidSpender(address spender); } /** * @dev Standard ERC721 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens. */ interface IERC721Errors { /** * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20. * Used in balance queries. * @param owner Address of the current owner of a token. */ error ERC721InvalidOwner(address owner); /** * @dev Indicates a `tokenId` whose `owner` is the zero address. * @param tokenId Identifier number of a token. */ error ERC721NonexistentToken(uint256 tokenId); /** * @dev Indicates an error related to the ownership over a particular token. Used in transfers. * @param sender Address whose tokens are being transferred. * @param tokenId Identifier number of a token. * @param owner Address of the current owner of a token. */ error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC721InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC721InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param tokenId Identifier number of a token. */ error ERC721InsufficientApproval(address operator, uint256 tokenId); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC721InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC721InvalidOperator(address operator); } /** * @dev Standard ERC1155 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens. */ interface IERC1155Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. * @param tokenId Identifier number of a token. */ error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC1155InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC1155InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param owner Address of the current owner of a token. */ error ERC1155MissingApprovalForAll(address operator, address owner); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC1155InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC1155InvalidOperator(address operator); /** * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. * Used in batch transfers. * @param idsLength Length of the array of token identifiers * @param valuesLength Length of the array of token amounts */ error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "./IERC20.sol"; import {IERC20Metadata} from "./extensions/IERC20Metadata.sol"; import {Context} from "../../utils/Context.sol"; import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. */ abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors { mapping(address account => uint256) private _balances; mapping(address account => mapping(address spender => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows _totalSupply += value; } else { uint256 fromBalance = _balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. _balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. _totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. _balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address owner, address spender, uint256 value) internal { _approve(owner, spender, value, true); } /** * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to * true using the following override: * ``` * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } _allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner` s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Does not emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @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 value of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the value of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves a `value` amount of tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the * allowance mechanism. `value` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 value) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * ==== Security Considerations * * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be * considered as an intention to spend the allowance in any specific way. The second is that because permits have * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be * generally recommended is: * * ```solidity * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} * doThing(..., value); * } * * function doThing(..., uint256 value) public { * token.safeTransferFrom(msg.sender, address(this), value); * ... * } * ``` * * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also * {SafeERC20-safeTransferFrom}). * * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so * contracts should have entry points that don't rely on permit. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. * * CAUTION: See Security Considerations above. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; import {IERC20Permit} from "../extensions/IERC20Permit.sol"; import {Address} from "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; /** * @dev An operation with an ERC20 token failed. */ error SafeERC20FailedOperation(address token); /** * @dev Indicates a failed `decreaseAllowance` request. */ error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value))); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value))); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); forceApprove(token, spender, oldAllowance + value); } /** * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no * value, non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal { unchecked { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance < requestedDecrease) { revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); } forceApprove(token, spender, currentAllowance - requestedDecrease); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval * to be set to zero before setting it to a non-zero value, such as USDT. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value)); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0))); _callOptionalReturn(token, approvalCall); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data); if (returndata.length != 0 && !abi.decode(returndata, (bool))) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol) pragma solidity ^0.8.20; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev The ETH balance of the account is not enough to perform the operation. */ error AddressInsufficientBalance(address account); /** * @dev There's no code at `target` (it is not a contract). */ error AddressEmptyCode(address target); /** * @dev A call to an address target failed. The target may have reverted. */ error FailedInnerCall(); /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { if (address(this).balance < amount) { revert AddressInsufficientBalance(address(this)); } (bool success, ) = recipient.call{value: amount}(""); if (!success) { revert FailedInnerCall(); } } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason or custom error, it is bubbled * up by this function (like regular Solidity function calls). However, if * the call reverted with no returned reason, this function reverts with a * {FailedInnerCall} error. * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { if (address(this).balance < value) { revert AddressInsufficientBalance(address(this)); } (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an * unsuccessful call. */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata ) internal view returns (bytes memory) { if (!success) { _revert(returndata); } else { // only check if target is a contract if the call was successful and the return data is empty // otherwise we already know that it was a contract if (returndata.length == 0 && target.code.length == 0) { revert AddressEmptyCode(target); } return returndata; } } /** * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the * revert reason or with a default {FailedInnerCall} error. */ function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) { if (!success) { _revert(returndata); } else { return returndata; } } /** * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}. */ function _revert(bytes memory returndata) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert FailedInnerCall(); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Create2.sol) pragma solidity ^0.8.20; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Not enough balance for performing a CREATE2 deploy. */ error Create2InsufficientBalance(uint256 balance, uint256 needed); /** * @dev There's no code to deploy. */ error Create2EmptyBytecode(); /** * @dev The deployment failed. */ error Create2FailedDeployment(); /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) { if (address(this).balance < amount) { revert Create2InsufficientBalance(address(this).balance, amount); } if (bytecode.length == 0) { revert Create2EmptyBytecode(); } /// @solidity memory-safe-assembly assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } if (addr == address(0)) { revert Create2FailedDeployment(); } } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) // Get free memory pointer // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... | // |-------------------|---------------------------------------------------------------------------| // | bytecodeHash | CCCCCCCCCCCCC...CC | // | salt | BBBBBBBBBBBBB...BB | // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA | // | 0xFF | FF | // |-------------------|---------------------------------------------------------------------------| // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC | // | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ | mstore(add(ptr, 0x40), bytecodeHash) mstore(add(ptr, 0x20), salt) mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff mstore8(start, 0xff) addr := keccak256(start, 85) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol) pragma solidity ^0.8.20; /** * @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; /** * @dev Unauthorized reentrant call. */ error ReentrancyGuardReentrantCall(); 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 if (_status == ENTERED) { revert ReentrancyGuardReentrantCall(); } // 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; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol) pragma solidity ^0.8.20; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Muldiv operation overflow. */ error MathOverflowedMulDiv(); enum Rounding { Floor, // Toward negative infinity Ceil, // Toward positive infinity Trunc, // Toward zero Expand // Away from zero } /** * @dev Returns the addition of two unsigned integers, with an overflow flag. */ 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. */ 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. */ 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. */ 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. */ 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 largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds towards infinity instead * of rounding towards zero. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { // Guarantee the same behavior as in a regular Solidity division. return a / b; } // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or * denominator == 0. * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by * Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0 = x * y; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (denominator <= prod1) { revert MathOverflowedMulDiv(); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. // Always >= 1. See https://cs.stackexchange.com/q/138556/92363. uint256 twos = denominator & (0 - denominator); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also // works in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded * towards zero. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256 of a positive value rounded towards zero. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0); } } /** * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers. */ function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) { return uint8(rounding) % 2 == 1; } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { }
// 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; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext( uint16 observationCardinalityNext ) external; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe( uint32[] calldata secondsAgos ) external view returns ( int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s ); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside( int24 tickLower, int24 tickUpper ) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol( uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New ); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol( address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1 ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks( int24 tick ) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions( bytes32 key ) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations( uint256 index ) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/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); }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Create2.sol"; import "@openzeppelin/contracts/access/Ownable2Step.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../interfaces/ITITANX.sol"; import "../libs/TitanStaker.sol"; import "../libs/constant.sol"; /** * @notice Central vault managing staking in TitanX and reward distribution */ contract WyvernVault is Ownable2Step, ReentrancyGuard { using SafeERC20 for IERC20; using SafeERC20 for ITitanX; address public titanBuyAddress; address public wyvernBuyAndBurnAddress; uint256 public vault; uint256 public titanStakerContractsCount; address public activeTitanStakerContract; uint256 public titanStakingStartTimestamp; uint256 public nextTitanStakeTimestamp; uint256 public totalTitanStaked; uint256 public totalTitanUnstaked; uint256 public totalEthRewardsCollected; mapping(uint256 => address) public titanStakerContracts; mapping(address => uint256) private genesisVault; mapping(address => bool) private ethDepositorWhitelist; mapping(address => bool) private titanStakerWhitelist; event TitanStakerCreated(uint256 indexed stakerContractId, address indexed stakerContractAddress); event Collected( address indexed caller, uint256 indexed totalCollected, uint256 titanBuy, uint256 wyvernBuyAndBurn, uint256 genesis, uint256 rewardFee ); event TitanStakeStarted(address indexed titanStakerAddress, uint256 amount); event TitanStakesEnded(address indexed titanStakerAddress, uint256 amount); error InvalidWyvernAddress(); error NoMoreStakesAllowed(); error NoPendingEthRewards(); error NoTokensToStake(); error NewTitanStakerNotNeeded(); error InvalidAddress(); error CooldownPeriodActive(); error InvalidCaller(); error InsufficientBalanceForCallerReward(); /** * @notice Begins a new TitanX staking session if conditions are met * @dev Initiates staking when vault reaches threshold or after cooldown */ function stake() external { TitanStaker titanStaker = TitanStaker( payable(activeTitanStakerContract) ); if (titanStaker.activeTitanXStakes() >= TITANX_MAX_STAKE_PER_WALLET) { revert NoMoreStakesAllowed(); } updateVault(); uint256 vault_ = vault; if (vault_ == 0) { revert NoTokensToStake(); } if (vault_ >= TITANX_BPB_MAX_TITAN) { _startTitanXStake(); nextTitanStakeTimestamp = block.timestamp + 7 days; } else { if (block.timestamp < nextTitanStakeTimestamp) { revert CooldownPeriodActive(); } _startTitanXStake(); nextTitanStakeTimestamp = block.timestamp + 7 days; } } /** * @notice Harvests and splits ETH yields across protocol components * @dev Allocates: 80% TitanX purchase (compound or send to WyvernX stakers), 5% genesis, 5% burn, 7% legacy, 3% caller */ function claim() external nonReentrant returns (uint256 collectedAmount) { if (msg.sender != tx.origin) revert InvalidCaller(); uint256 ethBalanceBefore = address(this).balance; ITitanX(TITANX_ADDRESS).triggerPayouts(); uint256 triggerPayoutsIncentiveFee = address(this).balance - ethBalanceBefore; for (uint256 ids; ids < titanStakerContractsCount; ids++) { TitanStaker titanStaker = TitanStaker( payable(titanStakerContracts[ids]) ); collectedAmount += titanStaker.claim(); } if (collectedAmount == 0) revert NoPendingEthRewards(); // Calculate the genesis share (5%). uint256 genesisShare = (collectedAmount * 500) / PERCENTAGE_BASE_VAULT; // Calculate the tip for the caller (3%). uint256 incentiveFee = (collectedAmount * REWARD_FEE) / PERCENTAGE_BASE_VAULT; // Calculate the Buy and Burn share for Wyvern (7%). uint256 buyAndBurnWyvern = (collectedAmount * 700) / PERCENTAGE_BASE_VAULT; // Calculate the Titan buy share (remainder, ~85%). uint256 buyTitanXshare = collectedAmount - genesisShare - incentiveFee - buyAndBurnWyvern; genesisVault[address(0)] += genesisShare; Address.sendValue(payable(wyvernBuyAndBurnAddress), buyAndBurnWyvern); Address.sendValue(payable(titanBuyAddress), buyTitanXshare); address sender = _msgSender(); uint256 callerReward = incentiveFee + triggerPayoutsIncentiveFee; if (address(this).balance < callerReward) { revert InsufficientBalanceForCallerReward(); } Address.sendValue( payable(sender), callerReward ); totalEthRewardsCollected += collectedAmount; emit Collected( sender, collectedAmount, buyTitanXshare, buyAndBurnWyvern, genesisShare, callerReward ); } constructor( address titanBuyAddress_, address wyvernBuyAndBurnAdddress_, bytes32 deploymentKey_ ) Ownable(msg.sender) { if (titanBuyAddress_ == address(0)) revert InvalidAddress(); if (wyvernBuyAndBurnAdddress_ == address(0)) revert InvalidAddress(); titanBuyAddress = titanBuyAddress_; wyvernBuyAndBurnAddress = wyvernBuyAndBurnAdddress_; ethDepositorWhitelist[TITANX_ADDRESS] = true; _createTitanStaker(deploymentKey_); } /** * @notice Creates a new TitanStaker contract if the current one is full. * @dev Uses a user-provided salt for unique deployment. * @param deploymentKey Salt for contract creation. */ function createNewTitanStaker(bytes32 deploymentKey) external { TitanStaker titanStaker = TitanStaker( payable(activeTitanStakerContract) ); if (titanStaker.activeTitanXStakes() < TITANX_MAX_STAKE_PER_WALLET) revert NewTitanStakerNotNeeded(); _createTitanStaker(deploymentKey); } /** * @notice Totals stakes across all TitanStaker contracts. * @dev Iterates and sums stakes from each contract. * @return totalActiveStakes Total stakes across contracts. */ function totalActiveStakesInTitanStakers() external view returns (uint256 totalActiveStakes) { for (uint256 ids; ids < titanStakerContractsCount; ids++) { TitanStaker titanStaker = TitanStaker( payable(titanStakerContracts[ids]) ); totalActiveStakes += titanStaker.activeTitanXStakes(); } } /** * @dev Scans all TitanStaker contracts for completed stakes. * Returns true, titanStaker address, and stake ID if found. * Otherwise, returns false, zero address, and zero ID. * @return hasCompletedStakes True if a completed stake exists. * @return titanStakerAddress Address of the titanStaker with a completed stake. * @return stakeId ID of the completed stake, or zero if none. */ function getAllCompletedStakes() external view returns (bool hasCompletedStakes, address titanStakerAddress, uint256 stakeId) { for (uint256 ids; ids < titanStakerContractsCount; ids++) { address titanStakerAddress_ = titanStakerContracts[ids]; TitanStaker titanStaker = TitanStaker(payable(titanStakerAddress_)); (bool isCompleted, uint256 completedStakeId) = titanStaker .checkForCompletedStakes(); if (isCompleted) return (true, titanStakerAddress_, completedStakeId); } return (false, address(0), 0); } /** * @notice Sets the initial timestamps for staking in TitanX Protocol. */ function allowTitanStaking() external { address wyvernBuyAndBurnAddress_ = wyvernBuyAndBurnAddress; require(msg.sender == wyvernBuyAndBurnAddress_, "unauthorized to allowTitanStaking"); uint256 nowTimestamp = block.timestamp; uint256 secondsToMidnight = SECONDS_IN_DAY - (nowTimestamp % SECONDS_IN_DAY); titanStakingStartTimestamp = nowTimestamp + secondsToMidnight; nextTitanStakeTimestamp = titanStakingStartTimestamp + STAKE_COOLDOWN_PERIOD; } modifier onlyTitanStaker() { require(titanStakerWhitelist[_msgSender()], "not permitted"); _; } /** * @dev Adjusts state after TitanX tokens are unstaked. * Only callable by authorized TitanStaker addresses. * @param amountWithdrawn Amount of TitanX tokens unstaked. * @notice Emits `TitanStakesEnded` event. */ function stakeEnded(uint256 amountWithdrawn) external onlyTitanStaker { updateVault(); totalTitanUnstaked += amountWithdrawn; emit TitanStakesEnded(_msgSender(), amountWithdrawn); } /** * @notice Updates Titan Buy contract address. * @dev Only owner can set a non-zero address. * @param titanBuyAddress_ New contract address. */ function setTitanBuyContractAddress(address titanBuyAddress_) external onlyOwner { if (titanBuyAddress_ == address(0)) revert InvalidAddress(); titanBuyAddress = titanBuyAddress_; } /** * @notice Updates Wyvern Buy & Burn contract address. * @dev Only owner can set a non-zero address. * @param wyvernBuyAndBurnAddress_ New contract address. */ function setWyvernBuyAndBurnContractAddress(address wyvernBuyAndBurnAddress_) external onlyOwner { if (wyvernBuyAndBurnAddress_ == address(0)) revert InvalidAddress(); wyvernBuyAndBurnAddress = wyvernBuyAndBurnAddress_; } /** * @notice Refreshes vault's available TitanX balance * @dev Calculates net holdings excluding genesis allocation */ function updateVault() public { IERC20 titanX = IERC20(TITANX_ADDRESS); uint256 balance = titanX.balanceOf(address(this)); vault = balance - genesisVault[address(titanX)]; } /** * @notice Queries available TitanX for new stakes * @dev Returns net balance minus genesis allocation */ function getTotalTitanBalanceInVault() public view returns (uint256) { return IERC20(TITANX_ADDRESS).balanceOf(address(this)) - genesisVault[address(IERC20(TITANX_ADDRESS))]; } /** * @notice Aggregates pending ETH rewards across all stakes * @dev Scans all active stake contracts for pending rewards */ function totalPendingEthRewards() public view returns (uint256 pendingRewards) { for (uint256 ids; ids < titanStakerContractsCount; ids++) { TitanStaker titanStaker = TitanStaker( payable(titanStakerContracts[ids]) ); pendingRewards += titanStaker.totalPendingEthRewards(); } } /** * @notice Calculates total active TitanX stakes * @dev Combines shares from all staker contracts */ function getCombinedWyvernActiveShares() public view returns (uint256) { uint256 combinedActiveShares; for (uint256 ids; ids < titanStakerContractsCount; ids++) { combinedActiveShares += ITitanX(TITANX_ADDRESS).getUserCurrentActiveShares(titanStakerContracts[ids]); } return combinedActiveShares; } /** * @notice Calculates the percentage of total Wyvern active shares in relation to global TitanX active shares. * @return percentage The percentage of total Wyvern active shares relative to global TitanX active shares. */ function getWyvernActiveSharesPercentage() external view returns (uint256 percentage) { uint256 combinedWyvernActiveShares = getCombinedWyvernActiveShares(); ITitanX titanX = ITitanX(TITANX_ADDRESS); uint256 totalGlobalTitanXActiveShares = titanX.getGlobalActiveShares(); if (totalGlobalTitanXActiveShares == 0) { return 0; } // Use a larger scaling factor first to prevent loss of precision uint256 scaledShares = combinedWyvernActiveShares * SCALING_FACTOR_1e6; // Then divide by totalGlobalTitanXActiveShares percentage = (scaledShares / totalGlobalTitanXActiveShares); return percentage; } /** * @notice Allows the owner to withdraw assets from the Genesis Vault. * @dev If `asset` is zero address, Ether is collected, else ERC20 tokens are transferred. * @param asset Asset address to claim; zero address for Ether, non-zero for ERC20. */ function withdrawFromGenesis(address asset) external onlyOwner { uint256 balance = genesisVault[asset]; genesisVault[asset] = 0; require(balance > 0, "nothing to collect"); if (asset == address(0)) { Address.sendValue(payable(owner()), balance); } else { IERC20 erc20 = IERC20(asset); erc20.safeTransfer(owner(), balance); } } /** * @dev Computes the reward for executing a claim. * @return reward The incentive reward. */ function callerRewardFeeForCallingClaim() external view returns (uint256 reward) { reward = (totalPendingEthRewards() * REWARD_FEE) / PERCENTAGE_BASE_VAULT; } /** * @notice Spawns new staker contract with deterministic address * @dev Uses CREATE2 for deployment and updates registry */ function _createTitanStaker(bytes32 deploymentKey) private { bytes memory bytecode = abi.encodePacked(type(TitanStaker).creationCode, abi.encode(address(this))); uint256 stakerContractId = titanStakerContractsCount; bytes32 salt = keccak256( abi.encodePacked(address(this), stakerContractId, blockhash(block.number - 1), deploymentKey) ); address precomputedAddress = Create2.computeAddress(salt, keccak256(bytecode), address(this)); require(_isAddressUnoccupied(precomputedAddress), "Address already exists"); address newTitanStakerContract = Create2.deploy(0, salt, bytecode); require(newTitanStakerContract != address(0), "Deployment failed"); require(newTitanStakerContract == precomputedAddress, "Address mismatch"); activeTitanStakerContract = newTitanStakerContract; titanStakerContracts[stakerContractId] = newTitanStakerContract; ethDepositorWhitelist[newTitanStakerContract] = true; titanStakerWhitelist[newTitanStakerContract] = true; emit TitanStakerCreated( stakerContractId, newTitanStakerContract ); titanStakerContractsCount += 1; } /** * @notice Locks available TitanX in current stake contract * @dev Transfers and initiates maximum duration stake */ function _startTitanXStake() private { address activeTitanStakerContract_ = activeTitanStakerContract; ITitanX titanX = ITitanX(TITANX_ADDRESS); TitanStaker titanStaker = TitanStaker( payable(activeTitanStakerContract_) ); uint256 amountToStake = vault; vault = 0; titanX.safeTransfer(activeTitanStakerContract_, amountToStake); titanStaker.stake(); totalTitanStaked += amountToStake; emit TitanStakeStarted(activeTitanStakerContract_, amountToStake); } /** * @notice Validates deployment address availability * @dev Checks for existing contract bytecode */ function _isAddressUnoccupied(address addr) private view returns (bool) { uint256 codeSize; assembly { codeSize := extcodesize(addr) } return codeSize == 0; } // NATIVE TOKEN HANDLING /** * @notice Processes incoming native token deposits * Reverts if the sender is not whitelisted. */ receive() external payable { require(ethDepositorWhitelist[msg.sender], "Sender unauthorized"); } /** * @notice Handles unexpected contract interactions * @dev Blocks unintended native token transfers */ fallback() external { revert("Fallback triggered"); } }
// SPDX-License-Identifier: UNLICENSED //██╗ ██╗██╗ ██╗██╗ ██╗███████╗██████╗ ███╗ ██╗██╗ ██╗ ██╗███████╗ ██████╗ ██╗ ██╗██╗██╗ ████████╗ ██████╗ ███╗ ██╗ ████████╗██╗████████╗ █████╗ ███╗ ██╗██╗ ██╗ //██║ ██║╚██╗ ██╔╝██║ ██║██╔════╝██╔══██╗████╗ ██║╚██╗██╔╝ ██║██╔════╝ ██╔══██╗██║ ██║██║██║ ╚══██╔══╝ ██╔═══██╗████╗ ██║ ╚══██╔══╝██║╚══██╔══╝██╔══██╗████╗ ██║╚██╗██╔╝ //██║ █╗ ██║ ╚████╔╝ ██║ ██║█████╗ ██████╔╝██╔██╗ ██║ ╚███╔╝ ██║███████╗ ██████╔╝██║ ██║██║██║ ██║ ██║ ██║██╔██╗ ██║ ██║ ██║ ██║ ███████║██╔██╗ ██║ ╚███╔╝ //██║███╗██║ ╚██╔╝ ╚██╗ ██╔╝██╔══╝ ██╔══██╗██║╚██╗██║ ██╔██╗ ██║╚════██║ ██╔══██╗██║ ██║██║██║ ██║ ██║ ██║██║╚██╗██║ ██║ ██║ ██║ ██╔══██║██║╚██╗██║ ██╔██╗ //╚███╔███╔╝ ██║ ╚████╔╝ ███████╗██║ ██║██║ ╚████║██╔╝ ██╗ ██║███████║ ██████╔╝╚██████╔╝██║███████╗██║ ╚██████╔╝██║ ╚████║ ██║ ██║ ██║ ██║ ██║██║ ╚████║██╔╝ ██╗ //╚══╝╚══╝ ╚═╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ //██╗ ██╗██╗ ██╗██╗ ██╗███████╗██████╗ ███╗ ██╗██╗ ██╗ ██╗███████╗ ██╗ ██╗ ██████╗ ███████╗███████╗██╗██████╗ ██████╗ //██║ ██║╚██╗ ██╔╝██║ ██║██╔════╝██╔══██╗████╗ ██║╚██╗██╔╝ ██║██╔════╝ ████████╗██╔══██╗██╔════╝██╔════╝██║╚════██╗ ██╔═████╗ //██║ █╗ ██║ ╚████╔╝ ██║ ██║█████╗ ██████╔╝██╔██╗ ██║ ╚███╔╝ ██║███████╗ ╚██╔═██╔╝██║ ██║█████╗ █████╗ ██║ █████╔╝ ██║██╔██║ //██║███╗██║ ╚██╔╝ ╚██╗ ██╔╝██╔══╝ ██╔══██╗██║╚██╗██║ ██╔██╗ ██║╚════██║ ████████╗██║ ██║██╔══╝ ██╔══╝ ██║ ╚═══██╗ ████╔╝██║ //╚███╔███╔╝ ██║ ╚████╔╝ ███████╗██║ ██║██║ ╚████║██╔╝ ██╗ ██║███████║ ╚██╔═██╔╝██████╔╝███████╗██║ ██║██████╔╝██╗╚██████╔╝ //╚══╝╚══╝ ╚═╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ pragma solidity ^0.8.20; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../interfaces/IWyvernOnBurn.sol"; import "../interfaces/IWyvernX.sol"; import "../interfaces/ITITANX.sol"; import "../libs/utilFunctions.sol"; import "../libs/TitanStaker.sol"; import "../libs/DifficultyLevel.sol"; import "../libs/HuntersGuild.sol"; import "../libs/Guardian.sol"; import "./WyvernVault.sol"; /** @title WyvernX is born */ contract WyvernX is ERC20, ReentrancyGuard, DifficultyLevel, HuntersGuild, Guardian { using SafeERC20 for IERC20; using SafeERC20 for ITitanX; address private s_genesisAddress; address private s_buyAndBurnAddress; address private s_wyvernVaultAddress; address private s_titanXAddress; address private s_liquidityBondingAddress; uint256 private s_undistributedLoot; uint256 private s_claimingEnabledTimestamp; /** @dev tracks if LP tokens have been minted */ WyvernManaPoolMinted private s_manaPoolMinted; /** @dev tracks if claiming of WyvernX Hunters is already possible */ ClaimingEnabled private s_claimingFrozen; /** @dev tracks if minting of WyvernX is no longer possible */ WyvernMintingPhaseFinished private s_mintingPhaseFinished; event LootReceived(address indexed user, uint256 indexed day, uint256 indexed amount); event TitanXLootDistributed(address indexed caller, uint256 indexed amount); event CycleWarChestTriggered( address indexed caller, uint256 indexed cycleNo, uint256 indexed reward ); event WarChestLootClaimed(address indexed user, uint256 indexed reward); error InsufficientBalance(); error GuildFeesTooLow(); error NotAllowed(); error NoCycleRewardToClaim(); error WarChestNotDepositedYet(); error EmptyUndistributeFees(); error InvalidBatchCount(); error MaxedWalletHunters(); error Wyvern_InvalidAddress(); error MintingPhaseFinished(); error InsufficientTitanXAllowance(); error InsufficientTitanXBalance(); error ClaimingFrozen(); /** * @notice Constructor for the WyvernX ERC20 Token Contract. * @param genesisAddress The address of the Genesis wallet address. * @param wyvernVaultAddress The address of the WyvernX Vault contract. */ constructor(address genesisAddress, address wyvernVaultAddress) ERC20("WyvernX", "WyvernX") { if (genesisAddress == address(0)) revert Wyvern_InvalidAddress(); if (wyvernVaultAddress == address(0)) revert Wyvern_InvalidAddress(); s_liquidityBondingAddress = LIQUIDITY_BONDING_ADDR; s_genesisAddress = genesisAddress; s_wyvernVaultAddress = wyvernVaultAddress; s_manaPoolMinted = WyvernManaPoolMinted.NO; s_mintingPhaseFinished = WyvernMintingPhaseFinished.NO; } /** @notice Recruit a new hunter to the guild * @param strength Hunter strength from 1 to 100 * @param huntDays Hunt duration from 1 to 280 days * @param amount TitanX tokens required for recruitment */ function hireHunter( uint256 strength, uint256 huntDays, uint256 amount ) external nonReentrant increaseDifficultyLevel { if (getUserLatestHunterId(_msgSender()) + 1 > MAX_HUNTERS_PER_WALLET) revert MaxedWalletHunters(); WyvernVault wyvernVault = WyvernVault(payable(s_wyvernVaultAddress)); // Get WyvernX current percentage of shares in TitanX uint256 activeSharesPercentage = wyvernVault.getWyvernActiveSharesPercentage(); // prevent minting if minting phase is over if (s_mintingPhaseFinished == WyvernMintingPhaseFinished.YES) revert MintingPhaseFinished(); if (activeSharesPercentage >= MINIMUM_SHAREPOOL_FOR_MINTING_PHASE) { // finish minting phase s_mintingPhaseFinished = WyvernMintingPhaseFinished.YES; } ITitanX titanX = ITitanX(TITANX_ADDRESS); if (titanX.allowance(_msgSender(), address(this)) < amount) revert InsufficientTitanXAllowance(); if (titanX.balanceOf(_msgSender()) < amount) revert InsufficientTitanXBalance(); uint256 gStrength = getGlobalGuildStrength() + strength; uint256 currentWRank = getGlobalWRank() + 1; uint256 latestHunterCost = getLatestHunterCost(); uint256 batchHunterCost = getBatchHunterCost(strength, 1, latestHunterCost); uint256 totalBeingLooted = getTotalWyvernBeingLooted() + _hireHunter( _msgSender(), strength, huntDays, getCurrentLootableWyvern(), getLatestHunterStrengthBonus(), getCurrentEarlyHunterBonus(), gStrength, currentWRank, batchHunterCost ); _updateHunterStats(currentWRank, gStrength, totalBeingLooted); _guildFees(strength, 1, amount); } /** @notice Recruit multiple hunters simultaneously * @param strength Hunter strength from 1 to 100 * @param huntDays Hunt duration from 1 to 280 days * @param count Number of hunters to recruit (1-100) * @param amount TitanX tokens required for recruitment */ function batchHire( uint256 strength, uint256 huntDays, uint256 count, uint256 amount ) external payable nonReentrant increaseDifficultyLevel { if (count == 0 || count > MAX_BATCH_HIRE_COUNT) revert InvalidBatchCount(); if (getUserLatestHunterId(_msgSender()) + count > MAX_HUNTERS_PER_WALLET) revert MaxedWalletHunters(); WyvernVault wyvernVault = WyvernVault(payable(s_wyvernVaultAddress)); // Get WyvernX current percentage of shares in TitanX uint256 activeSharesPercentage = wyvernVault.getWyvernActiveSharesPercentage(); // prevent hiring Hunters if minting phase is over if (s_mintingPhaseFinished == WyvernMintingPhaseFinished.YES) revert MintingPhaseFinished(); if (activeSharesPercentage >= MINIMUM_SHAREPOOL_FOR_MINTING_PHASE) { // finish minting phase s_mintingPhaseFinished = WyvernMintingPhaseFinished.YES; } ITitanX titanX = ITitanX(TITANX_ADDRESS); if (titanX.allowance(_msgSender(), address(this)) < amount) revert InsufficientTitanXAllowance(); if (titanX.balanceOf(_msgSender()) < amount) revert InsufficientTitanXBalance(); _hireHunterSquad( _msgSender(), strength, huntDays, getCurrentLootableWyvern(), getLatestHunterStrengthBonus(), getCurrentEarlyHunterBonus(), count, getBatchHunterCost(strength, 1, getLatestHunterCost()) ); _guildFees(strength, count, amount); } /** @notice claim hunter * @param id hunter id */ function claimHunter(uint256 id) external increaseDifficultyLevel nonReentrant { if (!isClaimingEnabled()) revert ClaimingFrozen(); _mintReward(_claimHunter(_msgSender(), id, HunterAction.CLAIM)); } /** @notice batch claim up to 100 hunters */ function batchClaimHunter() external increaseDifficultyLevel nonReentrant { if (!isClaimingEnabled()) revert ClaimingFrozen(); _mintReward(_batchClaimHunters(_msgSender())); } /** @notice deposit WarChest * @param amount Wyvern amount * @param lockPeriod deposit lock Period */ function depositWarChest(uint256 amount, uint256 lockPeriod) external increaseDifficultyLevel nonReentrant { if (balanceOf(_msgSender()) < amount) revert InsufficientBalance(); _burn(_msgSender(), amount); _initFirstSharesCycleIndex( _msgSender(), _depositToWarChest( _msgSender(), amount, lockPeriod, getLatestInfluenceRate(), getCurrentDay(), getGlobalWarChestLootTriggered() ) ); } /** @notice withdraw warChest deposit * @param id depositId */ function withdrawWarChest(uint256 id) external increaseDifficultyLevel nonReentrant { _mint( _msgSender(), _withdrawWarChestDeposit( _msgSender(), id, getCurrentDay(), DepositAction.END, getGlobalWarChestLootTriggered() ) ); } /** @notice distribute the collected guild loot into different parties/warChests */ function distributeLoot() external increaseDifficultyLevel nonReentrant { (uint256 rewardFee, uint256 genesisWallet, uint256 vaultFunds, uint256 liquidityBondingFunds) = _distributeTitanX(); _sendFunds(rewardFee, genesisWallet, vaultFunds, liquidityBondingFunds); } /** @notice Activate War Chest loot distribution for cycle days 8, 28, 90, 369, 888 * As long as the cycle has met its maturity day (eg. Cycle28 is day 28), payout can be triggered in any day onwards */ function activateWarChest() external increaseDifficultyLevel nonReentrant { uint256 protocolTotalInfluence = getTotalInfluence() - getTotalExpiredInfluence(); if (protocolTotalInfluence < 1) revert WarChestNotDepositedYet(); uint256 rewardFee; uint256 genesisWallet; uint256 vaultFunds; uint256 liquidityBondingFunds; if (s_undistributedLoot != 0) (rewardFee, genesisWallet, vaultFunds, liquidityBondingFunds) = _distributeTitanX(); uint256 currentDay_ = getCurrentDay(); WarChestLootTriggered isTriggered = WarChestLootTriggered.NO; _activateCycleWarChest(DAY8, protocolTotalInfluence, currentDay_) == WarChestLootTriggered.YES && isTriggered == WarChestLootTriggered.NO ? isTriggered = WarChestLootTriggered.YES : isTriggered; _activateCycleWarChest(DAY28, protocolTotalInfluence, currentDay_) == WarChestLootTriggered.YES && isTriggered == WarChestLootTriggered.NO ? isTriggered = WarChestLootTriggered.YES : isTriggered; _activateCycleWarChest(DAY90, protocolTotalInfluence, currentDay_) == WarChestLootTriggered.YES && isTriggered == WarChestLootTriggered.NO ? isTriggered = WarChestLootTriggered.YES : isTriggered; _activateCycleWarChest(DAY369, protocolTotalInfluence, currentDay_) == WarChestLootTriggered.YES && isTriggered == WarChestLootTriggered.NO ? isTriggered = WarChestLootTriggered.YES : isTriggered; _activateCycleWarChest(DAY888, protocolTotalInfluence, currentDay_) == WarChestLootTriggered.YES && isTriggered == WarChestLootTriggered.NO ? isTriggered = WarChestLootTriggered.YES : isTriggered; if (isTriggered == WarChestLootTriggered.YES) { if (getGlobalWarChestLootTriggered() == WarChestLootTriggered.NO) _setGlobalWarChestLootTriggered(); } if (rewardFee != 0) _sendFunds(rewardFee, genesisWallet, vaultFunds, liquidityBondingFunds); } /** @notice claim all user available TitanX WarChest loot */ function claimUserAvailableTitanWarChestLoot() external increaseDifficultyLevel nonReentrant { uint256 reward = _claimCycleLoot(DAY8, CycleLootClaim.INFLUENCE); reward += _claimCycleLoot(DAY28, CycleLootClaim.INFLUENCE); reward += _claimCycleLoot(DAY90, CycleLootClaim.INFLUENCE); reward += _claimCycleLoot(DAY369, CycleLootClaim.INFLUENCE); reward += _claimCycleLoot(DAY888, CycleLootClaim.INFLUENCE); if (reward == 0) revert NoCycleRewardToClaim(); IERC20 titanX = IERC20(TITANX_ADDRESS); titanX.safeTransfer(_msgSender(), reward); emit WarChestLootClaimed(_msgSender(), reward); } /** @notice Enable claiming of WyvernX Hunters on 281 WyvernX Contract Day * Only owner can call this function */ function enableClaiming() external onlyOwner { require(s_claimingFrozen == ClaimingEnabled.NO, "Claiming already enabled"); s_claimingFrozen = ClaimingEnabled.YES; s_claimingEnabledTimestamp = block.timestamp; } /** @notice Set to new genesis wallet. Only genesis wallet can call this function * @param newAddress new genesis wallet address */ function setNewGenesisAddress(address newAddress) external { if (_msgSender() != s_genesisAddress) revert NotAllowed(); if (newAddress == address(0)) revert Wyvern_InvalidAddress(); s_genesisAddress = newAddress; } /** @notice Set BuyAndBurn Contract Address - able to change to new contract that supports UniswapV4+ * Only owner can call this function * @param contractAddress BuyAndBurn contract address */ function setBuyAndBurnContractAddress(address contractAddress) external onlyOwner { if (contractAddress == address(0)) revert Wyvern_InvalidAddress(); s_buyAndBurnAddress = contractAddress; } /** @notice Set WyvernVault Contract Address * Only owner can call this function * @param contractAddress WyvernVault contract address */ function setWyvernVaultContractAddress(address contractAddress) external onlyOwner { if (contractAddress == address(0)) revert Wyvern_InvalidAddress(); s_wyvernVaultAddress = contractAddress; } /** @notice Set TitanX Contract Address * Only owner can call this function * @param contractAddress TitanX contract address */ function setTitanXContractAddress(address contractAddress) external onlyOwner { if (contractAddress == address(0)) revert Wyvern_InvalidAddress(); s_titanXAddress = contractAddress; } /** @notice Set Liquidity Bonding Address * Only owner can call this function * @param newAddress Liquidity Bonding Address */ function setLiquidityBondingAddress(address newAddress) external onlyOwner { if (newAddress == address(0)) revert Wyvern_InvalidAddress(); s_liquidityBondingAddress = newAddress; } /** * @notice Mints the initial liquidity for the WyvernX token. * @dev This function mints a specified amount of tokens and sets up the TitanX staking phases. * It can only be called once by the authorized Buy&Burn contract address. * @param amount The amount of WyvernX tokens to be minted for initial liquidity. */ function mintInitialLiquidity(uint256 amount) external { address buyAndBurnAddress_ = s_buyAndBurnAddress; require(msg.sender == buyAndBurnAddress_, "must be B&B contract"); require( s_manaPoolMinted == WyvernManaPoolMinted.NO, "mana already minted" ); _mint(buyAndBurnAddress_, amount); s_manaPoolMinted = WyvernManaPoolMinted.YES; } /** @notice burn all BuyAndBurn contract WyvernX tokens */ function burnLPTokens() external increaseDifficultyLevel { _burn(s_buyAndBurnAddress, balanceOf(s_buyAndBurnAddress)); } /** @notice Returns if claiming is enabled * @return true if claiming is enabled, false otherwise */ function isClaimingEnabled() public view returns (bool) { return s_claimingFrozen == ClaimingEnabled.YES || getCurrentDay() >= AUTO_ENABLE_MINT_CLAIMING_DAY; } /** @notice Returns the start time of the claiming period * @return start time of the WyvernX Hunters claiming period */ function getClaimingStartTime() external view returns (uint256) { return s_claimingEnabledTimestamp; } // ----------------------------------------- // Private functions // ----------------------------------------- /** @dev mint reward to user and 3% to genesis wallet * @param reward WyvernX amount */ function _mintReward(uint256 reward) private { _mint(_msgSender(), reward); _mint(s_genesisAddress, (reward * 300) / PERCENT_BPS); } /** @dev send TitanX fess to respective parties * @param incentiveFee fees for caller to run distributeFees() * @param genesisWalletFunds funds for genesis wallet * @param vaultFunds funds for TitanX vault inside of Wyvern * @param liquidityBondingFunds funds for liquidity bonding */ function _sendFunds( uint256 incentiveFee, uint256 genesisWalletFunds, uint256 vaultFunds, uint256 liquidityBondingFunds ) private { IERC20 titanX = IERC20(TITANX_ADDRESS); titanX.safeTransfer(_msgSender(), incentiveFee); titanX.safeTransfer(s_genesisAddress, genesisWalletFunds); titanX.safeTransfer(s_liquidityBondingAddress, liquidityBondingFunds); // stop sending TitanX to Vault if minting phase is over if (s_mintingPhaseFinished != WyvernMintingPhaseFinished.YES) { titanX.safeTransfer(s_wyvernVaultAddress, vaultFunds); } } /** @dev calculation to distribute collected protocol fees into different pools/parties */ function _distributeTitanX() private returns (uint256 incentiveFee, uint256 genesisWallet, uint256 vaultFunds, uint256 liquidityBondingFunds) { updateUndistributedLoot(); uint256 accumulatedFees = s_undistributedLoot; if (accumulatedFees == 0) revert EmptyUndistributeFees(); s_undistributedLoot = 0; emit TitanXLootDistributed(_msgSender(), accumulatedFees); incentiveFee = (accumulatedFees * REWARD_FEE_PERCENT) / REWARD_FEE_PERCENTAGE_BASE_WYVERNX; //3% accumulatedFees -= incentiveFee; vaultFunds = 0; // Only calculate and distribute TitanX to the Vault if minting phase has not ended if (s_mintingPhaseFinished != WyvernMintingPhaseFinished.YES) { vaultFunds = (accumulatedFees * PERCENT_TO_WYVERN_VAULT) / PERCENT_BPS; } genesisWallet = (accumulatedFees * PERCENT_TO_GENESIS) / PERCENT_BPS; liquidityBondingFunds = (accumulatedFees * PERCENT_TO_LIQUIDITY_BONDING) / PERCENT_BPS; uint256 cycleRewardPool = accumulatedFees - genesisWallet - vaultFunds - liquidityBondingFunds; //cycle payout if (cycleRewardPool != 0) { uint256 cycle8Reward = (cycleRewardPool * CYCLE_8_PERCENT) / PERCENT_BPS; uint256 cycle28Reward = (cycleRewardPool * CYCLE_28_PERCENT) / PERCENT_BPS; uint256 cycle90Reward = (cycleRewardPool * CYCLE_90_PERCENT) / PERCENT_BPS; uint256 cycle369Reward = (cycleRewardPool * CYCLE_369_PERCENT) / PERCENT_BPS; _setCycleWarChest(DAY8, cycle8Reward); _setCycleWarChest(DAY28, cycle28Reward); _setCycleWarChest(DAY90, cycle90Reward); _setCycleWarChest(DAY369, cycle369Reward); _setCycleWarChest( DAY888, cycleRewardPool - cycle8Reward - cycle28Reward - cycle90Reward - cycle369Reward ); } } /** @dev calculate required guild fees, and return the balance * @param strength strength 1-100 * @param count how many hunters */ function _guildFees(uint256 strength, uint256 count, uint256 amount) private { uint256 guildFee = getBatchHunterCost(strength, count, getLatestHunterCost()); if (amount < guildFee) revert GuildFeesTooLow(); ITitanX titanX = ITitanX(TITANX_ADDRESS); titanX.safeTransferFrom(_msgSender(), address(this), amount); s_undistributedLoot += uint256(amount); emit LootReceived(_msgSender(), getCurrentDay(), amount); } /** @dev calculate loot for each cycle day * @param cycleNo cycle day 8, 28, 90, 369, 888 * @param protocolTotalInfluence total amount of active influence * @param currentDay current day * @return triggered is WarChest Loot Triggered */ function _activateCycleWarChest( uint256 cycleNo, uint256 protocolTotalInfluence, uint256 currentDay ) private returns (WarChestLootTriggered triggered) { if (currentDay < getNextCycleLootDay(cycleNo)) return WarChestLootTriggered.NO; _setNextCycleWarChestDay(cycleNo); uint256 reward = getCycleLootWarChest(cycleNo); if (reward == 0) return WarChestLootTriggered.NO; _calcCycleLootPerInfluence(cycleNo, reward, protocolTotalInfluence); emit CycleWarChestTriggered(_msgSender(), cycleNo, reward); return WarChestLootTriggered.YES; } /** @dev calculate user's loot with specified cycle day and and update user's last claim cycle index * @param cycleNo cycle day 8, 28, 90, 369, 888 * @param cycleLootClaim claim type - (Influence=0) */ function _claimCycleLoot(uint256 cycleNo, CycleLootClaim cycleLootClaim) private returns (uint256) { ( uint256 reward, uint256 userClaimCycleIndex, uint256 userClaimInfluenceIndex ) = _calculateUserCycleReward(_msgSender(), cycleNo, cycleLootClaim); if (cycleLootClaim == CycleLootClaim.INFLUENCE) _updateUserClaimIndexes( _msgSender(), cycleNo, userClaimCycleIndex, userClaimInfluenceIndex ); return reward; } /** @dev calculate user loot with specified cycle day and claim type. * @param user user address * @param cycleNo cycle day 8, 28, 90, 369, 888 * @param cycleLootClaim claim type * @return rewards calculated reward * @return userClaimCycleIndex last claim cycle index * @return userClaimInfluenceIndex last Claim Influence Index */ function _calculateUserCycleReward(address user, uint256 cycleNo, CycleLootClaim cycleLootClaim) private view returns ( uint256 rewards, uint256 userClaimCycleIndex, uint256 userClaimInfluenceIndex ) { uint256 cycleMaxIndex = getCurrentCycleLootIndex(cycleNo); if (cycleLootClaim == CycleLootClaim.INFLUENCE) { (userClaimCycleIndex, userClaimInfluenceIndex) = getUserLastClaimIndex(user, cycleNo); uint256 influenceMaxIndex = getUserCurrentInfluenceIndex(user); for (uint256 i = userClaimCycleIndex; i <= cycleMaxIndex; i++) { (uint256 lootPerInfluence, uint256 lootDay) = getLootPerInfluence(cycleNo, i); uint256 influence; for (uint256 j = userClaimInfluenceIndex; j <= influenceMaxIndex; j++) { if (getUserInfluenceDayFromInfluenceIndex(user, j) <= lootDay) influence = getUserInfluenceAtIndex(user, j); else break; userClaimInfluenceIndex = j; } if (lootPerInfluence != 0 && influence != 0) { rewards += (influence * lootPerInfluence) / SCALING_FACTOR_1e18; } userClaimCycleIndex = i + 1; } } } /** * @notice Updates the undistributed loot balance to match the current TITANX token balance. * @dev Refreshes s_undistributedLoot by querying the contract's TITANX holdings. */ function updateUndistributedLoot() public { IERC20 titanX = IERC20(TITANX_ADDRESS); uint256 balance = titanX.balanceOf(address(this)); s_undistributedLoot = balance; } /** @notice get contract TitanX balance * @return balance TitanX balance */ function getTitanXBalance() public view returns (uint256) { IERC20 titanX = IERC20(TITANX_ADDRESS); return titanX.balanceOf(address(this)); } /** @notice get undistributed loot balance * @return amount of loot fees that were generated from hunters and TitanX staking rewards */ function getUndistributedLoot() public view returns (uint256) { return s_undistributedLoot; } /** @notice get user TitanX payout for all cycles * @param user user address * @return reward total reward */ function getUserTitanClaimableTotal(address user) public view returns (uint256 reward) { uint256 _reward; (_reward, , ) = _calculateUserCycleReward(user, DAY8, CycleLootClaim.INFLUENCE); reward += _reward; (_reward, , ) = _calculateUserCycleReward(user, DAY28, CycleLootClaim.INFLUENCE); reward += _reward; (_reward, , ) = _calculateUserCycleReward(user, DAY90, CycleLootClaim.INFLUENCE); reward += _reward; (_reward, , ) = _calculateUserCycleReward(user, DAY369, CycleLootClaim.INFLUENCE); reward += _reward; (_reward, , ) = _calculateUserCycleReward(user, DAY888, CycleLootClaim.INFLUENCE); reward += _reward; } /** @notice Public function to return the total minted WyvernX * @return total amount of WyvernX minted */ function getTotalWyvernRewardsMinted() public view returns (uint256) { return getTotalLootedWyvern(); } //Public function for updating difficulty level /** @notice allow anyone to sync increaseDifficultyLevel manually */ function manualIncreaseLevelDifficulty() public increaseDifficultyLevel {} /** @notice Public function to return the current Vault address * @return vault address */ function getWyvernVaultAddress() public view returns (address) { return s_wyvernVaultAddress; } /** @notice Public function to return the current status of minting * @return minting status 0 or 1 */ function getIsMintingPhaseFinished() public view returns (WyvernMintingPhaseFinished) { return s_mintingPhaseFinished; } // NATIVE TOKEN HANDLING /** * @dev Receive function to handle plain Ether transfers. * Reverts on all ETH deposits as WyvernX doesn't utilize ETH in its core functionality. */ receive() external payable { revert("ETH not accepted"); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.20; /** * @notice A subset of the Uniswap Interface to allow * using latest openzeppelin contracts */ interface INonfungiblePositionManager { // Structs for mint and collect functions struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to achieve resulting liquidity /// @return amount1 The amount of token1 to achieve resulting liquidity function increaseLiquidity( IncreaseLiquidityParams calldata params ) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } // Functions function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); function mint( MintParams calldata params ) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); function collect( CollectParams calldata params ) external payable returns (uint256 amount0, uint256 amount1); }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.20; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; enum StakeStatus { ACTIVE, ENDED } struct UserStakeInfo { uint152 titanAmount; uint128 shares; uint16 numOfDays; uint48 stakeStartTs; uint48 maturityTs; StakeStatus status; } struct UserStake { uint256 sId; uint256 globalStakeId; UserStakeInfo stakeInfo; } interface IStakeInfo { function getUserStakes(address user) external view returns (UserStake[] memory); function getUserStakeInfo(address user, uint256 id) external view returns (UserStakeInfo memory); function getGlobalActiveShares() external view returns (uint256); function getUserCurrentActiveShares(address user) external view returns (uint256); } /** * @title The TitanX interface used by WyvernX to manage stakes */ interface ITitanX is IERC20, IStakeInfo { function startStake(uint256 amount, uint256 numOfDays) external; function claimUserAvailableETHPayouts() external; function getUserETHClaimableTotal(address user) external view returns (uint256 reward); function manualDailyUpdate() external; function triggerPayouts() external; function startMint(uint256 mintPower, uint256 numOfDays) external payable; function batchMint(uint256 mintPower, uint256 numOfDays, uint256 count) external payable; function getCurrentMintCost() external view returns (uint256); function endStake(uint256 id) external; }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.20; // OpenZeppelin import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; interface IWyvernOnBurn { function onBurn(address user, uint256 amount) external; }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; interface IWyvernX { function balanceOf(address account) external view returns (uint256); function getBalance() external; function mintLPTokens() external; function burnLPTokens() external; }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import "../libs/enum.sol"; import "../libs/constant.sol"; abstract contract DifficultyLevel { uint256 private immutable wyvernBirthTimestamp; uint256 private currentDay; uint256 private latestInfluenceRate; uint256 private latestHunterCost; /** @dev Lootable Wyvern starts at 150 ether, decreases to 10 ether. Stops when WyvernX has 41% of TitanX Staking Share Pool. */ uint256 private currentLootableWyvern; uint256 private latestHunterStrengthBonus; uint256 private currentEHBonus; /** @dev Tracks successful WarChestLoot for cycle days 8, 28, 90, 369, 888. Used in end stake for influence tracking. */ WarChestLootTriggered private isGlobalWarChestLootTriggered; /** @dev Maps cycle days to loot amounts. */ mapping(uint256 => uint256) private cycleLoot; /** @dev Maps cycle days to loot indices, incremented on successful WarChestLoot. */ mapping(uint256 => uint256) private cycleLootIndex; /** @dev Stores loot info (day and loot per influence) for each cycle day. */ mapping(uint256 => mapping(uint256 => CycleLootPerInfluence)) private cycleLootPerInfluence; /** @dev Tracks user's last claimed influence index for cycle and WarChestLoot. */ mapping(address => mapping(uint256 => UserCycleClaimIndex)) private addressCycleToLastLootClaimIndex; /** @dev Maps cycle days to next WarChestLoot days. */ mapping(uint256 => uint256) nextCycleLootDay; struct CycleLootPerInfluence { uint256 day; uint256 lootPerInfluence; } struct UserCycleClaimIndex { uint256 cycleIndex; uint256 influenceIndex; } event DifficultyLevelIncreasedStats( uint256 indexed day, uint256 indexed hunterCost, uint256 indexed influenceRate, uint256 lootableWyvern, uint256 mintPowerBonus, uint256 EHBonus ); /** @dev Updates daily variables for all external/public functions (excluding view). */ modifier increaseDifficultyLevel() { _increaseDifficultyLevel(); _; } constructor() { wyvernBirthTimestamp = block.timestamp; currentDay = 1; latestHunterCost = STARTING_MAX_HUNTER_COST; currentLootableWyvern = STARTING_MAX_DAILY_LOOTABLE_WYVERN; latestInfluenceRate = STARTING_INFLUENCE_RATE; latestHunterStrengthBonus = STARTING_HUNTER_STRENGTH_BONUS; currentEHBonus = STARTING_EH_BONUS; nextCycleLootDay[DAY8] = DAY8; nextCycleLootDay[DAY28] = DAY28; nextCycleLootDay[DAY90] = DAY90; nextCycleLootDay[DAY369] = DAY369; nextCycleLootDay[DAY888] = DAY888; } /** @dev Calculates and updates daily variables, resets triggers. */ function _increaseDifficultyLevel() private { uint256 currentDay_ = currentDay; uint256 currentBlockDay = ((block.timestamp - wyvernBirthTimestamp) / 1 days) + 1; if (currentBlockDay > currentDay_) { uint256 newHunterCost = latestHunterCost; uint256 newInfluenceRate = latestInfluenceRate; uint256 newLootableWyvern = currentLootableWyvern; uint256 newHunterStrengthBonus = latestHunterStrengthBonus; uint256 newEHBonus = currentEHBonus; uint256 dayDifference = currentBlockDay - currentDay_; for (uint256 i; i < dayDifference; i++) { newHunterCost = (newHunterCost * DAILY_HUNTER_COST_INCREASE) / PERCENT_BPS; // Freeze influence rate reduction for the first 281 days if (currentDay_ >= MINTING_FREEZE_PERIOD) { newInfluenceRate = (newInfluenceRate * DAILY_SHARE_RATE_INCREASE_STEP) / PERCENT_BPS; } newLootableWyvern = (newLootableWyvern * DAILY_LOOTABLE_WYVERN_REDUCTION) / PERCENT_BPS; newHunterStrengthBonus = (newHunterStrengthBonus * DAILY_MINTPOWER_INCREASE_BONUS_REDUCTION) / PERCENT_BPS; if (newHunterCost > CAPPED_MAX_HUNTER_COST) { newHunterCost = CAPPED_MAX_HUNTER_COST; } if (newInfluenceRate > CAPPED_MAX_RATE) newInfluenceRate = CAPPED_MAX_RATE; if (newLootableWyvern < CAPPED_MIN_DAILY_LOOTABLE_WYVERN) { newLootableWyvern = CAPPED_MIN_DAILY_LOOTABLE_WYVERN; } if (newHunterStrengthBonus < MIN_HUNTER_STRENGTH_BONUS) { newHunterStrengthBonus = MIN_HUNTER_STRENGTH_BONUS; } if (currentBlockDay <= MAX_BONUS_DAY) { newEHBonus -= EH_BONUS_FIXED_REDUCTION_PER_DAY; } else { newEHBonus = EH_BONUS_END; } emit DifficultyLevelIncreasedStats( ++currentDay_, newHunterCost, newInfluenceRate, newLootableWyvern, newHunterStrengthBonus, newEHBonus ); } latestHunterCost = newHunterCost; latestInfluenceRate = newInfluenceRate; currentLootableWyvern = newLootableWyvern; latestHunterStrengthBonus = newHunterStrengthBonus; currentEHBonus = newEHBonus; currentDay = currentBlockDay; isGlobalWarChestLootTriggered = WarChestLootTriggered.NO; } } /** @dev Initializes first influence from last claim index + 1. */ function _initFirstSharesCycleIndex(address user, uint256 isFirstInfluece) internal { if (isFirstInfluece == 1) { if (cycleLootIndex[DAY8] != 0) { addressCycleToLastLootClaimIndex[user][DAY8].cycleIndex = cycleLootIndex[DAY8] + 1; addressCycleToLastLootClaimIndex[user][DAY28].cycleIndex = cycleLootIndex[DAY28] + 1; addressCycleToLastLootClaimIndex[user][DAY90].cycleIndex = cycleLootIndex[DAY90] + 1; addressCycleToLastLootClaimIndex[user][DAY369].cycleIndex = cycleLootIndex[DAY369] + 1; addressCycleToLastLootClaimIndex[user][DAY888].cycleIndex = cycleLootIndex[DAY888] + 1; } } } /** @dev Calculates loot per influence for specified cycle. */ function _calcCycleLootPerInfluence( uint256 cycleNo, uint256 loot, uint256 protocolTotalInfluence ) internal returns (uint256 index) { cycleLoot[cycleNo] = 0; index = ++cycleLootIndex[cycleNo]; cycleLootPerInfluence[cycleNo][index].lootPerInfluence = (loot * SCALING_FACTOR_1e18) / protocolTotalInfluence; cycleLootPerInfluence[cycleNo][index].day = getCurrentDay(); } /** @dev Updates stats after WarChestLoot is claimed. */ function _updateUserClaimIndexes( address user, uint256 cycleNo, uint256 userClaimCycleIndex, uint256 userClaimInfluenceIndex ) internal { if (userClaimCycleIndex != addressCycleToLastLootClaimIndex[user][cycleNo].cycleIndex) addressCycleToLastLootClaimIndex[user][cycleNo].cycleIndex = userClaimCycleIndex; if (userClaimInfluenceIndex != addressCycleToLastLootClaimIndex[user][cycleNo].influenceIndex) addressCycleToLastLootClaimIndex[user][cycleNo].influenceIndex = userClaimInfluenceIndex; } /** @dev Marks loot as triggered for cycle days. */ function _setGlobalWarChestLootTriggered() internal { isGlobalWarChestLootTriggered = WarChestLootTriggered.YES; } /** @dev Adds reward to specified cycle's war chest. */ function _setCycleWarChest(uint256 cycleNo, uint256 reward) internal { cycleLoot[cycleNo] += reward; } /** @dev Updates next WarChestLoot day for specified cycle. */ function _setNextCycleWarChestDay(uint256 cycleNo) internal { uint256 lootDay = nextCycleLootDay[cycleNo]; uint256 currentDay_ = currentDay; if (currentDay_ >= lootDay) { nextCycleLootDay[cycleNo] += cycleNo * (((currentDay_ - lootDay) / cycleNo) + 1); } } /** Views */ /** @notice Returns current block timestamp. */ function getCurrentBlockTimeStamp() public view returns (uint256) { return block.timestamp; } /** @notice Returns current day. */ function getCurrentDay() public view returns (uint256) { return currentDay; } /** @notice Returns latest Hunter Cost. */ function getLatestHunterCost() public view returns (uint256) { return latestHunterCost; } /** @notice Returns latest Influence Rate. */ function getLatestInfluenceRate() public view returns (uint256) { return latestInfluenceRate; } /** @notice Returns current Lootable Wyvern. */ function getCurrentLootableWyvern() public view returns (uint256) { return currentLootableWyvern; } /** @notice Returns latest Hunter Strength Bonus. */ function getLatestHunterStrengthBonus() public view returns (uint256) { return latestHunterStrengthBonus; } /** @notice Returns current Early Hunter Bonus. */ function getCurrentEarlyHunterBonus() public view returns (uint256) { return currentEHBonus; } /** @notice Returns current cycle loot index for specified cycle day. */ function getCurrentCycleLootIndex(uint256 cycleNo) public view returns (uint256) { return cycleLootIndex[cycleNo]; } /** @notice Checks if war chest has been triggered. */ function getGlobalWarChestLootTriggered() public view returns (WarChestLootTriggered) { return isGlobalWarChestLootTriggered; } /** @notice Returns war chest reward for specified cycle day. */ function getCycleLootWarChest(uint256 cycleNo) public view returns (uint256) { return cycleLoot[cycleNo]; } /** @notice Returns loot per influence and day for specified cycle day and index. */ function getLootPerInfluence(uint256 cycleNo, uint256 index) public view returns (uint256, uint256) { return ( cycleLootPerInfluence[cycleNo][index].lootPerInfluence, cycleLootPerInfluence[cycleNo][index].day ); } /** @notice Returns user's last claimed influence indexes for specified cycle day. */ function getUserLastClaimIndex( address user, uint256 cycleNo ) public view returns (uint256 cycleIndex, uint256 influenceIndex) { return ( addressCycleToLastLootClaimIndex[user][cycleNo].cycleIndex, addressCycleToLastLootClaimIndex[user][cycleNo].influenceIndex ); } /** @notice Returns day when WyvernX was born. */ function getWyvernBirthTimestamp() public view returns (uint256) { return wyvernBirthTimestamp; } /** @notice Returns next Cycle Loot Day. */ function getNextCycleLootDay(uint256 cycleNo) public view returns (uint256) { return nextCycleLootDay[cycleNo]; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import "@openzeppelin/contracts/utils/Context.sol"; error IsNotOnwer(); abstract contract Guardian is Context { address private s_owner; /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { s_owner = _msgSender(); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { if (s_owner != _msgSender()) revert IsNotOnwer(); } /** * @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 onlyOwner { _setOwner(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 onlyOwner { _setOwner(newOwner); } function _setOwner(address newOwner) private { s_owner = newOwner; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import "../libs/utilFunctions.sol"; import "../libs/enum.sol"; abstract contract HuntersGuild { /** @dev track guild wyvernRank */ uint256 private globalWRank; /** @dev track total amount of claimed Hunters */ uint256 private totalHuntersClaimed; /** @dev track total WyvernX looted by Hunters */ uint256 private totalLootedWyvern; /** @dev track total WyvernX being looted currently from Hunters */ uint256 private totalWyvernBeingLooted; /** @dev track guild strength */ uint256 private globalGuildStrength; /** @dev track guild's depositId */ uint256 private currentDepositId; /** @dev track guild's influence */ uint256 private totalInfluence; /** @dev track guild's expired influence */ uint256 private totalExpiredInfluence; /** @dev track guild's Wyvern in war chest */ uint256 private totalWyvernInWarChests; /** @dev track guild's withdrawal penalties */ uint256 private totalWithdrawalPenalties; /** @dev track guild's withdrawn deposits */ uint256 private totalWithdrawnDeposits; /** @dev track address => hunterId */ mapping(address => uint256) private addressHId; /** @dev track address, hunterId => WyvernRank */ mapping(address => mapping(uint256 => WyvernRank)) private addressHIdToWyvernRank; /** @dev track guild wRank => Hunter */ mapping(uint256 => Hunter) private wRankToHunter; /** @dev track address => depositId */ mapping(address => uint256) private addressDepositId; /** @dev track address, depositId => global depositId */ mapping(address => mapping(uint256 => uint256)) private addressDepositIdToGlobalDepositId; /** @dev track global deposit Id => WarChestDeposit */ mapping(uint256 => WarChestDeposit) private globalDepositIdToWarChestDeposit; /** @dev track address => tracks the latest index of influence share for each user */ mapping(address => uint256) private userInfluenceIndex; /** @dev track user total current influence by day */ mapping(address => mapping(uint256 => UserInfluence)) private addressIdToCurrentInfluence; struct Hunter { uint256 strength; uint16 huntDays; uint256 lootableWyvern; uint48 huntStart; uint48 huntEnd; uint256 hunterStrengthBonus; uint256 EHBonus; uint256 lootedWyvern; uint256 hunterCost; HunterStatus status; } struct UserHunter { uint256 hunterId; uint256 wRank; uint256 guildStrength; Hunter hunter; } struct WyvernRank { uint256 wRank; uint256 guildStrength; } struct WarChestDeposit { uint256 wyvernAmount; uint256 influence; uint16 lockPeriod; uint48 depositTimestamp; uint48 unlockTimestamp; DepositStatus status; } struct UserWarChest { uint256 depositId; uint256 currentDepositId; WarChestDeposit warChestDeposit; } struct UserInfluence { uint256 day; uint256 currentInfluence; } event HunterStarted( address indexed user, uint256 indexed wRank, uint256 indexed guildStrength, Hunter hunter ); event HunterClaimed( address indexed user, uint256 indexed wRank, uint256 wyvernLooted ); event WarChestDeposited( address indexed user, uint256 indexed currentDepositId, uint256 lockPeriod, WarChestDeposit indexed warChestDeposit ); event WarChestWithdrawn( address indexed user, uint256 indexed currentDepositId, uint256 wyvernAmount, uint256 indexed penalty, uint256 penaltyAmount ); error InvalidHuntLength(); error InvalidHunterStrength(); error NoSuchHunterExists(); error HunterAlreadyClaimed(); error HuntNotFinished(); error InvalidLockPeriod(); error YouHaveNoInfluence(); error NoDeposits(); error DepositAlreadyWithdrawn(); error MaxDepositsReached(); /** @dev hire a new hunter * @param user user address * @param strength strength of hunter * @param huntDays length of hunt * @param lootableWyvern lootable WyvernX * @param hunterStrengthBonus hunter strength bonus * @param EHBonus Early Hunter Bonus * @param guildStrength guild Strength * @param currentWRank current global wRank * @param hunterCost cost to hire a hunter */ function _hireHunter( address user, uint256 strength, uint256 huntDays, uint256 lootableWyvern, uint256 hunterStrengthBonus, uint256 EHBonus, uint256 guildStrength, uint256 currentWRank, uint256 hunterCost ) internal returns (uint256 lootable) { if (huntDays == 0 || huntDays > MAX_HUNT_LENGTH) revert InvalidHuntLength(); if (strength == 0 || strength > MAX_HUNTER_STRENGTH_CAP) revert InvalidHunterStrength(); lootable = calculateHunterReward(strength, huntDays, lootableWyvern, EHBonus); Hunter memory hunter = Hunter({ strength: strength, huntDays: uint16(huntDays), lootableWyvern: lootable, hunterStrengthBonus: hunterStrengthBonus, EHBonus: EHBonus, huntStart: uint48(block.timestamp), huntEnd: uint48(block.timestamp + (huntDays * SECONDS_IN_DAY)), lootedWyvern: 0, hunterCost: hunterCost, status: HunterStatus.ACTIVE }); uint256 id = ++addressHId[user]; addressHIdToWyvernRank[user][id].wRank = currentWRank; addressHIdToWyvernRank[user][id].guildStrength = guildStrength; wRankToHunter[currentWRank] = hunter; emit HunterStarted(user, currentWRank, guildStrength, hunter); } /** @dev hire a squad of hunters (up to max 100 hunters with same hunt duration) * @param user user address * @param strength strength of hunter * @param huntDays length of hunt * @param lootableWyvern lootable WyvernX * @param hunterStrengthBonus hunter strength bonus * @param EHBonus Early Hunter Bonus * @param squadSize count of hunters * @param hunterCost cost to hire a hunter */ function _hireHunterSquad( address user, uint256 strength, uint256 huntDays, uint256 lootableWyvern, uint256 hunterStrengthBonus, uint256 EHBonus, uint256 squadSize, uint256 hunterCost ) internal { uint256 guildStrength = globalGuildStrength; uint256 currentWRank = globalWRank; uint256 totalLooting = totalWyvernBeingLooted; for (uint256 i = 0; i < squadSize; i++) { guildStrength += strength; totalLooting += _hireHunter( user, strength, huntDays, lootableWyvern, hunterStrengthBonus, EHBonus, guildStrength, ++currentWRank, hunterCost ); } _updateHunterStats(currentWRank, guildStrength, totalLooting); } /** @dev calculate loot for hunter claim * @param user user address * @param id hunter id * @param action claim hunter * @return loot calculated final Wyvern loot */ function _claimHunter( address user, uint256 id, HunterAction action ) internal returns (uint256 loot) { uint256 wRank = addressHIdToWyvernRank[user][id].wRank; uint256 guildStrength = addressHIdToWyvernRank[user][id].guildStrength; if (wRank == 0) revert NoSuchHunterExists(); Hunter memory hunter = wRankToHunter[wRank]; if (hunter.status == HunterStatus.CLAIMED) revert HunterAlreadyClaimed(); if (hunter.huntEnd > block.timestamp && action == HunterAction.CLAIM) revert HuntNotFinished(); totalWyvernBeingLooted -= hunter.lootableWyvern; totalLootedWyvern += hunter.lootableWyvern; loot = _calculateClaimLoot(user, wRank, guildStrength, hunter, action); } /** @dev calculate loot up to 100 claims * @param user user address * @return loot total loot from batch hunter claim */ function _batchClaimHunters(address user) internal returns (uint256 loot) { uint256 maxId = addressHId[user]; uint256 claimCount; uint256 wRank; uint256 wyvernLooting; Hunter memory mint; for (uint256 i = 1; i <= maxId; i++) { wRank = addressHIdToWyvernRank[user][i].wRank; mint = wRankToHunter[wRank]; if (mint.status == HunterStatus.ACTIVE && block.timestamp >= mint.huntEnd) { loot += _calculateClaimLoot( user, wRank, addressHIdToWyvernRank[user][i].guildStrength, mint, HunterAction.CLAIM ); wyvernLooting += mint.lootableWyvern; ++claimCount; } if (claimCount == 100) break; } totalWyvernBeingLooted -= wyvernLooting; totalLootedWyvern += wyvernLooting; } /** @dev create a new war chest deposit * @param user user address * @param amount WyvernX amount * @param lockPeriod deposit lock duration * @param influenceRate current influence rate * @param day current contract day * @param isWarChestTriggered has global payout triggered * @return startingInfluence protocol's first influence */ function _depositToWarChest( address user, uint256 amount, uint256 lockPeriod, uint256 influenceRate, uint256 day, WarChestLootTriggered isWarChestTriggered ) internal returns (uint256 startingInfluence) { uint256 depositId = ++addressDepositId[user]; if (depositId > MAX_DEPOSITS_PER_WALLET) revert MaxDepositsReached(); if (lockPeriod < MIN_LOCK_PERIOD || lockPeriod > MAX_LOCK_PERIOD) revert InvalidLockPeriod(); uint256 influence = calculateInfluence(amount, lockPeriod, influenceRate); if (influence / SCALING_FACTOR_1e18 < 1) revert YouHaveNoInfluence(); uint256 currentDepositId_ = ++currentDepositId; uint256 unlockTimestamp; unlockTimestamp = block.timestamp + (lockPeriod * SECONDS_IN_DAY); WarChestDeposit memory warChestDeposit = WarChestDeposit({ wyvernAmount: amount, influence: influence, lockPeriod: uint16(lockPeriod), depositTimestamp: uint48(block.timestamp), unlockTimestamp: uint48(unlockTimestamp), status: DepositStatus.ACTIVE }); addressDepositIdToGlobalDepositId[user][depositId] = currentDepositId_; globalDepositIdToWarChestDeposit[currentDepositId_] = warChestDeposit; startingInfluence = _updateInfluenceStats( user, influence, amount, day, isWarChestTriggered, DepositAction.START ); emit WarChestDeposited(user, currentDepositId_, lockPeriod, warChestDeposit); } /** @dev withdraws warChest deposit * @param user user address * @param depositId depositId * @param day current protocol day * @param action deposit action * @param isWarChestTriggered was WarChest Triggered * @return wyvern withdrawal amount */ function _withdrawWarChestDeposit( address user, uint256 depositId, uint256 day, DepositAction action, WarChestLootTriggered isWarChestTriggered ) internal returns (uint256 wyvern) { uint256 globalDepositId = addressDepositIdToGlobalDepositId[user][depositId]; if (globalDepositId == 0) revert NoDeposits(); WarChestDeposit memory warChestDeposit = globalDepositIdToWarChestDeposit[globalDepositId]; if (warChestDeposit.status == DepositStatus.ENDED) revert DepositAlreadyWithdrawn(); uint256 influence = warChestDeposit.influence; _updateInfluenceStats(user, influence, warChestDeposit.wyvernAmount, day, isWarChestTriggered, action); if (action == DepositAction.END) { ++totalWithdrawnDeposits; globalDepositIdToWarChestDeposit[globalDepositId].status = DepositStatus.ENDED; } wyvern = _calcWithdrawalAmount(user, globalDepositId, warChestDeposit); } /** @dev update stats related to Hunter * @param currentWRank current wRank * @param guildStrength current global guild Strength * @param totalLooting current total Wyvern Being Looted */ function _updateHunterStats(uint256 currentWRank, uint256 guildStrength, uint256 totalLooting) internal { globalWRank = currentWRank; globalGuildStrength = guildStrength; totalWyvernBeingLooted = totalLooting; } /** @dev updates influence stats * @param user user address * @param influence influence * @param amount WyvernX amount * @param day current contract day * @param isWarChestTriggered has WarChest been triggered * @param action start or withdraw deposit * @return startingInfluence startingInfluence protocol's first influence */ function _updateInfluenceStats( address user, uint256 influence, uint256 amount, uint256 day, WarChestLootTriggered isWarChestTriggered, DepositAction action ) private returns (uint256 startingInfluence) { uint256 index = userInfluenceIndex[user]; uint256 previousShares = addressIdToCurrentInfluence[user][index].currentInfluence; if (action == DepositAction.START) { if (index == 0) startingInfluence = 1; addressIdToCurrentInfluence[user][++index].currentInfluence = previousShares + influence; totalInfluence += influence; totalWyvernInWarChests += amount; } else { addressIdToCurrentInfluence[user][++index].currentInfluence = previousShares - influence; totalExpiredInfluence += influence; totalWyvernInWarChests -= amount; } addressIdToCurrentInfluence[user][index].day = isWarChestTriggered == WarChestLootTriggered.NO ? day : day + 1; userInfluenceIndex[user] = index; } /** @dev calculate final loot * @param user user address * @param wRank hunter's wRank * @param guildStrength guild Strength * @param hunter hunter stats * @param action claim hunter * @return loot final loot with all bonuses */ function _calculateClaimLoot( address user, uint256 wRank, uint256 guildStrength, Hunter memory hunter, HunterAction action ) private returns (uint256 loot) { if (action == HunterAction.CLAIM) wRankToHunter[wRank].status = HunterStatus.CLAIMED; uint256 bonus; if (action == HunterAction.CLAIM) { bonus = calculateGuildStrengthBonus( hunter.hunterStrengthBonus, hunter.strength, guildStrength, globalGuildStrength ); } loot = uint256(hunter.lootableWyvern) + (bonus / SCALING_FACTOR_1e7); if (action == HunterAction.CLAIM) ++totalHuntersClaimed; if (action == HunterAction.CLAIM) wRankToHunter[wRank].lootedWyvern = loot; emit HunterClaimed(user, wRank, loot); } /** @dev calculate amount of Wyvern to withdraw * @param user user address * @param globalDepositId global depositId * @param warChestDeposit warChest Deposit * @return toWithdraw amount to withdraw after penalties */ function _calcWithdrawalAmount( address user, uint256 globalDepositId, WarChestDeposit memory warChestDeposit ) internal returns (uint256 toWithdraw) { uint256 wyvernAmount = warChestDeposit.wyvernAmount; uint256 penalty = calcWithdrawalPenalty( warChestDeposit.depositTimestamp, warChestDeposit.unlockTimestamp, block.timestamp ); uint256 penaltyAmount; penaltyAmount = (wyvernAmount * penalty) / 100; toWithdraw = wyvernAmount - penaltyAmount; totalWithdrawalPenalties += penaltyAmount; emit WarChestWithdrawn(user, globalDepositId, toWithdraw, penalty, penaltyAmount); } // === Global State Accessors === /** @notice Return current global wyvernRank * @return globalWRank global wRank */ function getGlobalWRank() public view returns (uint256) { return globalWRank; } /** @notice Return current global Guild Strength * @return globalGuildStrength global Guild Strength */ function getGlobalGuildStrength() public view returns (uint256) { return globalGuildStrength; } /** @notice Return total Hunters Claimed * @return totalMintClaimed total Hunters Claimed */ function getTotalHuntersClaimed() public view returns (uint256) { return totalHuntersClaimed; } /** @notice Return total looted Wyvern * @return totalLootedWyvern total Looted Wyvern */ function getTotalLootedWyvern() public view returns (uint256) { return totalLootedWyvern; } /** @notice Return total Wyvern Being Looted * @return totalWyvernBeingLooted total Wyvern Being Looted */ function getTotalWyvernBeingLooted() public view returns (uint256) { return totalWyvernBeingLooted; } /** @notice get total Influence * @return totalInfluence total Influence */ function getTotalInfluence() public view returns (uint256) { return totalInfluence; } /** @notice get total Expired Influence * @return totalExpiredInfluence total Expired Influence */ function getTotalExpiredInfluence() public view returns (uint256) { return totalExpiredInfluence; } /** @notice get guilds total Influence * @return protocolTotalInfluence guilds total Influence */ function getProtocolTotalInfluence() public view returns (uint256) { return totalInfluence - totalExpiredInfluence; } /** @notice get total Wyvern deposited in WarChests * @return totalWyvernInWarChests total Wyvern In WarChests */ function getTotalWyvernDeposited() public view returns (uint256) { return totalWyvernInWarChests; } /** @notice get guilds depositId * @return currentDepositId guilds current depositId */ function getCurrentDepositId() public view returns (uint256) { return currentDepositId; } /** @notice get total Withdrawal Penalties * @return totalWithdrawalPenalties total Withdrawal Penalties */ function getTotalWithdrawalPenalties() public view returns (uint256) { return totalWithdrawalPenalties; } /** @notice get total active deposits * @return totalActiveDeposits Total Active Deposits */ function getTotalActiveDeposits() public view returns (uint256) { return currentDepositId - getTotalWithdrawnDeposits(); } /** @notice get guild's total Withdrawn Deposits * @return totalWithdrawnDeposits total Withdrawn Deposits */ function getTotalWithdrawnDeposits() public view returns (uint256) { return totalWithdrawnDeposits; } // === User-Specific Functions === /** @notice Returns the latest hunter Id of an address * @return hunterId latest hunter id */ function getUserLatestHunterId(address user) public view returns (uint256) { return addressHId[user]; } /** @notice Returns hunter stats of an address * @param user address * @param id hunter id * @return hunter user hunter stats */ function getHunter( address user, uint256 id ) public view returns (Hunter memory hunter) { return wRankToHunter[addressHIdToWyvernRank[user][id].wRank]; } /** @notice Return all userHunters of an address * @return userHunter all userHunters of an address */ function getUserHunters(address user) public view returns (UserHunter[] memory userHunter) { uint256 count = addressHId[user]; userHunter = new UserHunter[](count); for (uint256 i = 1; i <= count; i++) { userHunter[i - 1] = UserHunter({ hunterId: i, wRank: addressHIdToWyvernRank[user][i].wRank, guildStrength: addressHIdToWyvernRank[user][i].guildStrength, hunter: getHunter(user, i) }); } } /** @notice get deposit stats * @return warChestDeposit deposit stats */ function getUserWarChestDeposit(address user, uint256 id) public view returns (WarChestDeposit memory) { return globalDepositIdToWarChestDeposit[addressDepositIdToGlobalDepositId[user][id]]; } /** @notice get all warChest deposits of an address * @return userWarChest all warChest deposits of an address */ function getUserWarChests(address user) public view returns (UserWarChest[] memory) { uint256 count = addressDepositId[user]; UserWarChest[] memory userWarChest = new UserWarChest[](count); for (uint256 i = 1; i <= count; i++) { userWarChest[i - 1] = UserWarChest({ depositId: i, currentDepositId: addressDepositIdToGlobalDepositId[user][i], warChestDeposit: getUserWarChestDeposit(user, i) }); } return userWarChest; } // === User Influence Functions === /** @notice get user latest Influence Index * @return userInfluenceIndex latest user Influence Index */ function getUserCurrentInfluenceIndex(address user) public view returns (uint256) { return userInfluenceIndex[user]; } /** @notice get user current influence * @return currentInfluence current Influence */ function getUserCurrentInfluence(address user) public view returns (uint256) { return addressIdToCurrentInfluence[user][getUserCurrentInfluenceIndex(user)].currentInfluence; } /** @notice get user influence from influenceIndex snapshot * @return influence active influence at influenceIndex */ function getUserInfluenceAtIndex( address user, uint256 influenceIndex ) internal view returns (uint256) { return addressIdToCurrentInfluence[user][influenceIndex].currentInfluence; } /** @notice get user influenceDay from influenceIndex * @return influenceDay protocol's day stored at influenceIndex */ function getUserInfluenceDayFromInfluenceIndex( address user, uint256 influenceIndex ) internal view returns (uint256) { return addressIdToCurrentInfluence[user][influenceIndex].day; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.20; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../interfaces/ITITANX.sol"; import "../contracts/WyvernVault.sol"; import "../contracts/WyvernX.sol"; import "./constant.sol"; /** * @title WyvernVault's staking module * @notice Operates as part of WyvernVault, not standalone */ contract TitanStaker is Ownable { using SafeERC20 for IERC20; using SafeERC20 for ITitanX; uint256 public activeTitanXStakes; error StakeNotCompleted(); constructor() Ownable(msg.sender) {} // NATIVE TOKEN HANDLING /** * @notice Processes incoming native token deposits * Reverts if the sender is not TitanX contract. */ receive() external payable { require(msg.sender == TITANX_ADDRESS, "Sender is not TitanX"); } /** * @notice Handles unexpected contract interactions * @dev Blocks unintended native token transfers */ fallback() external payable { revert("Fallback triggered"); } /** * @notice Locks available TitanX in max-length stake */ function stake() external onlyOwner { ITitanX titanX = ITitanX(TITANX_ADDRESS); uint256 amountToStake = titanX.balanceOf(address(this)); titanX.startStake(amountToStake, TITANX_MAX_STAKE_LENGTH); activeTitanXStakes += 1; } /** * @notice Collects ETH rewards from TitanX staking * @return pendingReward ETH amount to be claimed */ function claim() external onlyOwner returns (uint256 pendingReward) { ITitanX titanX = ITitanX(TITANX_ADDRESS); pendingReward = titanX.getUserETHClaimableTotal(address(this)); if (pendingReward > 0) { titanX.claimUserAvailableETHPayouts(); Address.sendValue(payable(owner()), pendingReward); } } /** * @dev Unlocks completed stake and returns tokens to vault * @param stakeId Target stake identifier * @notice Requires completed lock period */ function withdrawCompletedStake(uint256 stakeId) external { ITitanX titanX = ITitanX(TITANX_ADDRESS); require(stakeId > 0 && stakeId <= activeTitanXStakes, "Invalid stake ID"); UserStakeInfo memory stakeInfo = titanX.getUserStakeInfo(address(this), stakeId); if (block.timestamp >= stakeInfo.maturityTs) { uint256 balanceBefore = titanX.balanceOf(address(this)); titanX.endStake(stakeId); uint256 withdrawnAmount = titanX.balanceOf(address(this)) - balanceBefore; IERC20(TITANX_ADDRESS).safeTransfer(owner(), withdrawnAmount); WyvernVault(payable(owner())).stakeEnded(withdrawnAmount); } else { revert StakeNotCompleted(); } } /** * @dev Checks available ETH rewards * @return pendingReward ETH rewards ready to be claimed */ function totalPendingEthRewards() external view returns (uint256 pendingReward) { ITitanX titanX = ITitanX(TITANX_ADDRESS); pendingReward = titanX.getUserETHClaimableTotal(address(this)); } /** * @dev Finds completed stakes * @return isCompleted Status of completed stake * @return completedStakeId Id of completed stake */ function checkForCompletedStakes() external view returns (bool isCompleted, uint256 completedStakeId) { ITitanX titanX = ITitanX(TITANX_ADDRESS); UserStake[] memory activeStakes = titanX.getUserStakes(address(this)); for (uint256 i; i < activeStakes.length; i++) { if (block.timestamp > activeStakes[i].stakeInfo.maturityTs) { return (true, activeStakes[i].sId); } } return (false, 0); } /** * @dev Returns TitanX to vault * @notice Recovery for locked tokens */ function recoverTitanX() external { IERC20 titanX = IERC20(TITANX_ADDRESS); titanX.safeTransfer(owner(), titanX.balanceOf(address(this))); WyvernVault(payable(owner())).updateVault(); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; /* Universal */ uint256 constant SECONDS_IN_DAY = 86400; uint256 constant SCALING_FACTOR_1e2 = 1e2; uint256 constant SCALING_FACTOR_1e3 = 1e3; uint256 constant SCALING_FACTOR_1e4 = 1e4; uint256 constant SCALING_FACTOR_1e6 = 1e6; uint256 constant SCALING_FACTOR_1e7 = 1e7; uint256 constant SCALING_FACTOR_1e11 = 1e11; uint256 constant SCALING_FACTOR_1e18 = 1e18; /* Uniswap */ uint24 constant FEE_TIER = 10000; int24 constant MIN_TICK = -887200; int24 constant MAX_TICK = 887200; /* Addresses */ address constant TITANX_ADDRESS = 0xF19308F923582A6f7c465e5CE7a9Dc1BEC6665B1; address constant WETH9_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address constant UNI_SWAP_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564; address constant UNI_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984; address constant UNI_NONFUNGIBLEPOSITIONMANAGER = 0xC36442b4a4522E871399CD717aBDD847Ab11FE88; /* WyvernX Const */ uint256 constant PERCENT_TO_CYCLE_WARCHESTS = 15_00; uint256 constant PERCENT_TO_WYVERN_VAULT = 73_00; uint256 constant PERCENT_TO_GENESIS = 7_00; uint256 constant PERCENT_TO_LIQUIDITY_BONDING = 5_00; // 5% uint256 constant REWARD_FEE_PERCENT = 30000; uint256 constant REWARD_FEE_PERCENTAGE_BASE_WYVERNX = 1_000_000; address constant LIQUIDITY_BONDING_ADDR = 0x4105aD0e580Af6b300bA2b0D8c747a5A004A04F9; uint256 constant AUTO_ENABLE_MINT_CLAIMING_DAY = 290; uint256 constant DAILY_LOOTABLE_WYVERN_REDUCTION = 99_65; uint256 constant STARTING_MAX_DAILY_LOOTABLE_WYVERN = 150 ether; uint256 constant CAPPED_MIN_DAILY_LOOTABLE_WYVERN = 10 ether; uint256 constant MINIMUM_SHAREPOOL_FOR_MINTING_PHASE = 41 * SCALING_FACTOR_1e4; // 41% uint256 constant MINIMUM_SHAREPOOL_FOR_STAKING_PHASE = 51 * SCALING_FACTOR_1e4; // 51% uint256 constant STARTING_INFLUENCE_RATE = 800 ether; uint256 constant DAILY_SHARE_RATE_INCREASE_STEP = 100_07; uint256 constant CAPPED_MAX_RATE = 2_800 ether; //WarChest Const uint256 constant DAY8 = 8; uint256 constant DAY28 = 28; uint256 constant DAY90 = 90; uint256 constant DAY369 = 369; uint256 constant DAY888 = 888; uint256 constant CYCLE_8_PERCENT = 13_00; uint256 constant CYCLE_28_PERCENT = 20_00; uint256 constant CYCLE_90_PERCENT = 25_00; uint256 constant CYCLE_369_PERCENT = 30_00; uint256 constant CYCLE_888_PERCENT = 12_00; uint256 constant PERCENT_BPS = 100_00; //Hunters Claiming Const uint256 constant MAX_HUNTER_STRENGTH_CAP = 100; uint256 constant MAX_HUNT_LENGTH = 280; uint256 constant MINTING_FREEZE_PERIOD = 281; uint256 constant MAX_BATCH_HIRE_COUNT = 100; uint256 constant MAX_HUNTERS_PER_WALLET = 1000; uint256 constant MINT_DAILY_REDUCTION = 11; uint256 constant STARTING_MAX_HUNTER_COST = 2_800_000_000 ether; uint256 constant CAPPED_MAX_HUNTER_COST = 3_800_000_000 ether; uint256 constant DAILY_HUNTER_COST_INCREASE = 100_08; uint256 constant STARTING_HUNTER_STRENGTH_BONUS = 2 * SCALING_FACTOR_1e6; uint256 constant MIN_HUNTER_STRENGTH_BONUS = 2 * SCALING_FACTOR_1e2; uint256 constant DAILY_MINTPOWER_INCREASE_BONUS_REDUCTION = 99_65; uint256 constant STARTING_EH_BONUS = 10 * SCALING_FACTOR_1e6; uint256 constant EH_BONUS_FIXED_REDUCTION_PER_DAY = 28_571; uint256 constant EH_BONUS_END = 0; uint256 constant MAX_BONUS_DAY = 281; uint256 constant MAX_DEPOSITS_PER_WALLET = 1000; uint256 constant MIN_LOCK_PERIOD = 28; uint256 constant MAX_LOCK_PERIOD = 3500; uint256 constant WITHDRAW_GOODWILL_PERIOD = 20; uint256 constant LPB_MAX_DAYS = 2888; uint256 constant LPB_PER_PERCENT = 825; uint256 constant BPB_MAX_WYVERN = 200_000 * SCALING_FACTOR_1e18; // 200,000 uint256 constant BPB_PER_PERCENT = 2_500_000 * SCALING_FACTOR_1e18; /* WyvernVault Const */ uint256 constant VAULT_DISTRIBUTION = 7300; // 73% uint256 constant WYVERN_STAKING_DISTRIBUTION = 2200; // 22% uint256 constant REWARD_FEE = 300; // 3% uint256 constant TINC_BURN_DISTRIBUTION = 500; // 5% uint256 constant PERCENTAGE_BASE_VAULT = 10_000; uint256 constant STAKE_COOLDOWN_PERIOD = 10 days; /* TitanX Protocol Const */ /* Staking */ uint256 constant TITANX_MAX_STAKE_PER_WALLET = 1000; uint256 constant TITANX_MIN_STAKE_LENGTH = 28; uint256 constant TITANX_MAX_STAKE_LENGTH = 3500; /* Stake bonuses */ uint256 constant TITANX_LPB_MAX_DAYS = 2888; uint256 constant TITANX_LPB_PER_PERCENT = 825; uint256 constant TITANX_BPB_MAX_TITAN = 100 * 1e9 * SCALING_FACTOR_1e18; //100 billion uint256 constant TITANX_BPB_PER_PERCENT = 1_250_000_000_000 * SCALING_FACTOR_1e18;
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; enum WyvernManaPoolMinted { NO, YES } enum WyvernMintingPhaseFinished { NO, YES } enum ClaimingEnabled { NO, YES } enum HunterAction { CLAIM } enum HunterStatus { ACTIVE, CLAIMED } enum DepositAction { START, END } enum DepositStatus { ACTIVE, ENDED } enum WarChestLootTriggered { NO, YES } enum CycleLootClaim { INFLUENCE }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.20; // Uniswap import "@uniswap/v3-core/interfaces/IUniswapV3Pool.sol"; // OpenZeppelin import "@openzeppelin/contracts/utils/math/Math.sol"; /** * @notice Adapted Uniswap V3 OracleLibrary computation to be compliant with Solidity 0.8.x and later. * * Documentation for Auditors: * * Solidity Version: Updated the Solidity version pragma to ^0.8.0. This change ensures compatibility * with Solidity version 0.8.x. * * Safe Arithmetic Operations: Solidity 0.8.x automatically checks for arithmetic overflows/underflows. * Therefore, the code no longer needs to use SafeMath library (or similar) for basic arithmetic operations. * This change simplifies the code and reduces the potential for errors related to manual overflow/underflow checking. * * Overflow/Underflow: With the introduction of automatic overflow/underflow checks in Solidity 0.8.x, the code is inherently * safer and less prone to certain types of arithmetic errors. * * Removal of SafeMath Library: Since Solidity 0.8.x handles arithmetic operations safely, the use of SafeMath library * is omitted in this update. * * Git-style diff for the `consult` function: * * ```diff * function consult(address pool, uint32 secondsAgo) * internal * view * returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity) * { * require(secondsAgo != 0, 'BP'); * * uint32[] memory secondsAgos = new uint32[](2); * secondsAgos[0] = secondsAgo; * secondsAgos[1] = 0; * * (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = * IUniswapV3Pool(pool).observe(secondsAgos); * * int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; * uint160 secondsPerLiquidityCumulativesDelta = * secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0]; * * - arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo); * + int56 secondsAgoInt56 = int56(uint56(secondsAgo)); * + arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgoInt56); * // Always round to negative infinity * - if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) arithmeticMeanTick--; * + if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgoInt56 != 0)) arithmeticMeanTick--; * * - uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max; * + uint192 secondsAgoUint192 = uint192(secondsAgo); * + uint192 secondsAgoX160 = secondsAgoUint192 * type(uint160).max; * harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32)); * } * ``` */ /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool /// @param pool Address of the pool that we want to observe /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp function consult( address pool, uint32 secondsAgo ) internal view returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity) { require(secondsAgo != 0, "BP"); uint32[] memory secondsAgos = new uint32[](2); secondsAgos[0] = secondsAgo; secondsAgos[1] = 0; ( int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s ) = IUniswapV3Pool(pool).observe(secondsAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[ 1 ] - secondsPerLiquidityCumulativeX128s[0]; // Safe casting of secondsAgo to int56 for division int56 secondsAgoInt56 = int56(uint56(secondsAgo)); arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgoInt56); // Always round to negative infinity if ( tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgoInt56 != 0) ) arithmeticMeanTick--; // Safe casting of secondsAgo to uint192 for multiplication uint192 secondsAgoUint192 = uint192(secondsAgo); harmonicMeanLiquidity = uint128( (secondsAgoUint192 * uint192(type(uint160).max)) / (uint192(secondsPerLiquidityCumulativesDelta) << 32) ); } /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation /// @param pool Address of Uniswap V3 pool that we want to observe /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool function getOldestObservationSecondsAgo( address pool ) internal view returns (uint32 secondsAgo) { ( , , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); require(observationCardinality > 0, "NI"); (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool( pool ).observations((observationIndex + 1) % observationCardinality); // The next index might not be initialized if the cardinality is in the process of increasing // In this case the oldest observation is always in index 0 if (!initialized) { (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0); } secondsAgo = uint32(block.timestamp) - observationTimestamp; } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// a slightly modified version of the UniSwap library getQuoteAtTick to accept a sqrtRatioX96 as input parameter /// @param sqrtRatioX96 The sqrt ration /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteForSqrtRatioX96( uint160 sqrtRatioX96, uint256 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? Math.mulDiv(ratioX192, baseAmount, 1 << 192) : Math.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = Math.mulDiv( sqrtRatioX96, sqrtRatioX96, 1 << 64 ); quoteAmount = baseToken < quoteToken ? Math.mulDiv(ratioX128, baseAmount, 1 << 128) : Math.mulDiv(1 << 128, baseAmount, ratioX128); } } }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.20; /** * @notice Adapted Uniswap V3 pool address computation to be compliant with Solidity 0.8.x and later. * @dev Changes were made to address the stricter type conversion rules in newer Solidity versions. * Original Uniswap V3 code directly converted a uint256 to an address, which is disallowed in Solidity 0.8.x. * Adaptation Steps: * 1. The `pool` address is computed by first hashing pool parameters. * 2. The resulting `uint256` hash is then explicitly cast to `uint160` before casting to `address`. * This two-step conversion process is necessary due to the Solidity 0.8.x restriction. * Direct conversion from `uint256` to `address` is disallowed to prevent mistakes * that can occur due to the size mismatch between the types. * 3. Added a require statement to ensure `token0` is less than `token1`, maintaining * Uniswap's invariant and preventing pool address calculation errors. * @param factory The Uniswap V3 factory contract address. * @param key The PoolKey containing token addresses and fee tier. * @return pool The computed address of the Uniswap V3 pool. * @custom:modification Explicit type conversion from `uint256` to `uint160` then to `address`. * * function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { * require(key.token0 < key.token1); * pool = address( * uint160( // Explicit conversion to uint160 added for compatibility with Solidity 0.8.x * uint256( * keccak256( * abi.encodePacked( * hex'ff', * factory, * keccak256(abi.encode(key.token0, key.token1, key.fee)), * POOL_INIT_CODE_HASH * ) * ) * ) * ) * ); * } */ /// @dev This code is copied from Uniswap V3 which uses an older compiler version. /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress( address factory, PoolKey memory key ) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint160( // Convert uint256 to uint160 first uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256( abi.encode(key.token0, key.token1, key.fee) ), POOL_INIT_CODE_HASH ) ) ) ) ); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.20; /** * @notice Adapted Uniswap V3 TickMath library computation to be compliant with Solidity 0.8.x and later. * * Documentation for Auditors: * * Solidity Version: Updated the Solidity version pragma to ^0.8.0. This change ensures compatibility * with Solidity version 0.8.x. * * Safe Arithmetic Operations: Solidity 0.8.x automatically checks for arithmetic overflows/underflows. * Therefore, the code no longer needs to use the SafeMath library (or similar) for basic arithmetic operations. * This change simplifies the code and reduces the potential for errors related to manual overflow/underflow checking. * * Explicit Type Conversion: The explicit conversion of `MAX_TICK` from `int24` to `uint256` in the `require` statement * is safe and necessary for comparison with `absTick`, which is a `uint256`. This conversion is compliant with * Solidity 0.8.x's type system and does not introduce any arithmetic risk. * * Overflow/Underflow: With the introduction of automatic overflow/underflow checks in Solidity 0.8.x, the code is inherently * safer and less prone to certain types of arithmetic errors. * * Removal of SafeMath Library: Since Solidity 0.8.x handles arithmetic operations safely, the use of the SafeMath library * is omitted in this update. * * Git-style diff for the TickMath library: * * ```diff * - pragma solidity >=0.5.0 <0.8.0; * + pragma solidity ^0.8.0; * * function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { * uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); * - require(absTick <= uint256(MAX_TICK), 'T'); * + require(absTick <= uint256(int256(MAX_TICK)), 'T'); // Explicit type conversion for Solidity 0.8.x compatibility * // ... (rest of the function) * } * * function getTickAtSqrtRatio( * uint160 sqrtPriceX96 * ) internal pure returns (int24 tick) { * // [Code for calculating the tick based on sqrtPriceX96 remains unchanged] * * - tick = tickLow == tickHi * - ? tickLow * - : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 * - ? tickHi * - : tickLow; * + if (tickLow == tickHi) { * + tick = tickLow; * + } else { * + tick = (getSqrtRatioAtTick(tickHi) <= sqrtPriceX96) ? tickHi : tickLow; * + } * } * ``` * * Note: Other than the pragma version change and the explicit type conversion in the `require` statement, the original functions * within the TickMath library are compatible with Solidity 0.8.x without requiring any further modifications. This is due to * the fact that the logic within these functions already adheres to safe arithmetic practices and does not involve operations * that would be affected by the 0.8.x compiler's built-in checks. */ /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick( int24 tick ) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(int256(MAX_TICK)), "T"); // Explicit type conversion for Solidity 0.8.x compatibility uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160( (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1) ); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio( uint160 sqrtPriceX96 ) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require( sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R" ); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24( (log_sqrt10001 - 3402992956809132418596140100660247210) >> 128 ); int24 tickHi = int24( (log_sqrt10001 + 291339464771989622907027621153398088495) >> 128 ); // Adjusted logic for determining the tick if (tickLow == tickHi) { tick = tickLow; } else { tick = (getSqrtRatioAtTick(tickHi) <= sqrtPriceX96) ? tickHi : tickLow; } } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import "./constant.sol"; import "./enum.sol"; /** @notice get batch mint cost * @param mintPower mint power (1 - 100) * @param count number of mints * @return mintCost total mint cost */ function getBatchHunterCost( uint256 mintPower, uint256 count, uint256 mintCost ) pure returns (uint256) { return (mintCost * mintPower * count) / MAX_HUNTER_STRENGTH_CAP; } /** @notice the formula to calculate mint reward at create new mint * @param mintPower mint power 1 - 100 * @param numOfDays mint length 1 - 280 * @param mintableWyvern current contract day mintable Wyvern * @param EAABonus current contract day EAA Bonus * @return reward base Wyvern amount */ function calculateHunterReward( uint256 mintPower, uint256 numOfDays, uint256 mintableWyvern, uint256 EAABonus ) pure returns (uint256 reward) { uint256 baseReward = (mintableWyvern * mintPower * numOfDays); if (numOfDays != 1) baseReward -= (baseReward * MINT_DAILY_REDUCTION * (numOfDays - 1)) / PERCENT_BPS; reward = baseReward; if (EAABonus != 0) { //EAA Bonus has 1e6 scaling, so here divide by 1e6 reward += ((baseReward * EAABonus) / 100 / SCALING_FACTOR_1e6); } reward /= MAX_HUNTER_STRENGTH_CAP; } /** @notice the formula to calculate bonus reward * heavily influenced by the difference between current global mint power and user mint's global mint power * @param hunterStrengthBonus hunter Strength Bonus from hunter * @param strength hunter strength 1 - 100 snapshot from hunter * @param guildStrength guild Strength snapshot from hunter * @param globalGuildStrength current global Guild Strength * @return bonus bonus amount in Wyvern */ function calculateGuildStrengthBonus( uint256 hunterStrengthBonus, uint256 strength, uint256 guildStrength, uint256 globalGuildStrength ) pure returns (uint256 bonus) { if (globalGuildStrength <= guildStrength) return 0; bonus = (((hunterStrengthBonus * strength * (globalGuildStrength - guildStrength)) * SCALING_FACTOR_1e18) / MAX_HUNTER_STRENGTH_CAP); } error WithdrawalNotYetPossible(); /** @notice get max stake length * @return maxStakeLength max stake length */ function getMaxStakeLength() pure returns (uint256) { return MAX_LOCK_PERIOD; } /** @notice calculate shares and shares bonus * @param amount WyvernX amount * @param noOfDays stake length * @param shareRate current contract share rate * @return shares calculated shares in 18 decimals */ function calculateInfluence( uint256 amount, uint256 noOfDays, uint256 shareRate ) pure returns (uint256) { uint256 shares = amount; shares += (shares * calculateShareBonus(amount, noOfDays)) / SCALING_FACTOR_1e11; shares /= (shareRate / SCALING_FACTOR_1e18); return shares; } /** @notice calculate share bonus * @param amount Wyvern amount * @param noOfDays stake length * @return shareBonus calculated shares bonus in 11 decimals */ function calculateShareBonus(uint256 amount, uint256 noOfDays) pure returns (uint256 shareBonus) { uint256 cappedExtraDays = noOfDays <= LPB_MAX_DAYS ? noOfDays : LPB_MAX_DAYS; uint256 cappedStakedWyvern = amount <= BPB_MAX_WYVERN ? amount : BPB_MAX_WYVERN; shareBonus = ((cappedExtraDays * SCALING_FACTOR_1e11) / LPB_PER_PERCENT) + ((cappedStakedWyvern * SCALING_FACTOR_1e11) / BPB_PER_PERCENT); return shareBonus; } /** @notice calculate Withdrawal Penalty * @param depositTimestamp deposit Timestamp * @param unlockTimestamp unlock Timestamp * @param blockTimestamp current block timestamp * @return penalty penalty in percentage */ function calcWithdrawalPenalty( uint256 depositTimestamp, uint256 unlockTimestamp, uint256 blockTimestamp ) view returns (uint256) { if (blockTimestamp > unlockTimestamp) { uint256 timeLateSinceUnlock = blockTimestamp - unlockTimestamp; uint256 withdrawGoodwillInSec = WITHDRAW_GOODWILL_PERIOD * SECONDS_IN_DAY; if (timeLateSinceUnlock <= withdrawGoodwillInSec) return 0; return max((min((timeLateSinceUnlock - withdrawGoodwillInSec), 1) / SECONDS_IN_DAY) + 1, 99); } // Withdrawal not possible if 50% of the unlock time has passed if (block.timestamp < depositTimestamp + (unlockTimestamp - depositTimestamp) / 2) revert WithdrawalNotYetPossible(); //50% penalty for unlocking early return 50; } //a - input to check against b //b - minimum number function min(uint256 a, uint256 b) pure returns (uint256) { if (a > b) return a; return b; } //a - input to check against b //b - maximum number function max(uint256 a, uint256 b) pure returns (uint256) { if (a > b) return b; return a; } // @dev Returns the square root of `x`, rounded down. function sqrt(uint256 x) pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`. z := 181 // The "correct" value is 1, but this saves a multiplication later. // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. // Let `y = x / 2**r`. We check `y >= 2**(k + 8)` // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`. let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffffff, shr(r, x)))) z := shl(shr(1, r), z) // Goal was to get `z*z*y` within a small factor of `x`. More iterations could // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`. // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small. // That's not possible if `x < 256` but we can just verify those cases exhaustively. // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`. // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`. // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps. // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)` // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`, // with largest error when `s = 1` and when `s = 256` or `1/256`. // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`. // Then we can estimate `sqrt(y)` using // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`. // There is no overflow risk here since `y < 2**136` after the first branch above. z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181. // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // If `x+1` is a perfect square, the Babylonian method cycles between // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor. // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division z := sub(z, lt(div(x, z), z)) } }
{ "evmVersion": "paris", "libraries": {}, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "enabled": true, "runs": 200 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"CooldownPeriodActive","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidCaller","type":"error"},{"inputs":[],"name":"InvalidWyvernAddress","type":"error"},{"inputs":[],"name":"InvalidWyvernVaultAddress","type":"error"},{"inputs":[],"name":"MathOverflowedMulDiv","type":"error"},{"inputs":[],"name":"NoWethBalanceToBuyAndBurnWyvern","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"weth","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"wyvern","type":"uint256"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"BoughtAndBurned","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"wyvern","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"titan","type":"uint256"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"CollectedFees","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"wyvern","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"titan","type":"uint256"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"LiquidityAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"stateMutability":"nonpayable","type":"fallback"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"addLiquidity","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"buyAndBurnWyvernX","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"name":"calculateMinimumWyvernAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"calculateWethForNextBuyAndBurn","outputs":[{"internalType":"uint256","name":"nextBuySize","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"callerRewardFeeForCallingBuyAndBurnWyvern","outputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"capPerBuy","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collectFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"initialWyvernXLiquidityAmount","type":"uint256"}],"name":"createUniswapLiquidity","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"enableTitanStaking","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getBuyAndBurnBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentTitanPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"baseAmount","type":"uint256"}],"name":"getTitanQuoteForEth","outputs":[{"internalType":"uint256","name":"quote","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getWethBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"baseAmount","type":"uint256"}],"name":"getWyvernQuoteForTitan","outputs":[{"internalType":"uint256","name":"quote","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"interval","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastBuyTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidityBondingAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"secs","type":"uint256"}],"name":"setBuyAndBurnFrequency","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"setCapPerBuy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newAddress","type":"address"}],"name":"setLiquidityBondingAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"setSlippage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"mins","type":"uint32"}],"name":"setTitanPriceTwa","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"wyvernAddress_","type":"address"}],"name":"setWyvernContractAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"mins","type":"uint32"}],"name":"setWyvernPriceTwa","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"wyvernVaultAddress_","type":"address"}],"name":"setWyvernVaultContractAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"slippage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalTitanFeesCollected","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalWethForBuyAndBurn","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalWethUsedForBuyAndBurns","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalWyvernBurned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalWyvernFeesCollected","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"wyvernAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"wyvernTitanPoolAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"wyvernVaultAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
Contract Creation Code
60806040523480156200001157600080fd5b5033806200003957604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b6200004481620000a9565b506001600255669fdf42f6e48000600b5560056006819055610e10600d556012805468010000000f0000000f6001600160481b031990911617905580546001600160a01b031916734105ad0e580af6b300ba2b0d8c747a5a004a04f917905562000117565b600180546001600160a01b0319169055620000c481620000c7565b50565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6137d380620001276000396000f3fe6080604052600436106102345760003560e01c806382c791f01161012e578063e30c3978116100ab578063f1e741a81161006f578063f1e741a8146106b7578063f2419177146106d7578063f2fde38b146106ec578063f55e943e1461070c578063f58545ac1461072c576102bf565b8063e30c397814610624578063e8078d9414610642578063e9373eef14610657578063eb35d16014610677578063f0fa55a914610697576102bf565b8063a6fc9f66116100f2578063a6fc9f6614610599578063afb16a5c146105b9578063c8796572146105d9578063d770f068146105ee578063df79d7521461060e576102bf565b806382c791f01461050557806384ef03ba146105255780638c14a5d6146105455780638da5cb5b14610565578063947a36fb14610583576102bf565b806361093ad2116101bc5780636d84fb83116101805780636d84fb831461049b578063715018a6146104b15780637708926a146104c657806379ba5097146104db5780637b4ba9af146104f0576102bf565b806361093ad214610426578063636b32ea1461043c578063665f8efb1461045157806366ffd6c6146104665780636a70962e1461047b576102bf565b80633b20250c116102035780633b20250c1461038d5780633e032a3b146103ad5780634985746f146103c35780634b7ccc25146103d95780635ed88b8414610411576102bf565b80630caf60b61461030e5780631934378514610337578063281651ed146103575780632e3d44001461036d576102bf565b366102bf573373c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2146102bd5773c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b1580156102a357600080fd5b505af11580156102b7573d6000803e3d6000fd5b50505050505b005b3480156102cb57600080fd5b5060405162461bcd60e51b815260206004820152601260248201527111985b1b189858dac81d1c9a59d9d95c995960721b60448201526064015b60405180910390fd5b34801561031a57600080fd5b50610324600b5481565b6040519081526020015b60405180910390f35b34801561034357600080fd5b506102bd610352366004612f0e565b61074c565b34801561036357600080fd5b5061032460095481565b34801561037957600080fd5b50610324610388366004612f0e565b6107a6565b34801561039957600080fd5b506103246103a8366004612f3c565b61085e565b3480156103b957600080fd5b5061032460065481565b3480156103cf57600080fd5b50610324600c5481565b3480156103e557600080fd5b506003546103f9906001600160a01b031681565b6040516001600160a01b03909116815260200161032e565b34801561041d57600080fd5b506103246108e3565b34801561043257600080fd5b50610324600a5481565b34801561044857600080fd5b5061032461095e565b34801561045d57600080fd5b50610324610969565b34801561047257600080fd5b50610324610a17565b34801561048757600080fd5b506102bd610496366004612f3c565b610df9565b3480156104a757600080fd5b5061032460085481565b3480156104bd57600080fd5b506102bd610e4a565b3480156104d257600080fd5b50610324610e5e565b3480156104e757600080fd5b506102bd610eed565b3480156104fc57600080fd5b506102bd610f31565b34801561051157600080fd5b506102bd610520366004612f0e565b611002565b34801561053157600080fd5b506102bd610540366004612f3c565b6111c6565b34801561055157600080fd5b506102bd610560366004612f6b565b611217565b34801561057157600080fd5b506000546001600160a01b03166103f9565b34801561058f57600080fd5b50610324600d5481565b3480156105a557600080fd5b506103246105b4366004612f0e565b611292565b3480156105c557600080fd5b506004546103f9906001600160a01b031681565b3480156105e557600080fd5b506102bd611302565b3480156105fa57600080fd5b506005546103f9906001600160a01b031681565b34801561061a57600080fd5b5061032460075481565b34801561063057600080fd5b506001546001600160a01b03166103f9565b34801561064e57600080fd5b506102bd611557565b34801561066357600080fd5b506102bd610672366004612f6b565b611585565b34801561068357600080fd5b50610324610692366004612f0e565b61160c565b3480156106a357600080fd5b506102bd6106b2366004612f0e565b611696565b3480156106c357600080fd5b506102bd6106d2366004612f3c565b6116ee565b3480156106e357600080fd5b5061032461173f565b3480156106f857600080fd5b506102bd610707366004612f3c565b61176b565b34801561071857600080fd5b50600e546103f9906001600160a01b031681565b34801561073857600080fd5b506102bd610747366004612f0e565b6117dc565b6107546117e9565b603c8110158015610767575061a8c08111155b6107a15760405162461bcd60e51b815260206004820152600b60248201526a316d2d313268206f6e6c7960a81b6044820152606401610305565b600d55565b6000806107fb731f98431c8ad98523631ae4a59f267346ea31f9846107f673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273f19308f923582a6f7c465e5ce7a9dc1bec6665b1612710611816565b61188d565b60125490915060009061082090839061081b9063ffffffff16603c612f9e565b611976565b9050610856818573c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273f19308f923582a6f7c465e5ce7a9dc1bec6665b1611a44565b949350505050565b6040516370a0823160e01b81526001600160a01b038216600482015260009073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2906370a0823190602401602060405180830381865afa1580156108b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108dd9190612fc6565b92915050565b6040516370a0823160e01b815230600482015260009073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2906370a0823190602401602060405180830381865afa158015610935573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109599190612fc6565b905090565b60006109593061085e565b600e546012546000918291610993916001600160a01b03169061081b9063ffffffff16603c612f9e565b6001600160a01b0316905060006109aa8280612fdf565b9050670de0b6b3a764000060006109c68383600160c01b611b0c565b6003549091506001600160a01b031673f19308f923582a6f7c465e5ce7a9dc1bec6665b1106109f55780610a0e565b610a0e816ec097ce7bc90715b34b9f100000000061300c565b95945050505050565b6000610a21611bd0565b6003546001600160a01b031680610a4b576040516333deee4b60e11b815260040160405180910390fd5b333214610a6b576040516348f5c3ed60e01b815260040160405180910390fd5b600d54600c54610a7b9042613020565b11610a995760405163998d019b60e01b815260040160405180910390fd5b42600c556040516370a0823160e01b815230600482015273e592427a0aece92de3edee1f18e0157c058615649073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29060009082906370a0823190602401602060405180830381865afa158015610b07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b2b9190612fc6565b600b5490915080821115610b3d578091505b6000612710610b4e61012c85612fdf565b610b58919061300c565b604051632e1a7d4d60e01b8152600481018290529091506001600160a01b03851690632e1a7d4d90602401600060405180830381600087803b158015610b9d57600080fd5b505af1158015610bb1573d6000803e3d6000fd5b505050508083610bc19190613020565b925082600003610be357604051627c4e1b60e11b815260040160405180910390fd5b610bf76001600160a01b0385168685611bf8565b60408051736015551cd911ff4685072e2793f56c841e3ab66160611b602082015261027160ec1b6034820181905273f19308f923582a6f7c465e5ce7a9dc1bec6665b160601b6037830152604b8201526bffffffffffffffffffffffff19606089901b16604e8201528151604281830301815260629091019091526000610c7d85611292565b6040805160a081018252848152306020820152919250600091908101610ca4426001613033565b8152602001878152602001838152509050876001600160a01b031663c04b8d59826040518263ffffffff1660e01b8152600401610ce1919061306a565b6020604051808303816000875af1158015610d00573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d249190612fc6565b9950886001600160a01b031663bb88603c6040518163ffffffff1660e01b8152600401600060405180830381600087803b158015610d6157600080fd5b505af1158015610d75573d6000803e3d6000fd5b505050508560076000828254610d8b9190613033565b925050819055508960086000828254610da49190613033565b90915550610db490503385611c88565b60405133908b9088907f1b6fe3d614107093562b62b9236e265cac820f430060c5eb674a70824a7435db90600090a4505050505050505050610df66001600255565b90565b610e016117e9565b6001600160a01b038116610e2857604051633c7e6f8f60e21b815260040160405180910390fd5b600480546001600160a01b0319166001600160a01b0392909216919091179055565b610e526117e9565b610e5c6000611d24565b565b600b546040516370a0823160e01b81523060048201526000919073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29081906370a0823190602401602060405180830381865afa158015610eb6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610eda9190612fc6565b925081831115610ee8578192505b505090565b60015433906001600160a01b03168114610f255760405163118cdaa760e01b81526001600160a01b0382166004820152602401610305565b610f2e81611d24565b50565b610f396117e9565b601254600160481b900460ff1615610f895760405162461bcd60e51b8152602060048201526013602482015272105b1c9958591e481a5b9a5d1a585b1a5e9959606a1b6044820152606401610305565b6004805460408051633d47c34b60e01b815290516001600160a01b03909216928392633d47c34b92808301926000929182900301818387803b158015610fce57600080fd5b505af1158015610fe2573d6000803e3d6000fd5b50506012805469ff0000000000000000001916600160481b179055505050565b61100a6117e9565b6003546001600160a01b031680611034576040516333deee4b60e11b815260040160405180910390fd5b6040516370a0823160e01b8152306004820152819073f19308f923582a6f7c465e5ce7a9dc1bec6665b19060009082906370a0823190602401602060405180830381865afa15801561108a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110ae9190612fc6565b9050600081116111005760405162461bcd60e51b815260206004820152601860248201527f50726f7669646520546974616e58204c697175696469747900000000000000006044820152606401610305565b6040516364a3a24960e11b8152600481018690526001600160a01b0384169063c947449290602401600060405180830381600087803b15801561114257600080fd5b505af1158015611156573d6000803e3d6000fd5b50611183925050506001600160a01b03831673c36442b4a4522e871399cd717abdd847ab11fe8883611bf8565b6111ab6001600160a01b03841673c36442b4a4522e871399cd717abdd847ab11fe8887611bf8565b6111b58186611d3d565b6111bf8186611f2d565b5050505050565b6111ce6117e9565b6001600160a01b0381166111f5576040516333deee4b60e11b815260040160405180910390fd5b600380546001600160a01b0319166001600160a01b0392909216919091179055565b61121f6117e9565b60058163ffffffff161015801561123d5750603c8163ffffffff1611155b6112765760405162461bcd60e51b815260206004820152600a602482015269356d2d3168206f6e6c7960b01b6044820152606401610305565b6012805463ffffffff191663ffffffff92909216919091179055565b600654600090816112a2846107a6565b9050600060646112b28482613020565b6112bc9084612fdf565b6112c6919061300c565b905060006112d38261160c565b9050600060646112e38682613020565b6112ed9084612fdf565b6112f7919061300c565b979650505050505050565b61130a611bd0565b6003546005546001600160a01b039182169173f19308f923582a6f7c465e5ce7a9dc1bec6665b1911682611351576040516333deee4b60e11b815260040160405180910390fd5b338373f19308f923582a6f7c465e5ce7a9dc1bec6665b16000806113736120d2565b91509150600080886001600160a01b03168a6001600160a01b0316101561139e5750829050816113a4565b50819050825b601254600160401b900460ff16156114b15760006113c0610969565b905082158015906113d057508115155b156114ab576113fd6001600160a01b03881673c36442b4a4522e871399cd717abdd847ab11fe8885611bf8565b6114256001600160a01b03871673c36442b4a4522e871399cd717abdd847ab11fe8884611bf8565b8a6001600160a01b03168a6001600160a01b0316101561144f5761144a8284836121b2565b611472565b611472838361146d846ec097ce7bc90715b34b9f100000000061300c565b6121b2565b876001600160a01b031682847f0351f600ef1e31e5e13b4dc27bff4cbde3e9269f0ffc666629ae6cac573eb22060405160405180910390a45b50611543565b81600960008282546114c39190613033565b9250508190555080600a60008282546114dc9190613033565b909155506114f690506001600160a01b038a168b8361235c565b61150a6001600160a01b038b16898461235c565b866001600160a01b031681837fb3ff07f4fe20273bbc264b773aacc6325987f8b0b1aa4c5bdfe5b75fdbd1284c60405160405180910390a45b50505050505050505050610e5c6001600255565b61155f6117e9565b6012805468ff0000000000000000198116600160401b9182900460ff1615909102179055565b61158d6117e9565b60058163ffffffff16101580156115ab5750603c8163ffffffff1611155b6115e45760405162461bcd60e51b815260206004820152600a602482015269356d2d3168206f6e6c7960b01b6044820152606401610305565b6012805463ffffffff9092166401000000000267ffffffff0000000019909216919091179055565b60035460009073f19308f923582a6f7c465e5ce7a9dc1bec6665b1906001600160a01b031682611657731f98431c8ad98523631ae4a59f267346ea31f9846107f68486612710611816565b9050600061167e82601260049054906101000a900463ffffffff16603c61081b9190612f9e565b905061168c81878686611a44565b9695505050505050565b61169e6117e9565b600581101580156116b05750600f8111155b6116e95760405162461bcd60e51b815260206004820152600a602482015269352d313525206f6e6c7960b01b6044820152606401610305565b600655565b6116f66117e9565b6001600160a01b03811661171d5760405163e6c4247b60e01b815260040160405180910390fd5b600580546001600160a01b0319166001600160a01b0392909216919091179055565b60008061174a610e5e565b905061271061175b61012c83612fdf565b611765919061300c565b91505090565b6117736117e9565b600180546001600160a01b0383166001600160a01b031990911681179091556117a46000546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b6117e46117e9565b600b55565b6000546001600160a01b03163314610e5c5760405163118cdaa760e01b8152336004820152602401610305565b6040805160608101825260008082526020820181905291810191909152826001600160a01b0316846001600160a01b03161115611851579192915b6040518060600160405280856001600160a01b03168152602001846001600160a01b031681526020018362ffffff1681525090505b9392505050565b600081602001516001600160a01b031682600001516001600160a01b0316106118b557600080fd5b815160208084015160408086015181516001600160a01b0395861681860152949092168482015262ffffff90911660608085019190915281518085038201815260808501909252815191909201206001600160f81b031960a08401529085901b6bffffffffffffffffffffffff191660a183015260b58201527fe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b5460d582015260f50160408051601f1981840301815291905280516020909101209392505050565b600080611982846123bb565b90508263ffffffff168163ffffffff16101561199c578092505b8263ffffffff16600003611a21576000849050806001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156119ed573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a119190613100565b50949750611a3d95505050505050565b6000611a2d8585612574565b509050611a39816127b8565b9250505b5092915050565b60006001600160801b036001600160a01b03861611611ab8576000611a726001600160a01b03871680612fdf565b9050826001600160a01b0316846001600160a01b031610611aa157611a9c600160c01b8683611b0c565b611ab0565b611ab08186600160c01b611b0c565b915050610856565b6000611ad26001600160a01b03871680600160401b611b0c565b9050826001600160a01b0316846001600160a01b031610611b0157611afc600160801b8683611b0c565b61168c565b61168c8186600160801b5b6000838302816000198587098281108382030391505080600003611b4357838281611b3957611b39612ff6565b0492505050611886565b808411611b635760405163227bc15360e01b815260040160405180910390fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b6002805403611bf257604051633ee5aeb560e01b815260040160405180910390fd5b60028055565b604051636eb1769f60e11b81523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015611c48573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c6c9190612fc6565b9050611c828484611c7d8585613033565b612bc6565b50505050565b80471015611cab5760405163cd78605960e01b8152306004820152602401610305565b6000826001600160a01b03168260405160006040518083038185875af1925050503d8060008114611cf8576040519150601f19603f3d011682016040523d82523d6000602084013e611cfd565b606091505b5050905080611d1f57604051630a12f52160e11b815260040160405180910390fd5b505050565b600180546001600160a01b0319169055610f2e81612c56565b600080600080611d4d8686612ca6565b9296509094509250905073c36442b4a4522e871399cd717abdd847ab11fe886000633b9aca00611e1585611d8986670de0b6b3a7640000612fdf565b611d93919061300c565b6001600160881b03811160071b81811c68ffffffffffffffffff1060061b1781811c64ffffffffff1060051b1781811c62ffffff1060041b1781811c620100000160b5600192831c1b0260121c80830401811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b611e2390600160601b612fdf565b611e2d919061300c565b6040516309f56ab160e11b81526001600160a01b038881166004830152878116602483015261271060448301528083166064830152919250908316906313ead562906084016020604051808303816000875af1158015611e91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eb5919061319a565b600e80546001600160a01b0319166001600160a01b039290921691821790556040516332148f6760e01b8152606460048201526332148f6790602401600060405180830381600087803b158015611f0b57600080fd5b505af1158015611f1f573d6000803e3d6000fd5b505050505050505050505050565b73c36442b4a4522e871399cd717abdd847ab11fe886000808080611f518787612ca6565b93509350935093506000604051806101600160405280866001600160a01b03168152602001856001600160a01b0316815260200161271062ffffff168152602001620d899f1960020b8152602001620d89a060020b8152602001848152602001838152602001606485605a611fc69190612fdf565b611fd0919061300c565b81526020016064611fe285605a612fdf565b611fec919061300c565b815230602082015260400161200342610258613033565b8152509050600080876001600160a01b03166388316456846040518263ffffffff1660e01b815260040161203791906131b7565b6080604051808303816000875af1158015612056573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061207a9190613292565b5050600f805469ffffffffffffffffffff191669ffffffffffffffffffff93909316929092179091556001600160801b031660105550506011805465ffffffffffff1916650d89a0f276601790555050505050505050565b60408051608081018252600f5469ffffffffffffffffffff16815230602082019081526001600160801b0382840181815260608401828152945163fc6f786560e01b81528451600482015292516001600160a01b03166024840152518116604483015292519092166064830152600091829173c36442b4a4522e871399cd717abdd847ab11fe8891829063fc6f78659060840160408051808303816000875af1158015612183573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121a791906132ce565b909590945092505050565b60006121c78383670de0b6b3a7640000611b0c565b905060006121de85670de0b6b3a764000085611b0c565b905060008286106121ef57826121f1565b855b905060008286106122025782612204565b855b6040805160c081018252600f5469ffffffffffffffffffff1681526020810185905290810182905290915060009060608101606461224386605a612fdf565b61224d919061300c565b8152602001606461225f85605a612fdf565b612269919061300c565b815260200161227a42610258613033565b90526040805163219f5d1760e01b81528251600482015260208301516024820152908201516044820152606082015160648201526080820151608482015260a082015160a482015290915060009073c36442b4a4522e871399cd717abdd847ab11fe889063219f5d179060c4016060604051808303816000875af1158015612306573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061232a91906132f2565b50506001600160801b0316905080600f600101600082825461234c9190613033565b9091555050505050505050505050565b6040516001600160a01b03838116602483015260448201839052611d1f91859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050612d10565b6000806000836001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156123fe573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124229190613100565b50505093509350505060008161ffff16116124645760405162461bcd60e51b81526020600482015260026024820152614e4960f01b6044820152606401610305565b6000806001600160a01b03861663252c09d784612482876001613327565b61248c9190613342565b6040516001600160e01b031960e084901b16815261ffff9091166004820152602401608060405180830381865afa1580156124cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124ef9190613375565b9350505091508061256a5760405163252c09d760e01b8152600060048201526001600160a01b0387169063252c09d790602401608060405180830381865afa15801561253f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125639190613375565b5091935050505b61168c82426133cd565b6000808263ffffffff166000036125b25760405162461bcd60e51b8152602060048201526002602482015261042560f41b6044820152606401610305565b60408051600280825260608201835260009260208301908036833701905050905083816000815181106125e7576125e7613400565b602002602001019063ffffffff16908163ffffffff168152505060008160018151811061261657612616613400565b602002602001019063ffffffff16908163ffffffff1681525050600080866001600160a01b031663883bdbfd846040518263ffffffff1660e01b815260040161265f9190613416565b600060405180830381865afa15801561267c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526126a49190810190613529565b915091506000826000815181106126bd576126bd613400565b6020026020010151836001815181106126d8576126d8613400565b60200260200101516126ea91906135ec565b905060008260008151811061270157612701613400565b60200260200101518360018151811061271c5761271c613400565b602002602001015161272e9190613619565b905063ffffffff88166127418184613639565b975060008360060b128015612761575061275b8184613677565b60060b15155b15612774578761277081613699565b9850505b63ffffffff8916640100000000600160c01b03602084901b1661279e6001600160a01b03836136bc565b6127a891906136ee565b9750505050505050509250929050565b60008060008360020b126127cf578260020b6127dc565b8260020b6127dc90613714565b90506127eb620d89e719613730565b60020b8111156128215760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610305565b60008160011660000361283857600160801b61284a565b6ffffcb933bd6fad37aa2d162d1a5940015b6001600160881b03169050600282161561287f57608061287a826ffff97272373d413259a46990580e213a612fdf565b901c90505b60048216156128a95760806128a4826ffff2e50f5f656932ef12357cf3c7fdcc612fdf565b901c90505b60088216156128d35760806128ce826fffe5caca7e10e4e61c3624eaa0941cd0612fdf565b901c90505b60108216156128fd5760806128f8826fffcb9843d60f6159c9db58835c926644612fdf565b901c90505b6020821615612927576080612922826fff973b41fa98c081472e6896dfb254c0612fdf565b901c90505b604082161561295157608061294c826fff2ea16466c96a3843ec78b326b52861612fdf565b901c90505b608082161561297b576080612976826ffe5dee046a99a2a811c461f1969c3053612fdf565b901c90505b6101008216156129a65760806129a1826ffcbe86c7900a88aedcffc83b479aa3a4612fdf565b901c90505b6102008216156129d15760806129cc826ff987a7253ac413176f2b074cf7815e54612fdf565b901c90505b6104008216156129fc5760806129f7826ff3392b0822b70005940c7a398e4b70f3612fdf565b901c90505b610800821615612a27576080612a22826fe7159475a2c29b7443b29c7fa6e889d9612fdf565b901c90505b611000821615612a52576080612a4d826fd097f3bdfd2022b8845ad8f792aa5825612fdf565b901c90505b612000821615612a7d576080612a78826fa9f746462d870fdf8a65dc1f90e061e5612fdf565b901c90505b614000821615612aa8576080612aa3826f70d869a156d2a1b890bb3df62baf32f7612fdf565b901c90505b618000821615612ad3576080612ace826f31be135f97d08fd981231505542fcfa6612fdf565b901c90505b62010000821615612aff576080612afa826f09aa508b5b7a84e1c677de54f3e99bc9612fdf565b901c90505b62020000821615612b2a576080612b25826e5d6af8dedb81196699c329225ee604612fdf565b901c90505b62040000821615612b54576080612b4f826d2216e584f5fa1ea926041bedfe98612fdf565b901c90505b62080000821615612b7c576080612b77826b048a170391f7dc42444e8fa2612fdf565b901c90505b60008460020b1315612b9757612b948160001961300c565b90505b612ba664010000000082613752565b15612bb2576001612bb5565b60005b6108569060ff16602083901c613033565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052612c178482612d73565b611c82576040516001600160a01b03848116602483015260006044830152612c4c91869182169063095ea7b390606401612389565b611c828482612d10565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6003546000908190819081906001600160a01b031673f19308f923582a6f7c465e5ce7a9dc1bec6665b1808210612cde578082612ce1565b81815b90965094506001600160a01b0380871690831614612d00578787612d03565b86885b9699959850965050505050565b6000612d256001600160a01b03841683612e16565b90508051600014158015612d4a575080806020019051810190612d489190613766565b155b15611d1f57604051635274afe760e01b81526001600160a01b0384166004820152602401610305565b6000806000846001600160a01b031684604051612d909190613781565b6000604051808303816000865af19150503d8060008114612dcd576040519150601f19603f3d011682016040523d82523d6000602084013e612dd2565b606091505b5091509150818015612dfc575080511580612dfc575080806020019051810190612dfc9190613766565b8015611a395750505050506001600160a01b03163b151590565b60606118868383600084600080856001600160a01b03168486604051612e3c9190613781565b60006040518083038185875af1925050503d8060008114612e79576040519150601f19603f3d011682016040523d82523d6000602084013e612e7e565b606091505b509150915061168c868383606082612e9e57612e9982612ee5565b611886565b8151158015612eb557506001600160a01b0384163b155b15612ede57604051639996b31560e01b81526001600160a01b0385166004820152602401610305565b5080611886565b805115612ef55780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b600060208284031215612f2057600080fd5b5035919050565b6001600160a01b0381168114610f2e57600080fd5b600060208284031215612f4e57600080fd5b813561188681612f27565b63ffffffff81168114610f2e57600080fd5b600060208284031215612f7d57600080fd5b813561188681612f59565b634e487b7160e01b600052601160045260246000fd5b63ffffffff818116838216028082169190828114612fbe57612fbe612f88565b505092915050565b600060208284031215612fd857600080fd5b5051919050565b80820281158282048414176108dd576108dd612f88565b634e487b7160e01b600052601260045260246000fd5b60008261301b5761301b612ff6565b500490565b818103818111156108dd576108dd612f88565b808201808211156108dd576108dd612f88565b60005b83811015613061578181015183820152602001613049565b50506000910152565b602081526000825160a0602084015280518060c08501526130928160e0860160208501613046565b60018060a01b0360208601511660408501526040850151606085015260608501516080850152608085015160a085015260e0601f19601f8301168501019250505092915050565b805161ffff811681146130eb57600080fd5b919050565b805180151581146130eb57600080fd5b600080600080600080600060e0888a03121561311b57600080fd5b875161312681612f27565b8097505060208801518060020b811461313e57600080fd5b955061314c604089016130d9565b945061315a606089016130d9565b9350613168608089016130d9565b925060a088015160ff8116811461317e57600080fd5b915061318c60c089016130f0565b905092959891949750929550565b6000602082840312156131ac57600080fd5b815161188681612f27565b81516001600160a01b03168152610160810160208301516131e360208401826001600160a01b03169052565b5060408301516131fa604084018262ffffff169052565b50606083015161320f606084018260020b9052565b506080830151613224608084018260020b9052565b5060a083015160a083015260c083015160c083015260e083015160e08301526101008084015181840152506101208084015161326a828501826001600160a01b03169052565b505061014092830151919092015290565b80516001600160801b03811681146130eb57600080fd5b600080600080608085870312156132a857600080fd5b845193506132b86020860161327b565b6040860151606090960151949790965092505050565b600080604083850312156132e157600080fd5b505080516020909101519092909150565b60008060006060848603121561330757600080fd5b6133108461327b565b925060208401519150604084015190509250925092565b61ffff818116838216019080821115611a3d57611a3d612f88565b600061ffff8084168061335757613357612ff6565b92169190910692915050565b8051600681900b81146130eb57600080fd5b6000806000806080858703121561338b57600080fd5b845161339681612f59565b93506133a460208601613363565b925060408501516133b481612f27565b91506133c2606086016130f0565b905092959194509250565b63ffffffff828116828216039080821115611a3d57611a3d612f88565b634e487b7160e01b600052604160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b6020808252825182820181905260009190848201906040850190845b8181101561345457835163ffffffff1683529284019291840191600101613432565b50909695505050505050565b604051601f8201601f1916810167ffffffffffffffff81118282101715613489576134896133ea565b604052919050565b600067ffffffffffffffff8211156134ab576134ab6133ea565b5060051b60200190565b600082601f8301126134c657600080fd5b815160206134db6134d683613491565b613460565b82815260059290921b840181019181810190868411156134fa57600080fd5b8286015b8481101561351e57805161351181612f27565b83529183019183016134fe565b509695505050505050565b6000806040838503121561353c57600080fd5b825167ffffffffffffffff8082111561355457600080fd5b818501915085601f83011261356857600080fd5b815160206135786134d683613491565b82815260059290921b8401810191818101908984111561359757600080fd5b948201945b838610156135bc576135ad86613363565b8252948201949082019061359c565b918801519196509093505050808211156135d557600080fd5b506135e2858286016134b5565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156108dd576108dd612f88565b6001600160a01b03828116828216039080821115611a3d57611a3d612f88565b60008160060b8360060b8061365057613650612ff6565b667fffffffffffff1982146000198214161561366e5761366e612f88565b90059392505050565b60008260060b8061368a5761368a612ff6565b808360060b0791505092915050565b60008160020b627fffff1981036136b2576136b2612f88565b6000190192915050565b6001600160c01b038281168282168181028316929181158285048214176136e5576136e5612f88565b50505092915050565b60006001600160c01b038381168061370857613708612ff6565b92169190910492915050565b6000600160ff1b820161372957613729612f88565b5060000390565b60008160020b627fffff19810361374957613749612f88565b60000392915050565b60008261376157613761612ff6565b500690565b60006020828403121561377857600080fd5b611886826130f0565b60008251613793818460208701613046565b919091019291505056fea2646970667358221220044a58ce7c0249b80cfd53e7cc0cf6bd0ce79009acfa48447f3638cd447393d464736f6c63430008140033
Deployed Bytecode
0x6080604052600436106102345760003560e01c806382c791f01161012e578063e30c3978116100ab578063f1e741a81161006f578063f1e741a8146106b7578063f2419177146106d7578063f2fde38b146106ec578063f55e943e1461070c578063f58545ac1461072c576102bf565b8063e30c397814610624578063e8078d9414610642578063e9373eef14610657578063eb35d16014610677578063f0fa55a914610697576102bf565b8063a6fc9f66116100f2578063a6fc9f6614610599578063afb16a5c146105b9578063c8796572146105d9578063d770f068146105ee578063df79d7521461060e576102bf565b806382c791f01461050557806384ef03ba146105255780638c14a5d6146105455780638da5cb5b14610565578063947a36fb14610583576102bf565b806361093ad2116101bc5780636d84fb83116101805780636d84fb831461049b578063715018a6146104b15780637708926a146104c657806379ba5097146104db5780637b4ba9af146104f0576102bf565b806361093ad214610426578063636b32ea1461043c578063665f8efb1461045157806366ffd6c6146104665780636a70962e1461047b576102bf565b80633b20250c116102035780633b20250c1461038d5780633e032a3b146103ad5780634985746f146103c35780634b7ccc25146103d95780635ed88b8414610411576102bf565b80630caf60b61461030e5780631934378514610337578063281651ed146103575780632e3d44001461036d576102bf565b366102bf573373c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2146102bd5773c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b1580156102a357600080fd5b505af11580156102b7573d6000803e3d6000fd5b50505050505b005b3480156102cb57600080fd5b5060405162461bcd60e51b815260206004820152601260248201527111985b1b189858dac81d1c9a59d9d95c995960721b60448201526064015b60405180910390fd5b34801561031a57600080fd5b50610324600b5481565b6040519081526020015b60405180910390f35b34801561034357600080fd5b506102bd610352366004612f0e565b61074c565b34801561036357600080fd5b5061032460095481565b34801561037957600080fd5b50610324610388366004612f0e565b6107a6565b34801561039957600080fd5b506103246103a8366004612f3c565b61085e565b3480156103b957600080fd5b5061032460065481565b3480156103cf57600080fd5b50610324600c5481565b3480156103e557600080fd5b506003546103f9906001600160a01b031681565b6040516001600160a01b03909116815260200161032e565b34801561041d57600080fd5b506103246108e3565b34801561043257600080fd5b50610324600a5481565b34801561044857600080fd5b5061032461095e565b34801561045d57600080fd5b50610324610969565b34801561047257600080fd5b50610324610a17565b34801561048757600080fd5b506102bd610496366004612f3c565b610df9565b3480156104a757600080fd5b5061032460085481565b3480156104bd57600080fd5b506102bd610e4a565b3480156104d257600080fd5b50610324610e5e565b3480156104e757600080fd5b506102bd610eed565b3480156104fc57600080fd5b506102bd610f31565b34801561051157600080fd5b506102bd610520366004612f0e565b611002565b34801561053157600080fd5b506102bd610540366004612f3c565b6111c6565b34801561055157600080fd5b506102bd610560366004612f6b565b611217565b34801561057157600080fd5b506000546001600160a01b03166103f9565b34801561058f57600080fd5b50610324600d5481565b3480156105a557600080fd5b506103246105b4366004612f0e565b611292565b3480156105c557600080fd5b506004546103f9906001600160a01b031681565b3480156105e557600080fd5b506102bd611302565b3480156105fa57600080fd5b506005546103f9906001600160a01b031681565b34801561061a57600080fd5b5061032460075481565b34801561063057600080fd5b506001546001600160a01b03166103f9565b34801561064e57600080fd5b506102bd611557565b34801561066357600080fd5b506102bd610672366004612f6b565b611585565b34801561068357600080fd5b50610324610692366004612f0e565b61160c565b3480156106a357600080fd5b506102bd6106b2366004612f0e565b611696565b3480156106c357600080fd5b506102bd6106d2366004612f3c565b6116ee565b3480156106e357600080fd5b5061032461173f565b3480156106f857600080fd5b506102bd610707366004612f3c565b61176b565b34801561071857600080fd5b50600e546103f9906001600160a01b031681565b34801561073857600080fd5b506102bd610747366004612f0e565b6117dc565b6107546117e9565b603c8110158015610767575061a8c08111155b6107a15760405162461bcd60e51b815260206004820152600b60248201526a316d2d313268206f6e6c7960a81b6044820152606401610305565b600d55565b6000806107fb731f98431c8ad98523631ae4a59f267346ea31f9846107f673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273f19308f923582a6f7c465e5ce7a9dc1bec6665b1612710611816565b61188d565b60125490915060009061082090839061081b9063ffffffff16603c612f9e565b611976565b9050610856818573c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273f19308f923582a6f7c465e5ce7a9dc1bec6665b1611a44565b949350505050565b6040516370a0823160e01b81526001600160a01b038216600482015260009073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2906370a0823190602401602060405180830381865afa1580156108b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108dd9190612fc6565b92915050565b6040516370a0823160e01b815230600482015260009073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2906370a0823190602401602060405180830381865afa158015610935573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109599190612fc6565b905090565b60006109593061085e565b600e546012546000918291610993916001600160a01b03169061081b9063ffffffff16603c612f9e565b6001600160a01b0316905060006109aa8280612fdf565b9050670de0b6b3a764000060006109c68383600160c01b611b0c565b6003549091506001600160a01b031673f19308f923582a6f7c465e5ce7a9dc1bec6665b1106109f55780610a0e565b610a0e816ec097ce7bc90715b34b9f100000000061300c565b95945050505050565b6000610a21611bd0565b6003546001600160a01b031680610a4b576040516333deee4b60e11b815260040160405180910390fd5b333214610a6b576040516348f5c3ed60e01b815260040160405180910390fd5b600d54600c54610a7b9042613020565b11610a995760405163998d019b60e01b815260040160405180910390fd5b42600c556040516370a0823160e01b815230600482015273e592427a0aece92de3edee1f18e0157c058615649073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29060009082906370a0823190602401602060405180830381865afa158015610b07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b2b9190612fc6565b600b5490915080821115610b3d578091505b6000612710610b4e61012c85612fdf565b610b58919061300c565b604051632e1a7d4d60e01b8152600481018290529091506001600160a01b03851690632e1a7d4d90602401600060405180830381600087803b158015610b9d57600080fd5b505af1158015610bb1573d6000803e3d6000fd5b505050508083610bc19190613020565b925082600003610be357604051627c4e1b60e11b815260040160405180910390fd5b610bf76001600160a01b0385168685611bf8565b60408051736015551cd911ff4685072e2793f56c841e3ab66160611b602082015261027160ec1b6034820181905273f19308f923582a6f7c465e5ce7a9dc1bec6665b160601b6037830152604b8201526bffffffffffffffffffffffff19606089901b16604e8201528151604281830301815260629091019091526000610c7d85611292565b6040805160a081018252848152306020820152919250600091908101610ca4426001613033565b8152602001878152602001838152509050876001600160a01b031663c04b8d59826040518263ffffffff1660e01b8152600401610ce1919061306a565b6020604051808303816000875af1158015610d00573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d249190612fc6565b9950886001600160a01b031663bb88603c6040518163ffffffff1660e01b8152600401600060405180830381600087803b158015610d6157600080fd5b505af1158015610d75573d6000803e3d6000fd5b505050508560076000828254610d8b9190613033565b925050819055508960086000828254610da49190613033565b90915550610db490503385611c88565b60405133908b9088907f1b6fe3d614107093562b62b9236e265cac820f430060c5eb674a70824a7435db90600090a4505050505050505050610df66001600255565b90565b610e016117e9565b6001600160a01b038116610e2857604051633c7e6f8f60e21b815260040160405180910390fd5b600480546001600160a01b0319166001600160a01b0392909216919091179055565b610e526117e9565b610e5c6000611d24565b565b600b546040516370a0823160e01b81523060048201526000919073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29081906370a0823190602401602060405180830381865afa158015610eb6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610eda9190612fc6565b925081831115610ee8578192505b505090565b60015433906001600160a01b03168114610f255760405163118cdaa760e01b81526001600160a01b0382166004820152602401610305565b610f2e81611d24565b50565b610f396117e9565b601254600160481b900460ff1615610f895760405162461bcd60e51b8152602060048201526013602482015272105b1c9958591e481a5b9a5d1a585b1a5e9959606a1b6044820152606401610305565b6004805460408051633d47c34b60e01b815290516001600160a01b03909216928392633d47c34b92808301926000929182900301818387803b158015610fce57600080fd5b505af1158015610fe2573d6000803e3d6000fd5b50506012805469ff0000000000000000001916600160481b179055505050565b61100a6117e9565b6003546001600160a01b031680611034576040516333deee4b60e11b815260040160405180910390fd5b6040516370a0823160e01b8152306004820152819073f19308f923582a6f7c465e5ce7a9dc1bec6665b19060009082906370a0823190602401602060405180830381865afa15801561108a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110ae9190612fc6565b9050600081116111005760405162461bcd60e51b815260206004820152601860248201527f50726f7669646520546974616e58204c697175696469747900000000000000006044820152606401610305565b6040516364a3a24960e11b8152600481018690526001600160a01b0384169063c947449290602401600060405180830381600087803b15801561114257600080fd5b505af1158015611156573d6000803e3d6000fd5b50611183925050506001600160a01b03831673c36442b4a4522e871399cd717abdd847ab11fe8883611bf8565b6111ab6001600160a01b03841673c36442b4a4522e871399cd717abdd847ab11fe8887611bf8565b6111b58186611d3d565b6111bf8186611f2d565b5050505050565b6111ce6117e9565b6001600160a01b0381166111f5576040516333deee4b60e11b815260040160405180910390fd5b600380546001600160a01b0319166001600160a01b0392909216919091179055565b61121f6117e9565b60058163ffffffff161015801561123d5750603c8163ffffffff1611155b6112765760405162461bcd60e51b815260206004820152600a602482015269356d2d3168206f6e6c7960b01b6044820152606401610305565b6012805463ffffffff191663ffffffff92909216919091179055565b600654600090816112a2846107a6565b9050600060646112b28482613020565b6112bc9084612fdf565b6112c6919061300c565b905060006112d38261160c565b9050600060646112e38682613020565b6112ed9084612fdf565b6112f7919061300c565b979650505050505050565b61130a611bd0565b6003546005546001600160a01b039182169173f19308f923582a6f7c465e5ce7a9dc1bec6665b1911682611351576040516333deee4b60e11b815260040160405180910390fd5b338373f19308f923582a6f7c465e5ce7a9dc1bec6665b16000806113736120d2565b91509150600080886001600160a01b03168a6001600160a01b0316101561139e5750829050816113a4565b50819050825b601254600160401b900460ff16156114b15760006113c0610969565b905082158015906113d057508115155b156114ab576113fd6001600160a01b03881673c36442b4a4522e871399cd717abdd847ab11fe8885611bf8565b6114256001600160a01b03871673c36442b4a4522e871399cd717abdd847ab11fe8884611bf8565b8a6001600160a01b03168a6001600160a01b0316101561144f5761144a8284836121b2565b611472565b611472838361146d846ec097ce7bc90715b34b9f100000000061300c565b6121b2565b876001600160a01b031682847f0351f600ef1e31e5e13b4dc27bff4cbde3e9269f0ffc666629ae6cac573eb22060405160405180910390a45b50611543565b81600960008282546114c39190613033565b9250508190555080600a60008282546114dc9190613033565b909155506114f690506001600160a01b038a168b8361235c565b61150a6001600160a01b038b16898461235c565b866001600160a01b031681837fb3ff07f4fe20273bbc264b773aacc6325987f8b0b1aa4c5bdfe5b75fdbd1284c60405160405180910390a45b50505050505050505050610e5c6001600255565b61155f6117e9565b6012805468ff0000000000000000198116600160401b9182900460ff1615909102179055565b61158d6117e9565b60058163ffffffff16101580156115ab5750603c8163ffffffff1611155b6115e45760405162461bcd60e51b815260206004820152600a602482015269356d2d3168206f6e6c7960b01b6044820152606401610305565b6012805463ffffffff9092166401000000000267ffffffff0000000019909216919091179055565b60035460009073f19308f923582a6f7c465e5ce7a9dc1bec6665b1906001600160a01b031682611657731f98431c8ad98523631ae4a59f267346ea31f9846107f68486612710611816565b9050600061167e82601260049054906101000a900463ffffffff16603c61081b9190612f9e565b905061168c81878686611a44565b9695505050505050565b61169e6117e9565b600581101580156116b05750600f8111155b6116e95760405162461bcd60e51b815260206004820152600a602482015269352d313525206f6e6c7960b01b6044820152606401610305565b600655565b6116f66117e9565b6001600160a01b03811661171d5760405163e6c4247b60e01b815260040160405180910390fd5b600580546001600160a01b0319166001600160a01b0392909216919091179055565b60008061174a610e5e565b905061271061175b61012c83612fdf565b611765919061300c565b91505090565b6117736117e9565b600180546001600160a01b0383166001600160a01b031990911681179091556117a46000546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b6117e46117e9565b600b55565b6000546001600160a01b03163314610e5c5760405163118cdaa760e01b8152336004820152602401610305565b6040805160608101825260008082526020820181905291810191909152826001600160a01b0316846001600160a01b03161115611851579192915b6040518060600160405280856001600160a01b03168152602001846001600160a01b031681526020018362ffffff1681525090505b9392505050565b600081602001516001600160a01b031682600001516001600160a01b0316106118b557600080fd5b815160208084015160408086015181516001600160a01b0395861681860152949092168482015262ffffff90911660608085019190915281518085038201815260808501909252815191909201206001600160f81b031960a08401529085901b6bffffffffffffffffffffffff191660a183015260b58201527fe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b5460d582015260f50160408051601f1981840301815291905280516020909101209392505050565b600080611982846123bb565b90508263ffffffff168163ffffffff16101561199c578092505b8263ffffffff16600003611a21576000849050806001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156119ed573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a119190613100565b50949750611a3d95505050505050565b6000611a2d8585612574565b509050611a39816127b8565b9250505b5092915050565b60006001600160801b036001600160a01b03861611611ab8576000611a726001600160a01b03871680612fdf565b9050826001600160a01b0316846001600160a01b031610611aa157611a9c600160c01b8683611b0c565b611ab0565b611ab08186600160c01b611b0c565b915050610856565b6000611ad26001600160a01b03871680600160401b611b0c565b9050826001600160a01b0316846001600160a01b031610611b0157611afc600160801b8683611b0c565b61168c565b61168c8186600160801b5b6000838302816000198587098281108382030391505080600003611b4357838281611b3957611b39612ff6565b0492505050611886565b808411611b635760405163227bc15360e01b815260040160405180910390fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b6002805403611bf257604051633ee5aeb560e01b815260040160405180910390fd5b60028055565b604051636eb1769f60e11b81523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015611c48573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c6c9190612fc6565b9050611c828484611c7d8585613033565b612bc6565b50505050565b80471015611cab5760405163cd78605960e01b8152306004820152602401610305565b6000826001600160a01b03168260405160006040518083038185875af1925050503d8060008114611cf8576040519150601f19603f3d011682016040523d82523d6000602084013e611cfd565b606091505b5050905080611d1f57604051630a12f52160e11b815260040160405180910390fd5b505050565b600180546001600160a01b0319169055610f2e81612c56565b600080600080611d4d8686612ca6565b9296509094509250905073c36442b4a4522e871399cd717abdd847ab11fe886000633b9aca00611e1585611d8986670de0b6b3a7640000612fdf565b611d93919061300c565b6001600160881b03811160071b81811c68ffffffffffffffffff1060061b1781811c64ffffffffff1060051b1781811c62ffffff1060041b1781811c620100000160b5600192831c1b0260121c80830401811c80830401811c80830401811c80830401811c80830401811c80830401811c80830401901c908190048111900390565b611e2390600160601b612fdf565b611e2d919061300c565b6040516309f56ab160e11b81526001600160a01b038881166004830152878116602483015261271060448301528083166064830152919250908316906313ead562906084016020604051808303816000875af1158015611e91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eb5919061319a565b600e80546001600160a01b0319166001600160a01b039290921691821790556040516332148f6760e01b8152606460048201526332148f6790602401600060405180830381600087803b158015611f0b57600080fd5b505af1158015611f1f573d6000803e3d6000fd5b505050505050505050505050565b73c36442b4a4522e871399cd717abdd847ab11fe886000808080611f518787612ca6565b93509350935093506000604051806101600160405280866001600160a01b03168152602001856001600160a01b0316815260200161271062ffffff168152602001620d899f1960020b8152602001620d89a060020b8152602001848152602001838152602001606485605a611fc69190612fdf565b611fd0919061300c565b81526020016064611fe285605a612fdf565b611fec919061300c565b815230602082015260400161200342610258613033565b8152509050600080876001600160a01b03166388316456846040518263ffffffff1660e01b815260040161203791906131b7565b6080604051808303816000875af1158015612056573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061207a9190613292565b5050600f805469ffffffffffffffffffff191669ffffffffffffffffffff93909316929092179091556001600160801b031660105550506011805465ffffffffffff1916650d89a0f276601790555050505050505050565b60408051608081018252600f5469ffffffffffffffffffff16815230602082019081526001600160801b0382840181815260608401828152945163fc6f786560e01b81528451600482015292516001600160a01b03166024840152518116604483015292519092166064830152600091829173c36442b4a4522e871399cd717abdd847ab11fe8891829063fc6f78659060840160408051808303816000875af1158015612183573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121a791906132ce565b909590945092505050565b60006121c78383670de0b6b3a7640000611b0c565b905060006121de85670de0b6b3a764000085611b0c565b905060008286106121ef57826121f1565b855b905060008286106122025782612204565b855b6040805160c081018252600f5469ffffffffffffffffffff1681526020810185905290810182905290915060009060608101606461224386605a612fdf565b61224d919061300c565b8152602001606461225f85605a612fdf565b612269919061300c565b815260200161227a42610258613033565b90526040805163219f5d1760e01b81528251600482015260208301516024820152908201516044820152606082015160648201526080820151608482015260a082015160a482015290915060009073c36442b4a4522e871399cd717abdd847ab11fe889063219f5d179060c4016060604051808303816000875af1158015612306573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061232a91906132f2565b50506001600160801b0316905080600f600101600082825461234c9190613033565b9091555050505050505050505050565b6040516001600160a01b03838116602483015260448201839052611d1f91859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050612d10565b6000806000836001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156123fe573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124229190613100565b50505093509350505060008161ffff16116124645760405162461bcd60e51b81526020600482015260026024820152614e4960f01b6044820152606401610305565b6000806001600160a01b03861663252c09d784612482876001613327565b61248c9190613342565b6040516001600160e01b031960e084901b16815261ffff9091166004820152602401608060405180830381865afa1580156124cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124ef9190613375565b9350505091508061256a5760405163252c09d760e01b8152600060048201526001600160a01b0387169063252c09d790602401608060405180830381865afa15801561253f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125639190613375565b5091935050505b61168c82426133cd565b6000808263ffffffff166000036125b25760405162461bcd60e51b8152602060048201526002602482015261042560f41b6044820152606401610305565b60408051600280825260608201835260009260208301908036833701905050905083816000815181106125e7576125e7613400565b602002602001019063ffffffff16908163ffffffff168152505060008160018151811061261657612616613400565b602002602001019063ffffffff16908163ffffffff1681525050600080866001600160a01b031663883bdbfd846040518263ffffffff1660e01b815260040161265f9190613416565b600060405180830381865afa15801561267c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526126a49190810190613529565b915091506000826000815181106126bd576126bd613400565b6020026020010151836001815181106126d8576126d8613400565b60200260200101516126ea91906135ec565b905060008260008151811061270157612701613400565b60200260200101518360018151811061271c5761271c613400565b602002602001015161272e9190613619565b905063ffffffff88166127418184613639565b975060008360060b128015612761575061275b8184613677565b60060b15155b15612774578761277081613699565b9850505b63ffffffff8916640100000000600160c01b03602084901b1661279e6001600160a01b03836136bc565b6127a891906136ee565b9750505050505050509250929050565b60008060008360020b126127cf578260020b6127dc565b8260020b6127dc90613714565b90506127eb620d89e719613730565b60020b8111156128215760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610305565b60008160011660000361283857600160801b61284a565b6ffffcb933bd6fad37aa2d162d1a5940015b6001600160881b03169050600282161561287f57608061287a826ffff97272373d413259a46990580e213a612fdf565b901c90505b60048216156128a95760806128a4826ffff2e50f5f656932ef12357cf3c7fdcc612fdf565b901c90505b60088216156128d35760806128ce826fffe5caca7e10e4e61c3624eaa0941cd0612fdf565b901c90505b60108216156128fd5760806128f8826fffcb9843d60f6159c9db58835c926644612fdf565b901c90505b6020821615612927576080612922826fff973b41fa98c081472e6896dfb254c0612fdf565b901c90505b604082161561295157608061294c826fff2ea16466c96a3843ec78b326b52861612fdf565b901c90505b608082161561297b576080612976826ffe5dee046a99a2a811c461f1969c3053612fdf565b901c90505b6101008216156129a65760806129a1826ffcbe86c7900a88aedcffc83b479aa3a4612fdf565b901c90505b6102008216156129d15760806129cc826ff987a7253ac413176f2b074cf7815e54612fdf565b901c90505b6104008216156129fc5760806129f7826ff3392b0822b70005940c7a398e4b70f3612fdf565b901c90505b610800821615612a27576080612a22826fe7159475a2c29b7443b29c7fa6e889d9612fdf565b901c90505b611000821615612a52576080612a4d826fd097f3bdfd2022b8845ad8f792aa5825612fdf565b901c90505b612000821615612a7d576080612a78826fa9f746462d870fdf8a65dc1f90e061e5612fdf565b901c90505b614000821615612aa8576080612aa3826f70d869a156d2a1b890bb3df62baf32f7612fdf565b901c90505b618000821615612ad3576080612ace826f31be135f97d08fd981231505542fcfa6612fdf565b901c90505b62010000821615612aff576080612afa826f09aa508b5b7a84e1c677de54f3e99bc9612fdf565b901c90505b62020000821615612b2a576080612b25826e5d6af8dedb81196699c329225ee604612fdf565b901c90505b62040000821615612b54576080612b4f826d2216e584f5fa1ea926041bedfe98612fdf565b901c90505b62080000821615612b7c576080612b77826b048a170391f7dc42444e8fa2612fdf565b901c90505b60008460020b1315612b9757612b948160001961300c565b90505b612ba664010000000082613752565b15612bb2576001612bb5565b60005b6108569060ff16602083901c613033565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052612c178482612d73565b611c82576040516001600160a01b03848116602483015260006044830152612c4c91869182169063095ea7b390606401612389565b611c828482612d10565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6003546000908190819081906001600160a01b031673f19308f923582a6f7c465e5ce7a9dc1bec6665b1808210612cde578082612ce1565b81815b90965094506001600160a01b0380871690831614612d00578787612d03565b86885b9699959850965050505050565b6000612d256001600160a01b03841683612e16565b90508051600014158015612d4a575080806020019051810190612d489190613766565b155b15611d1f57604051635274afe760e01b81526001600160a01b0384166004820152602401610305565b6000806000846001600160a01b031684604051612d909190613781565b6000604051808303816000865af19150503d8060008114612dcd576040519150601f19603f3d011682016040523d82523d6000602084013e612dd2565b606091505b5091509150818015612dfc575080511580612dfc575080806020019051810190612dfc9190613766565b8015611a395750505050506001600160a01b03163b151590565b60606118868383600084600080856001600160a01b03168486604051612e3c9190613781565b60006040518083038185875af1925050503d8060008114612e79576040519150601f19603f3d011682016040523d82523d6000602084013e612e7e565b606091505b509150915061168c868383606082612e9e57612e9982612ee5565b611886565b8151158015612eb557506001600160a01b0384163b155b15612ede57604051639996b31560e01b81526001600160a01b0385166004820152602401610305565b5080611886565b805115612ef55780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b600060208284031215612f2057600080fd5b5035919050565b6001600160a01b0381168114610f2e57600080fd5b600060208284031215612f4e57600080fd5b813561188681612f27565b63ffffffff81168114610f2e57600080fd5b600060208284031215612f7d57600080fd5b813561188681612f59565b634e487b7160e01b600052601160045260246000fd5b63ffffffff818116838216028082169190828114612fbe57612fbe612f88565b505092915050565b600060208284031215612fd857600080fd5b5051919050565b80820281158282048414176108dd576108dd612f88565b634e487b7160e01b600052601260045260246000fd5b60008261301b5761301b612ff6565b500490565b818103818111156108dd576108dd612f88565b808201808211156108dd576108dd612f88565b60005b83811015613061578181015183820152602001613049565b50506000910152565b602081526000825160a0602084015280518060c08501526130928160e0860160208501613046565b60018060a01b0360208601511660408501526040850151606085015260608501516080850152608085015160a085015260e0601f19601f8301168501019250505092915050565b805161ffff811681146130eb57600080fd5b919050565b805180151581146130eb57600080fd5b600080600080600080600060e0888a03121561311b57600080fd5b875161312681612f27565b8097505060208801518060020b811461313e57600080fd5b955061314c604089016130d9565b945061315a606089016130d9565b9350613168608089016130d9565b925060a088015160ff8116811461317e57600080fd5b915061318c60c089016130f0565b905092959891949750929550565b6000602082840312156131ac57600080fd5b815161188681612f27565b81516001600160a01b03168152610160810160208301516131e360208401826001600160a01b03169052565b5060408301516131fa604084018262ffffff169052565b50606083015161320f606084018260020b9052565b506080830151613224608084018260020b9052565b5060a083015160a083015260c083015160c083015260e083015160e08301526101008084015181840152506101208084015161326a828501826001600160a01b03169052565b505061014092830151919092015290565b80516001600160801b03811681146130eb57600080fd5b600080600080608085870312156132a857600080fd5b845193506132b86020860161327b565b6040860151606090960151949790965092505050565b600080604083850312156132e157600080fd5b505080516020909101519092909150565b60008060006060848603121561330757600080fd5b6133108461327b565b925060208401519150604084015190509250925092565b61ffff818116838216019080821115611a3d57611a3d612f88565b600061ffff8084168061335757613357612ff6565b92169190910692915050565b8051600681900b81146130eb57600080fd5b6000806000806080858703121561338b57600080fd5b845161339681612f59565b93506133a460208601613363565b925060408501516133b481612f27565b91506133c2606086016130f0565b905092959194509250565b63ffffffff828116828216039080821115611a3d57611a3d612f88565b634e487b7160e01b600052604160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b6020808252825182820181905260009190848201906040850190845b8181101561345457835163ffffffff1683529284019291840191600101613432565b50909695505050505050565b604051601f8201601f1916810167ffffffffffffffff81118282101715613489576134896133ea565b604052919050565b600067ffffffffffffffff8211156134ab576134ab6133ea565b5060051b60200190565b600082601f8301126134c657600080fd5b815160206134db6134d683613491565b613460565b82815260059290921b840181019181810190868411156134fa57600080fd5b8286015b8481101561351e57805161351181612f27565b83529183019183016134fe565b509695505050505050565b6000806040838503121561353c57600080fd5b825167ffffffffffffffff8082111561355457600080fd5b818501915085601f83011261356857600080fd5b815160206135786134d683613491565b82815260059290921b8401810191818101908984111561359757600080fd5b948201945b838610156135bc576135ad86613363565b8252948201949082019061359c565b918801519196509093505050808211156135d557600080fd5b506135e2858286016134b5565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156108dd576108dd612f88565b6001600160a01b03828116828216039080821115611a3d57611a3d612f88565b60008160060b8360060b8061365057613650612ff6565b667fffffffffffff1982146000198214161561366e5761366e612f88565b90059392505050565b60008260060b8061368a5761368a612ff6565b808360060b0791505092915050565b60008160020b627fffff1981036136b2576136b2612f88565b6000190192915050565b6001600160c01b038281168282168181028316929181158285048214176136e5576136e5612f88565b50505092915050565b60006001600160c01b038381168061370857613708612ff6565b92169190910492915050565b6000600160ff1b820161372957613729612f88565b5060000390565b60008160020b627fffff19810361374957613749612f88565b60000392915050565b60008261376157613761612ff6565b500690565b60006020828403121561377857600080fd5b611886826130f0565b60008251613793818460208701613046565b919091019291505056fea2646970667358221220044a58ce7c0249b80cfd53e7cc0cf6bd0ce79009acfa48447f3638cd447393d464736f6c63430008140033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 35 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|---|---|---|---|---|
ETH | 100.00% | <$0.000001 | 897,719,330.9555 | $150.77 |
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.