Skip to content
Verified contractPartialMIT

AuctionUpgradeable

Address0xca8bcd94a353ebb566ff33d470a6865fa81e23f0
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.17

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.17+commit.8df45f5f
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
london
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
18,552,784
Creation transaction
0x3ee66f425f…606ec38f89

27 files

contracts/core/AuctionUpgradeable.sol

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

import "@gnus.ai/contracts-upgradeable-diamond/contracts/interfaces/IERC20MetadataUpgradeable.sol";
import "@gnus.ai/contracts-upgradeable-diamond/contracts/interfaces/IERC20Upgradeable.sol";
import "@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@gnus.ai/contracts-upgradeable-diamond/contracts/interfaces/IERC1155Upgradeable.sol";
import "@gnus.ai/contracts-upgradeable-diamond/contracts/security/ReentrancyGuardUpgradeable.sol";
import "@gnus.ai/contracts-upgradeable-diamond/contracts/security/PausableUpgradeable.sol";

import "./AuctionStorage.sol";
import "./WaterTowerStorage.sol";

import "../utils/EIP2535Initializable.sol";
import "../libraries/FullMath.sol";
import "../libraries/Constants.sol";

import "../interfaces/IPriceOracleUpgradeable.sol";
import "../interfaces/IWaterTowerUpgradeable.sol";

/// @title Auction Market for whitelisted erc20 tokens and erc1155 tranche nft
/// @dev  Auction contract allows users sell allowed tokens, buy or bid the tokens with allowed bid tokens
///     1. owner allow sell tokens and bid token groups, and set auction fee
///     2. seller(auctioner) create auction
///     * seller should have enough balance for sell tokens (sell amount + auction fee)
///     3. buyer buy listed tokens immediately or bid with any price in a range
///     * buyer shuold have enough balance for bid tokens (price * buy amount)
///     4. anyone(buyer, seller, or any) close auction after end time

contract AuctionUpgradeable is
    EIP2535Initializable,
    ReentrancyGuardUpgradeable,
    PausableUpgradeable
{
    using AuctionStorage for AuctionStorage.Layout;
    using SafeERC20Upgradeable for IERC20Upgradeable;
    /// @dev errors
    error InsufficientFee();
    error InsufficientReserveAsset();
    error NoListTrancheZ();
    error NoTransferEther();
    error InvalidTrancheAuction();
    error InvalidAuctionAmount();
    error InvalidStartTime();
    error InvalidMinBidAmount();
    error InvalidFixedPrice();
    error InvalidEndPrice();
    error InvalidSellToken();
    error NoClosedAuction();
    error NoAuction();
    error InvalidAuction();
    error InactiveAuction();
    error NoAuctioneer();
    error NoIdleAuction();
    error InvalidPurchaseAmount();
    error InvalidIncrementBidPrice();
    error NoStoreWater();
    // bid and buy
    error LowBid();
    error OverPriceBid();
    error NoCancelBid();
    error ClaimedBid();
    error NoBidder();
    error SmallBidAmount();
    error InvalidBidToken();

    event AuctionCreated(
        AuctionSetting auctionSetting,
        address indexed seller,
        uint256 indexed auctionId
    );

    /// @notice Emitted by auction for buyNow
    /// @param buyer The address call buyNow
    /// @param amountIn Token amount paid by user to buy auctioning token
    /// @param amountOut Auctioning token amount that user received
    /// @param auctionId Id of auction list

    event AuctionBuy(
        address indexed buyer,
        uint256 amountIn,
        uint256 amountOut,
        address purchaseToken,
        uint256 indexed auctionId
    );

    /// @notice Emitted by auction when bidder places a bid
    /// @param bid Bid token struct
    /// @param auctionId The id of auction list
    /// @param bidId The id of bid list

    event AuctionBid(Bid bid, uint indexed auctionId, uint indexed bidId, uint availableBidDepth);

    /// @notice Emitted by auction when bidder or auctioneer closes a auction
    /// @param unSoldAmount Amount of unsold auctioning token
    /// @param auctionId Auction id
    /// @param settledBidCount Settled bid count when closing auction
    event AuctionClosed(uint256 unSoldAmount, uint256 indexed auctionId, uint256 settledBidCount);

    event AuctionUpdate(
        uint indexed auctionId,
        uint minBidAmount,
        uint priceRangeStart,
        uint incrementPrice
    );

    event ClaimBid(uint auctionId, uint bidId, bool isWinner, uint claimAmount);

    uint256 internal constant FEE_DENOMINATOR = 1e6;
    uint256 internal constant BID_GAS_LIMIT = 470000;
    uint256 internal constant CLOSE_GAS_LIMIT = 180000;
    uint256 internal constant D12 = 1e12;
    uint256 internal constant MINBID_FACTOR = 100;
    uint256 internal constant INCREMENTBID_FACTOR = 2;

    function createAuction(
        AuctionSetting memory auctionSetting,
        uint8 periodId
    ) external payable whenNotPaused {
        AuctionStorage.Layout storage auctionStorage = AuctionStorage.layout();
        if (!auctionStorage.supportedSellTokens[auctionSetting.sellToken])
            revert InvalidSellToken();
        if (auctionSetting.bidTokenGroupId >= auctionStorage.countOfTokenGroups)
            revert InvalidBidToken();
        if (
            auctionSetting.minBidAmount < auctionSetting.sellAmount / MINBID_FACTOR ||
            auctionSetting.minBidAmount > auctionSetting.sellAmount
        ) revert InvalidMinBidAmount();
        if (auctionSetting.sellAmount == 0) revert InvalidAuctionAmount();

        if (
            (auctionSetting.auctionType == AuctionType.FixedPrice ||
                auctionSetting.auctionType == AuctionType.TimedAndFixed) &&
            auctionSetting.fixedPrice == 0
        ) revert InvalidFixedPrice();
        uint256 priceForFee;
        if (auctionSetting.auctionType != AuctionType.FixedPrice) {
            if (auctionSetting.priceRangeStart > auctionSetting.priceRangeEnd)
                revert InvalidEndPrice();
            if (
                auctionSetting.incrementBidPrice == 0 ||
                auctionSetting.incrementBidPrice * INCREMENTBID_FACTOR >
                auctionSetting.priceRangeStart
            ) revert InvalidIncrementBidPrice();
            priceForFee = auctionSetting.priceRangeStart;
        } else {
            priceForFee = auctionSetting.fixedPrice;
        }

        if (auctionSetting.startTime == 0) auctionSetting.startTime = uint48(block.timestamp);
        else if (
            auctionSetting.startTime < block.timestamp ||
            auctionSetting.startTime > block.timestamp + 30 days
        ) revert InvalidStartTime();
        auctionSetting.endTime = auctionSetting.startTime + auctionStorage.periods[periodId];
        uint256 auctionId = auctionStorage.currentAuctionId + 1;
        uint256 tokenMultiplier;
        // receive auction asset
        if (auctionSetting.trancheIndex == 0) {
            IERC20Upgradeable(auctionSetting.sellToken).safeTransferFrom(
                msg.sender,
                address(this),
                auctionSetting.sellAmount
            );
            tokenMultiplier = (10 **
                (18 - IERC20MetadataUpgradeable(auctionSetting.sellToken).decimals()));
        } else {
            if (auctionSetting.trancheIndex & 3 == 3) revert NoListTrancheZ();
            if (auctionSetting.sellToken != address(this)) revert InvalidTrancheAuction();
            IERC1155Upgradeable(address(this)).safeTransferFrom(
                msg.sender,
                address(this),
                auctionSetting.trancheIndex,
                auctionSetting.sellAmount,
                Constants.EMPTY
            );
            // tranche nft decimals is 6 and ether decimals is 18, so calculated factor = 10 ** (18-6)
            tokenMultiplier = D12;
        }
        (uint256 feeAmount, uint256 lockedLevel) = lockWater(
            msg.sender,
            auctionSetting.sellAmount,
            tokenMultiplier,
            priceForFee
        );
        if (feeAmount > 0) {
            if (msg.value < feeAmount) revert InsufficientFee();
            else if (msg.value > feeAmount) {
                (bool success, ) = msg.sender.call{value: msg.value - feeAmount}("");
                if (!success) revert NoTransferEther();
            }
            uint256 ethReward = (feeAmount * auctionStorage.feeForTower) / FEE_DENOMINATOR;
            auctionStorage.reserveFees[Constants.ETHER] += (feeAmount - ethReward);
            IWaterTowerUpgradeable(address(this)).addETHReward{value: ethReward}();
        }
        auctionStorage.currentAuctionId = auctionId;
        auctionSetting.reserve = auctionSetting.sellAmount;
        auctionStorage.auctions[auctionId].s = auctionSetting;
        auctionStorage.auctions[auctionId].seller = msg.sender;
        auctionStorage.auctions[auctionId].lockedLevel = lockedLevel;
        emit AuctionCreated(auctionSetting, msg.sender, auctionId);
    }

    /// @notice update important options of auction before any bidding
    /// @param auctionId auction id
    /// @param minBidAmount min bid amount to update
    /// @param priceRangeStart start price
    /// @param incrementBidPrice increment bid price
    function updateAuction(
        uint256 auctionId,
        uint128 minBidAmount,
        uint128 priceRangeStart,
        uint128 incrementBidPrice
    ) external whenNotPaused {
        AuctionStorage.Layout storage auctionStorage = AuctionStorage.layout();
        AuctionData memory auction = auctionStorage.auctions[auctionId];
        if (auction.seller != msg.sender) revert NoAuctioneer();
        if (
            auction.status != AuctionStatus.Open ||
            auction.s.endTime < block.timestamp ||
            auction.curBidId != 0
        ) revert NoIdleAuction();

        if (priceRangeStart > auction.s.priceRangeEnd) revert InvalidEndPrice();

        if (
            minBidAmount >= auction.s.sellAmount / MINBID_FACTOR &&
            minBidAmount <= auction.s.sellAmount
        ) auctionStorage.auctions[auctionId].s.minBidAmount = minBidAmount;

        if (priceRangeStart != 0)
            auctionStorage.auctions[auctionId].s.priceRangeStart = priceRangeStart;
        if (
            incrementBidPrice != 0 &&
            incrementBidPrice * INCREMENTBID_FACTOR <=
            auctionStorage.auctions[auctionId].s.priceRangeStart
        ) auctionStorage.auctions[auctionId].s.incrementBidPrice = incrementBidPrice;

        emit AuctionUpdate(auctionId, minBidAmount, priceRangeStart, incrementBidPrice);
    }

    /// @notice buy token immediately with fixed price
    /// @param auctionId      auction id
    /// @param purchaseAmount amount to purchase
    /// @param buyTokenId     token id to buy with
    function buyNow(
        uint256 auctionId,
        uint128 purchaseAmount,
        uint16 buyTokenId
    ) external nonReentrant whenNotPaused {
        AuctionStorage.Layout storage auctionStorage = AuctionStorage.layout();
        AuctionData memory auction = auctionStorage.auctions[auctionId];
        // Check auction.seller if address(0) auction hasn't been initialized/created and then check the auction type.
        if (auction.seller == address(0) || auction.s.auctionType == AuctionType.TimedAuction)
            revert InvalidAuction();
        address _purchaseToken = AuctionStorage
            .layout()
            .bidTokenGroups[auction.s.bidTokenGroupId]
            .bidTokens[buyTokenId];
        checkAuctionInProgress(auction.s.endTime, auction.s.startTime);
        uint128 availableAmount = auction.s.reserve;
        uint256 trancheIndex = auction.s.trancheIndex;
        if (purchaseAmount > availableAmount) revert InsufficientReserveAsset();
        if (auction.s.minBidAmount > purchaseAmount) revert SmallBidAmount();

        unchecked {
            auctionStorage.auctions[auctionId].s.reserve = availableAmount - purchaseAmount;
        }
        uint8 sellTokenDecimals;
        if (trancheIndex == 0) {
            sellTokenDecimals = IERC20MetadataUpgradeable(auction.s.sellToken).decimals();
            IERC20Upgradeable(auction.s.sellToken).safeTransfer(msg.sender, purchaseAmount);
        } else {
            sellTokenDecimals = Constants.TRANCHE_DECIMALS;
            IERC1155Upgradeable(address(this)).safeTransferFrom(
                address(this),
                msg.sender,
                trancheIndex,
                purchaseAmount,
                Constants.EMPTY
            );
        }
        uint256 payAmount = getPayAmount(
            _purchaseToken,
            purchaseAmount,
            auction.s.fixedPrice,
            sellTokenDecimals
        );
        uint256 fee = (payAmount * auctionStorage.fee.successFees[auction.lockedLevel]) /
            FEE_DENOMINATOR;
        IERC20Upgradeable(_purchaseToken).safeTransferFrom(
            msg.sender,
            auction.seller,
            payAmount - fee
        );
        IERC20Upgradeable(_purchaseToken).safeTransferFrom(msg.sender, address(this), fee);
        auctionStorage.reserveFees[_purchaseToken] += fee;
        emit AuctionBuy(msg.sender, payAmount, purchaseAmount, _purchaseToken, auctionId);
    }

    function placeBid(
        uint256 auctionId,
        uint128 bidAmount,
        uint16 bidTokenId,
        uint128 bidPrice,
        uint128 maxBidPrice
    ) external nonReentrant whenNotPaused returns (uint256) {
        AuctionStorage.Layout storage auctionStorage = AuctionStorage.layout();
        AuctionData memory auction = auctionStorage.auctions[auctionId];
        if (auction.seller == address(0) || auction.s.auctionType == AuctionType.FixedPrice)
            revert InvalidAuction();
        address _purchaseToken = AuctionStorage
            .layout()
            .bidTokenGroups[auction.s.bidTokenGroupId]
            .bidTokens[bidTokenId];
        checkAuctionInProgress(auction.s.endTime, auction.s.startTime);
        if (auction.s.minBidAmount > bidAmount) revert SmallBidAmount();
        if (bidAmount > auction.s.reserve) revert InsufficientReserveAsset();
        // bid price starts from priceRangeStart
        uint128 availableBidPrice = auction.curBidId == 0
            ? auction.s.priceRangeStart
            : auctionStorage.bids[auctionId][auction.curBidId].bidPrice +
                auction.s.incrementBidPrice;
        // if bidPrice is 0, place bid in increment way
        if (bidPrice == 0) bidPrice = availableBidPrice;
        else if (bidPrice < availableBidPrice) revert LowBid();
        if (bidPrice > maxBidPrice) revert OverPriceBid();
        uint128 _bidPrice = bidPrice;
        uint256 payAmount = getPayAmount(
            _purchaseToken,
            bidAmount,
            _bidPrice,
            auction.s.trancheIndex > 0
                ? 6
                : IERC20MetadataUpgradeable(auction.s.sellToken).decimals()
        );
        IERC20Upgradeable(_purchaseToken).safeTransferFrom(msg.sender, address(this), payAmount);
        Bid memory bid = Bid({
            bidder: msg.sender,
            bidAmount: bidAmount,
            bidPrice: _bidPrice,
            paidAmount: uint128(payAmount),
            bidTokenId: bidTokenId,
            bCleared: false
        });
        uint128 currentBidId = auction.curBidId + 1;
        {
            uint256 gasRemaining = gasleft();
            uint256 _auctionId = auctionId;
            uint128 _bidAmount = bidAmount;
            auctionStorage.bids[_auctionId][currentBidId] = bid;
            uint256 availableBidDepth = uint256(auction.availableBidDepth) + 1;
            uint128 totalBidAmount = auction.totalBidAmount + _bidAmount;
            address[] memory bidTokens = AuctionStorage
                .layout()
                .bidTokenGroups[auction.s.bidTokenGroupId]
                .bidTokens;
            // cancel bids not eligible in a range of gas limit
            while (true) {
                uint256 _cancelBidId = currentBidId - availableBidDepth + 1;
                Bid memory cancelBid = auctionStorage.bids[_auctionId][_cancelBidId];
                // even though reserve sell amount is smaller than bidAmount, settle the bid and the bidder receives sell token as possible
                if (totalBidAmount < auction.s.reserve + cancelBid.bidAmount) break;
                unchecked {
                    totalBidAmount -= cancelBid.bidAmount;
                    availableBidDepth--;
                }
                /// cancel not eligible bids
                if (cancelBid.bCleared) revert NoCancelBid();
                IERC20Upgradeable(bidTokens[cancelBid.bidTokenId]).safeTransfer(
                    cancelBid.bidder,
                    cancelBid.paidAmount
                );
                AuctionStorage.layout().bids[_auctionId][_cancelBidId].bCleared = true;
                if (gasRemaining - gasleft() > BID_GAS_LIMIT) break;
            }
            AuctionStorage.layout().auctions[_auctionId].availableBidDepth = uint8(
                availableBidDepth
            );
            AuctionStorage.layout().auctions[_auctionId].totalBidAmount = totalBidAmount;
            AuctionStorage.layout().auctions[_auctionId].curBidId = currentBidId;
            emit AuctionBid(bid, _auctionId, currentBidId, availableBidDepth);
        }
        return currentBidId;
    }

    function closeAuction(uint256 auctionId) external nonReentrant whenNotPaused {
        AuctionData memory auction = AuctionStorage.layout().auctions[auctionId];
        require(
            block.timestamp >= auction.s.endTime && auction.status != AuctionStatus.Closed,
            "auction can't be closed"
        );
        _settleAuction(auctionId, auction);
    }

    /// @notice function to get status of bid
    /// @param auctionId auction id
    /// @param bidId  bid id
    /// @return isWinner true if the bid is winner
    /// @return isClaimed true if the bid was claimed

    function isWinnerBid(
        uint256 auctionId,
        uint256 bidId
    ) external view returns (bool isWinner, bool isClaimed, uint256 claimAmount) {
        AuctionStorage.Layout storage auctionStorage = AuctionStorage.layout();
        AuctionData memory auction = auctionStorage.auctions[auctionId];
        Bid memory bid = auctionStorage.bids[auctionId][bidId];
        return _isWinnerBid(auctionId, bidId, auction, bid);
    }

    /// @notice claim bid for winner or canceled bid after auction is closed
    /// @dev anyone can claim bid
    function claimBid(uint256 auctionId, uint256 bidId) external nonReentrant whenNotPaused {
        AuctionStorage.Layout storage auctionStorage = AuctionStorage.layout();
        AuctionData memory auction = auctionStorage.auctions[auctionId];
        Bid memory bid = auctionStorage.bids[auctionId][bidId];
        (bool isWinner, bool isClaimed, uint256 claimAmount) = _isWinnerBid(
            auctionId,
            bidId,
            auction,
            bid
        );
        if (isClaimed) revert ClaimedBid();
        auctionStorage.bids[auctionId][bidId].bCleared = true;
        if (auction.status != AuctionStatus.Closed) revert NoClosedAuction();
        IERC20Upgradeable _purchaseToken = IERC20Upgradeable(
            auctionStorage.bidTokenGroups[auction.s.bidTokenGroupId].bidTokens[bid.bidTokenId]
        );
        if (isWinner) {
            auctionStorage.auctions[auctionId].s.reserve = auction.s.reserve - uint128(claimAmount);
            _settleBid(
                auction.s.sellToken,
                auction.s.trancheIndex,
                _purchaseToken,
                bid,
                uint128(claimAmount)
            );
        } else {
            _purchaseToken.safeTransfer(bid.bidder, bid.paidAmount);
        }
        emit ClaimBid(auctionId, bidId, isWinner, claimAmount);
    }

    function _settleAuction(uint256 auctionId, AuctionData memory auction) internal {
        uint256 gasLimit = gasleft();
        uint128 availableAmount = auction.s.reserve;
        uint256 settledBidCount;
        uint256 curBidId = auction.curBidId;
        AuctionStorage.Layout storage auctionStorage = AuctionStorage.layout();
        address[] memory bidTokens = auctionStorage
            .bidTokenGroups[auction.s.bidTokenGroupId]
            .bidTokens;
        uint256[] memory payoutAmounts = new uint256[](bidTokens.length);
        bool bOverGasLimit = false;
        uint128 reserve = availableAmount;
        while (curBidId > 0 && reserve > 0) {
            Bid memory bid = auctionStorage.bids[auctionId][curBidId];
            if (bid.bCleared) break;
            if (!bOverGasLimit && gasLimit <= gasleft() + CLOSE_GAS_LIMIT) {
                auctionStorage.bids[auctionId][curBidId].bCleared = true;
                (uint128 settledAmount, uint128 payoutAmount) = _settleBid(
                    auction.s.sellToken,
                    auction.s.trancheIndex,
                    IERC20Upgradeable(bidTokens[bid.bidTokenId]),
                    bid,
                    availableAmount
                );
                payoutAmounts[bid.bidTokenId] += payoutAmount;
                unchecked {
                    availableAmount -= settledAmount;
                    reserve -= settledAmount;
                    ++settledBidCount;
                }
            } else {
                // it allows the calculation for gas limit done only one time
                if (!bOverGasLimit) bOverGasLimit = true;
                if (bid.bidAmount > reserve) {
                    payoutAmounts[bid.bidTokenId] += (bid.paidAmount * reserve) / bid.bidAmount;
                    reserve = 0;
                } else {
                    payoutAmounts[bid.bidTokenId] += bid.paidAmount;
                    unchecked {
                        reserve -= bid.bidAmount;
                    }
                }
            }
            unchecked {
                --curBidId;
            }
        }
        // transfer paid tokens from contract to seller
        // unclock locked water
        uint256 realPayPecentage = FEE_DENOMINATOR -
            unlockWater(auction.seller, auction.lockedLevel);
        for (uint256 i; i < bidTokens.length; ) {
            uint256 payoutAmount = payoutAmounts[i];
            if (payoutAmount > 0) {
                address _purchaseToken = bidTokens[i];
                uint256 realPayAmount = (payoutAmount * realPayPecentage) / FEE_DENOMINATOR;
                IERC20Upgradeable(bidTokens[i]).safeTransfer(auction.seller, realPayAmount);
                unchecked {
                    auctionStorage.reserveFees[_purchaseToken] += (payoutAmount - realPayAmount);
                }
            }
            unchecked {
                ++i;
            }
        }

        // refund unsold tokens
        if (reserve > 0) {
            unchecked {
                availableAmount -= reserve;
            }
            if (auction.s.trancheIndex == 0) {
                IERC20Upgradeable(auction.s.sellToken).safeTransfer(auction.seller, reserve);
            } else {
                IERC1155Upgradeable(address(this)).safeTransferFrom(
                    address(this),
                    auction.seller,
                    auction.s.trancheIndex,
                    reserve,
                    Constants.EMPTY
                );
            }
        }

        auctionStorage.auctions[auctionId].s.reserve = availableAmount;
        auctionStorage.auctions[auctionId].status = AuctionStatus.Closed;

        unchecked {
            auctionStorage.auctions[auctionId].totalBidAmount =
                auction.totalBidAmount -
                availableAmount;
            auctionStorage.auctions[auctionId].curBidId =
                auction.curBidId -
                uint128(settledBidCount);
        }
        emit AuctionClosed(availableAmount, auctionId, settledBidCount);
    }

    /// @notice transfer auctioning token to bidder
    function _settleBid(
        address sellToken,
        uint256 trancheIndex,
        IERC20Upgradeable _purchaseToken,
        Bid memory bid,
        uint128 availableAmount
    ) internal returns (uint128 settledAmount, uint128 payoutAmount) {
        settledAmount = bid.bidAmount;
        payoutAmount = bid.paidAmount;
        if (availableAmount < settledAmount) {
            uint128 repayAmount;
            unchecked {
                repayAmount = settledAmount - availableAmount;
            }
            // calculate as payout token
            repayAmount = (repayAmount * bid.paidAmount) / bid.bidAmount;
            payoutAmount -= repayAmount;
            settledAmount = availableAmount;
            _purchaseToken.safeTransfer(bid.bidder, repayAmount);
        }
        if (trancheIndex == 0) {
            IERC20Upgradeable(sellToken).safeTransfer(bid.bidder, settledAmount);
        } else {
            IERC1155Upgradeable(address(this)).safeTransferFrom(
                address(this),
                bid.bidder,
                trancheIndex,
                settledAmount,
                Constants.EMPTY
            );
        }
    }

    function _isWinnerBid(
        uint256 auctionId,
        uint256 bidId,
        AuctionData memory auction,
        Bid memory bid
    ) internal view returns (bool isWinner, bool isClaimed, uint256 claimAmount) {
        AuctionStorage.Layout storage auctionStorage = AuctionStorage.layout();
        if (bid.bCleared) isClaimed = true;
        if (auction.status != AuctionStatus.Closed) {
            return (false, isClaimed, 0);
        } else {
            uint256 curBidId = auction.curBidId;
            uint256 reserve = auction.s.reserve;
            unchecked {
                while (curBidId > bidId && reserve > 0) {
                    Bid memory seniorBid = auctionStorage.bids[auctionId][curBidId];
                    if (!seniorBid.bCleared) {
                        if (reserve > seniorBid.bidAmount) {
                            reserve -= seniorBid.bidAmount;
                        } else reserve = 0;
                    }
                    --curBidId;
                }
                if (reserve > 0) {
                    return (
                        true,
                        isClaimed,
                        reserve >= bid.bidAmount ? bid.bidAmount : bid.bidAmount - reserve
                    );
                } else return (false, isClaimed, 0);
            }
        }
    }

    // admin setters are implemented in IrrigationControl

    // getters
    function getPayAmount(
        address purchaseToken,
        uint128 purchaseAmount,
        uint128 price,
        uint8 sellTokenDecimals
    ) public view returns (uint256) {
        uint256 denominator = (10 **
            (18 - IERC20MetadataUpgradeable(purchaseToken).decimals() + sellTokenDecimals));
        return FullMath.mulDivRoundingUp128(purchaseAmount, price, denominator);
    }

    function getAuction(uint256 auctionId) external view returns (AuctionData memory) {
        return AuctionStorage.layout().auctions[auctionId];
    }

    function getBid(uint256 auctionId, uint256 bidId) external view returns (Bid memory) {
        return AuctionStorage.layout().bids[auctionId][bidId];
    }

    function getAuctionsCount() external view returns (uint256 totalAuctionsCount) {
        return AuctionStorage.layout().currentAuctionId;
    }

    function getBidTokenGroup(
        uint256 tokenGroupId
    ) external view returns (BidTokenGroup memory tokenGroup) {
        return AuctionStorage.layout().bidTokenGroups[tokenGroupId];
    }

    function getBidTokenGroupCount() external view returns (uint256 countOfTokenGroup) {
        return AuctionStorage.layout().countOfTokenGroups;
    }

    function getAuctionPeriods() external view returns (uint48[] memory) {
        return AuctionStorage.layout().periods;
    }

    /// @dev returns true if auction in progress, false otherwise
    function checkAuctionInProgress(uint256 endTime, uint256 startTime) internal view {
        if (startTime > block.timestamp || (endTime > 0 && endTime <= block.timestamp))
            revert InactiveAuction();
    }

    function getListingFeeForUser(
        address user,
        uint256 amount,
        uint256 multiplier,
        uint256 tokenPrice
    ) external view returns (uint256 feeAmount) {
        (uint256 listingFee, , , ) = getAuctionFeeAndLimit(WaterTowerStorage.userInfo(user).amount);
        feeAmount = getListingFee(listingFee, amount, multiplier, tokenPrice);
    }

    /// @notice returns fee level, fee amount, listing fee and closing fee numerator for water amount
    function getAuctionFeeAndLimit(
        uint256 waterAmount
    )
        public
        view
        returns (uint256 listingFee, uint256 successFee, uint256 feeLevel, uint256 limit)
    {
        AuctionFee memory fee = AuctionStorage.layout().fee;
        uint256 i;
        for (i; i < fee.limits.length - 1; ) {
            if (waterAmount < fee.limits[i + 1])
                return (fee.listingFees[i], fee.successFees[i], i, fee.limits[i]);
            unchecked {
                ++i;
            }
        }
        return (fee.listingFees[i], fee.successFees[i], i, fee.limits[i]);
    }

    /// @notice return listing fee amount for amount and fee percentage
    function getListingFee(
        uint256 listingFee,
        uint256 auctionAmount,
        uint256 multiplier,
        uint256 tokenPrice
    ) internal view returns (uint256 feeEthAmount) {
        /// @dev fee is calulated with ether price, auction price, and auction amount
        uint256 ethPrice = IPriceOracleUpgradeable(address(this)).getUnderlyingPriceETH();
        return
            (((auctionAmount * multiplier * listingFee * tokenPrice) / ethPrice)) / FEE_DENOMINATOR;
    }

    // lock water for fee level and return listing fee amount
    // called when creating auction
    function lockWater(
        address user,
        uint256 auctionAmount,
        uint256 multiplier,
        uint256 tokenPrice
    ) internal returns (uint256 fee, uint256 lockedLevel) {
        WaterTowerStorage.Layout storage wl = WaterTowerStorage.layout();
        uint256 userAmount = wl.users[user].amount;
        LockedUserInfo storage lockedInfo = wl.lockedUsers[user];
        (uint256 listingFee, , uint256 feeLevel, uint256 amountToLock) = getAuctionFeeAndLimit(
            userAmount
        );
        /// @dev fee is calulated with ether price, auction price, and auction amount
        fee = getListingFee(listingFee, auctionAmount, multiplier, tokenPrice);
        if (amountToLock != 0) {
            lockedInfo.lockedCounts[feeLevel] = lockedInfo.lockedCounts[feeLevel] + 1;
            if (lockedInfo.lockedAmount < amountToLock) lockedInfo.lockedAmount = amountToLock;
        }
        return (fee, feeLevel);
    }

    function unlockWater(
        address user,
        uint256 lockedLevelForAuction
    ) internal returns (uint256 successFee) {
        // WaterTowerStorage.Layout storage wl = WaterTowerStorage.layout();
        LockedUserInfo storage lockedInfo = WaterTowerStorage.layout().lockedUsers[user];
        AuctionFee memory fee = AuctionStorage.layout().fee;
        successFee = fee.successFees[lockedLevelForAuction];
        uint256 lockedForAuction = fee.limits[lockedLevelForAuction];
        if (lockedForAuction == 0) return successFee;
        uint256 lockedCount = lockedInfo.lockedCounts[lockedLevelForAuction] - 1;
        lockedInfo.lockedCounts[lockedLevelForAuction] = uint32(lockedCount);
        if (lockedCount == 0 && lockedInfo.lockedAmount == lockedForAuction) {
            if (lockedLevelForAuction >= 1) {
                // find locked min level
                for (uint256 i = lockedLevelForAuction - 1; i > 0; ) {
                    if (lockedInfo.lockedCounts[i] > 0) {
                       lockedInfo.lockedAmount = fee.limits[i];
                        return successFee;
                    }
                    unchecked {
                        --i;
                    }
                }
            }
            lockedInfo.lockedAmount = fee.limits[0];
        }
    }

    function getReserveFee(address token) external view returns (uint256 fee) {
        return AuctionStorage.layout().reserveFees[token];
    }
}

@gnus.ai/contracts-upgradeable-diamond/contracts/interfaces/IERC1155Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1155.sol)

pragma solidity ^0.8.0;

import "../token/ERC1155/IERC1155Upgradeable.sol";

@gnus.ai/contracts-upgradeable-diamond/contracts/interfaces/IERC20MetadataUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/extensions/IERC20MetadataUpgradeable.sol";

@gnus.ai/contracts-upgradeable-diamond/contracts/interfaces/IERC20Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20Upgradeable.sol";

@gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";
import { InitializableStorage } from "./InitializableStorage.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !InitializableStorage.layout()._initializing;
        require(
            (isTopLevelCall && InitializableStorage.layout()._initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && InitializableStorage.layout()._initialized == 1),
            "Initializable: contract is already initialized"
        );
        InitializableStorage.layout()._initialized = 1;
        if (isTopLevelCall) {
            InitializableStorage.layout()._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            InitializableStorage.layout()._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!InitializableStorage.layout()._initializing && InitializableStorage.layout()._initialized < version, "Initializable: contract is already initialized");
        InitializableStorage.layout()._initialized = version;
        InitializableStorage.layout()._initializing = true;
        _;
        InitializableStorage.layout()._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(InitializableStorage.layout()._initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!InitializableStorage.layout()._initializing, "Initializable: contract is initializing");
        if (InitializableStorage.layout()._initialized < type(uint8).max) {
            InitializableStorage.layout()._initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return InitializableStorage.layout()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return InitializableStorage.layout()._initializing;
    }
}

@gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/InitializableStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;


import { Initializable } from "./Initializable.sol";

library InitializableStorage {

  struct Layout {
    /*
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 _initialized;

    /*
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool _initializing;
  
  }
  
  bytes32 internal constant STORAGE_SLOT = keccak256('openzeppelin.contracts.storage.Initializable');

  function layout() internal pure returns (Layout storage l) {
    bytes32 slot = STORAGE_SLOT;
    assembly {
      l.slot := slot
    }
  }
}
    

@gnus.ai/contracts-upgradeable-diamond/contracts/security/PausableStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;


import { PausableUpgradeable } from "./PausableUpgradeable.sol";

library PausableStorage {

  struct Layout {

    bool _paused;
  
  }
  
  bytes32 internal constant STORAGE_SLOT = keccak256('openzeppelin.contracts.storage.Pausable');

  function layout() internal pure returns (Layout storage l) {
    bytes32 slot = STORAGE_SLOT;
    assembly {
      l.slot := slot
    }
  }
}
    

@gnus.ai/contracts-upgradeable-diamond/contracts/security/PausableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import { PausableStorage } from "./PausableStorage.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    using PausableStorage for PausableStorage.Layout;
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage.layout()._paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return PausableStorage.layout()._paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage.layout()._paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage.layout()._paused = false;
        emit Unpaused(_msgSender());
    }
}

@gnus.ai/contracts-upgradeable-diamond/contracts/security/ReentrancyGuardStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;


import { ReentrancyGuardUpgradeable } from "./ReentrancyGuardUpgradeable.sol";

library ReentrancyGuardStorage {

  struct Layout {

    uint256 _status;
  
  }
  
  bytes32 internal constant STORAGE_SLOT = keccak256('openzeppelin.contracts.storage.ReentrancyGuard');

  function layout() internal pure returns (Layout storage l) {
    bytes32 slot = STORAGE_SLOT;
    assembly {
      l.slot := slot
    }
  }
}
    

@gnus.ai/contracts-upgradeable-diamond/contracts/security/ReentrancyGuardUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;
import { ReentrancyGuardStorage } from "./ReentrancyGuardStorage.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @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 ReentrancyGuardUpgradeable is Initializable {
    using ReentrancyGuardStorage for ReentrancyGuardStorage.Layout;
    // 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;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage.layout()._status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(ReentrancyGuardStorage.layout()._status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        ReentrancyGuardStorage.layout()._status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        ReentrancyGuardStorage.layout()._status = _NOT_ENTERED;
    }
}

@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC1155/IERC1155Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165Upgradeable.sol";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155Upgradeable is IERC165Upgradeable {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}

@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC20/IERC20Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20Upgradeable {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC20/extensions/IERC20MetadataUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
    /**
     * @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);
}

@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @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.
 */
interface IERC20PermitUpgradeable {
    /**
     * @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].
     */
    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);
}

@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";
import "../extensions/draft-IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
    using AddressUpgradeable for address;

    function safeTransfer(
        IERC20Upgradeable token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20Upgradeable token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20Upgradeable token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20Upgradeable token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20Upgradeable token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    function safePermit(
        IERC20PermitUpgradeable token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @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(IERC20Upgradeable 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, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

@gnus.ai/contracts-upgradeable-diamond/contracts/utils/AddressUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }


    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

@gnus.ai/contracts-upgradeable-diamond/contracts/utils/ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

@gnus.ai/contracts-upgradeable-diamond/contracts/utils/introspection/IERC165Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @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 IERC165Upgradeable {
    /**
     * @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);
}

contracts/core/AuctionStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

enum AuctionType {
    TimedAuction,
    FixedPrice,
    TimedAndFixed
}

enum AuctionStatus {
    Open,
    Closed
}

struct Bid {
    uint128 bidAmount;
    uint128 bidPrice;
    address bidder;
    // bid token amount paid out when bidding
    uint128 paidAmount;
    uint16 bidTokenId;
    bool bCleared;
}

struct BidTokenGroup {
    // tokens in one group should be max 255
    address[] bidTokens;
    // calculated price by this address
    address basePriceToken;
    bytes32 name;
}

struct AuctionSetting {
    // start and expired time
    uint48 startTime;
    uint48 endTime;
    // listed token address
    address sellToken;
    // tranche id for tranche nft auction
    uint256 trancheIndex;
    // minimum bid or buy amount
    uint128 minBidAmount;
    // fixed price used when buying directly, without bidding
    uint128 fixedPrice;
    // lowest and highest bid price
    uint128 priceRangeStart;
    uint128 priceRangeEnd;
    // total amount of listed token
    uint128 sellAmount;
    // while auction is open, available token amount
    uint128 reserve;
    // price used when bidding in increment way
    uint128 incrementBidPrice;
    // bid token group id
    uint16 bidTokenGroupId;
    // auction type
    AuctionType auctionType;
}
/// @dev Contains all data for erc20 or tranche auction
struct AuctionData {
    // config params set by autioneer
    AuctionSetting s;
    // current bid id
    uint128 curBidId;
    // total amount of bids that can win after auction is closed
    uint128 totalBidAmount;
    // seller address
    address seller;
    // number of bids that can win after auction is closed. all bids out the range of availableBidDepth are canceled when bidding.
    uint8 availableBidDepth;
    // auction status
    AuctionStatus status;
    // updated upgrade 002
    // locked user level 
    uint256 lockedLevel;
}
/// @dev Auction Fee
struct AuctionFee {
    // fee when creating auction. 1 => 0.1%
    uint32[] listingFees;
    // fee percentage for buying and settled bids when closing auction
    uint32[] successFees;
    // stored water amount list
    uint256[] limits;
}

library AuctionStorage {
    struct Layout {
        // count of auctions and current auction id
        uint256 currentAuctionId;
        // all auctions by auction id
        mapping(uint256 => AuctionData) auctions;
        // all bids by auction id and bid id
        mapping(uint256 => mapping(uint256 => Bid)) bids;
        // whitelist for sell tokens
        mapping(address => bool) supportedSellTokens;
        // bid token groups
        mapping(uint256 => BidTokenGroup) bidTokenGroups;
        // count of bid token groups
        uint256 countOfTokenGroups;
        // fee amount and fee receiver address // deprecated
        uint256 feeNumerator;
        address feeReceiver;
        // deprecated
        uint96 maxIncrementRate;
        // available auction periods like 1 day, 3 days,
        uint48[] periods;
        // added upgrade 002
        // listing fees and success fees
        AuctionFee fee;
        // reserve auction fees in contract
        mapping(address => uint256) reserveFees;
        // factor fee to add water tower eth reward
        uint256 feeForTower;
    }

    bytes32 internal constant STORAGE_SLOT = keccak256("irrigation.contracts.storage.Auction");

    function layout() internal pure returns (Layout storage ls) {
        bytes32 slot = STORAGE_SLOT;
        assembly {
            ls.slot := slot
        }
    }
}

contracts/core/WaterTowerStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

import {IERC20Upgradeable} from "@gnus.ai/contracts-upgradeable-diamond/contracts/token/ERC20/IERC20Upgradeable.sol";

/// @notice User Setting Info
struct UserInfo {
    bool isAutoIrrigate;
    // last poolIndex that user interact
    uint256 lastPoolIndex;
    // total claimable reward of user
    uint256 pending;
    // reward rate in this month = sum (block time * amount)
    uint256 rewardRate;
    // deposited water amount
    uint256 amount;
}

struct PoolInfo {
    // sum of all user reward rate in this month
    uint256 totalRewardRate;
    uint256 monthlyRewards;
    uint128 endTime;
    uint128 startTime;
}

struct UserPoolHistory {
    // total user reward rate = sum(staked time * staked amount)
    uint256 rewardRate;
    // average water amount stored by user in each pool
    uint256 averageStored;
    // reserve field
    uint256 reserve;
}

struct LockedUserInfo {
    // fee level index => total auction count for the fee level
    uint32[8] lockedCounts;
    uint256 lockedAmount;
}

library WaterTowerStorage {
    struct Layout {
        // total ether reward received from other markets
        uint256 totalRewards;
        // current pool index
        uint256 curPoolIndex;
        // total water deposit amount
        uint256 totalDeposits;
        // water amount sent as irrigate bonus
        uint256 totalBonus;
        // pool info per month
        mapping(uint256 => PoolInfo) pools;
        // deposit amount, pending reward, and setting for user
        mapping(address => UserInfo) users;
        /// @dev config variables
        // bonus percent for irrigator
        uint256 irrigateBonusRate;
        // Middle asset for irrigating ether reward
        address middleAssetForIrrigate;
        // added upgrade 002
        // user => locked user info
        mapping(address => LockedUserInfo) lockedUsers;
    }

    bytes32 internal constant STORAGE_SLOT = keccak256("irrigation.contracts.storage.WaterTower");

    function layout() internal pure returns (Layout storage l) {
        bytes32 slot = STORAGE_SLOT;
        assembly {
            l.slot := slot
        }
    }

    function curPool() internal view returns (PoolInfo storage) {
        return layout().pools[layout().curPoolIndex];
    }

    function userInfo(address user) internal view returns (UserInfo storage) {
        return layout().users[user];
    }
}

contracts/interfaces/IDiamondCut.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/

interface IDiamondCut {
    enum FacetCutAction {Add, Replace, Remove}
    // Add=0, Replace=1, Remove=2

    struct FacetCut {
        address facetAddress;
        FacetCutAction action;
        bytes4[] functionSelectors;
    }

    /// @notice Add/replace/remove any number of functions and optionally execute
    ///         a function with delegatecall
    /// @param _diamondCut Contains the facet addresses and function selectors
    /// @param _init The address of the contract or facet to execute _calldata
    /// @param _calldata A function call, including function selector and arguments
    ///                  _calldata is executed with delegatecall on _init
    function diamondCut(
        FacetCut[] calldata _diamondCut,
        address _init,
        bytes calldata _calldata
    ) external;

    event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}

contracts/interfaces/IPriceOracleUpgradeable.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

interface IPriceOracleUpgradeable {
    /**
     * @notice Get latest price normalized to 1e18 for asset
     */
    function getPrice(address asset) external view returns (uint256);

    function getUnderlyingPriceETH() external view returns (uint);

    function getWaterPrice() external view returns (uint256);
}

contracts/interfaces/IWaterTowerUpgradeable.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

/// @title WaterTower Interface

interface IWaterTowerUpgradeable {
    
    /// @dev events
    event Deposited(address indexed user, uint amount);
    event Withdrawn(address indexed user, uint amount);
    event Claimed(address indexed user, uint amount);
    event Irrigate(
        address indexed user,
        address middleAsset,
        uint irrigateAmount,
        uint waterAmount,
        uint bonusAmount
    );
    event SetAutoIrrigate(address indexed user, uint timestamp, bool bAutoIrrigate);
    event AutoIrrigate(address indexed user, uint rewardAmount, uint gasFee);
    event AddETHReward(uint256 amount);
    event UpdateRewardPeriod(uint poolIndex, uint endTime, uint monthlyRewards);

    function addETHReward() external payable;
}

contracts/libraries/Constants.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

library Constants {
    /// Addresses
    address internal constant CURVE_ROUTER = 0x99a58482BD75cbab83b27EC03CA68fF489b5788f;
    address internal constant BEAN = 0xBEA0000029AD1c77D3d5D23Ba2D8893dB9d1Efab;
    address internal constant ETHER = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    address internal constant TRI_CRYPTO_POOL = 0xD51a44d3FaE010294C616388b506AcdA1bfAAE46;
    address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
    address internal constant CURVE_BEAN_METAPOOL = 0xc9C32cd16Bf7eFB85Ff14e0c8603cc90F6F2eE49;
    address internal constant BEANSTALK_PRICE = 0xb01CE0008CaD90104651d6A84b6B11e182a9B62A;
    address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
    address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
    address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address internal constant ZERO = 0x0000000000000000000000000000000000000000;
    address internal constant BEANSTALK = 0xC1E088fC1323b20BCBee9bd1B9fC9546db5624C5;
    address internal constant FERTILIZER = 0x402c84De2Ce49aF88f5e2eF3710ff89bFED36cB6;
    /// bean - weth pool
    address internal constant BEAN_ETH_WELL = 0xBEA0e11282e2bB5893bEcE110cF199501e872bAd;

    /// @notice time out to get price from chainlink
    /// @dev should update before deploying on mainnet
    uint256 internal constant GRACE_PERIOD_TIME = 6 days;

    /// underlying decimals
    uint256 internal constant D18 = 1e18;
    // tranche nft is fractionalized with decimals 6
    uint8 internal constant TRANCHE_DECIMALS = 6;
    uint8 internal constant WATER_DECIMALS = 18;

    bytes internal constant EMPTY = "";

    /// function selectors
    bytes4 internal constant ERC1155_ACCEPTED = 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
    bytes4 internal constant ERC1155_BATCH_ACCEPTED = 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
}

contracts/libraries/FullMath.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

/// @title Contains math functions
library FullMath {
    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        result = (a * b) / denominator;
        if (mulmod(a, b, denominator) > 0) {
            require(result < type(uint256).max);
            result++;
        }
    }

    function mulDivRoundingUp128(
        uint128 a,
        uint128 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        result = (uint256(a) * uint256(b)) / denominator;
        if (mulmod(uint256(a), uint256(b), denominator) > 0) {
            // require(result < type(uint256).max); // no overflow for uint128
            result++;
        }
    }
}

contracts/libraries/LibDiamond.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/
import { IDiamondCut } from "../interfaces/IDiamondCut.sol";

// Remember to add the loupe functions from DiamondLoupeFacet to the diamond.
// The loupe functions are required by the EIP2535 Diamonds standard

library LibDiamond {
    bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");

    struct DiamondStorage {
        // maps function selectors to the facets that execute the functions.
        // and maps the selectors to their position in the selectorSlots array.
        // func selector => address facet, selector position
        mapping(bytes4 => bytes32) facets;
        // array of slots of function selectors.
        // each slot holds 8 function selectors.
        mapping(uint256 => bytes32) selectorSlots;
        // The number of function selectors in selectorSlots
        uint16 selectorCount;
        // Used to query if a contract implements an interface.
        // Used to implement ERC-165.
        mapping(bytes4 => bool) supportedInterfaces;
        // owner of the contract
        address contractOwner;
    }

    function diamondStorage() internal pure returns (DiamondStorage storage ds) {
        bytes32 position = DIAMOND_STORAGE_POSITION;
        assembly {
            ds.slot := position
        }
    }

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    function setContractOwner(address _newOwner) internal {
        DiamondStorage storage ds = diamondStorage();
        address previousOwner = ds.contractOwner;
        ds.contractOwner = _newOwner;
        emit OwnershipTransferred(previousOwner, _newOwner);
    }

    function contractOwner() internal view returns (address contractOwner_) {
        contractOwner_ = diamondStorage().contractOwner;
    }

    function enforceIsContractOwner() internal view {
        require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
    }

    event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);

    bytes32 constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff));
    bytes32 constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224));

    // Internal function version of diamondCut
    // This code is almost the same as the external diamondCut,
    // except it is using 'Facet[] memory _diamondCut' instead of
    // 'Facet[] calldata _diamondCut'.
    // The code is duplicated to prevent copying calldata to memory which
    // causes an error for a two dimensional array.
    function diamondCut(
        IDiamondCut.FacetCut[] memory _diamondCut,
        address _init,
        bytes memory _calldata
    ) internal {
        DiamondStorage storage ds = diamondStorage();
        uint256 originalSelectorCount = ds.selectorCount;
        uint256 selectorCount = originalSelectorCount;
        bytes32 selectorSlot;
        // Check if last selector slot is not full
        // "selectorCount & 7" is a gas efficient modulo by eight "selectorCount % 8"
        if (selectorCount & 7 > 0) {
            // get last selectorSlot
            // "selectorSlot >> 3" is a gas efficient division by 8 "selectorSlot / 8"
            selectorSlot = ds.selectorSlots[selectorCount >> 3];
        }
        // loop through diamond cut
        for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
            (selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors(
                selectorCount,
                selectorSlot,
                _diamondCut[facetIndex].facetAddress,
                _diamondCut[facetIndex].action,
                _diamondCut[facetIndex].functionSelectors
            );
        }
        if (selectorCount != originalSelectorCount) {
            ds.selectorCount = uint16(selectorCount);
        }
        // If last selector slot is not full
        // "selectorCount & 7" is a gas efficient modulo by eight "selectorCount % 8"
        if (selectorCount & 7 > 0) {
            // "selectorSlot >> 3" is a gas efficient division by 8 "selectorSlot / 8"
            ds.selectorSlots[selectorCount >> 3] = selectorSlot;
        }
        emit DiamondCut(_diamondCut, _init, _calldata);
        initializeDiamondCut(_init, _calldata);
    }

    function addReplaceRemoveFacetSelectors(
        uint256 _selectorCount,
        bytes32 _selectorSlot,
        address _newFacetAddress,
        IDiamondCut.FacetCutAction _action,
        bytes4[] memory _selectors
    ) internal returns (uint256, bytes32) {
        DiamondStorage storage ds = diamondStorage();
        require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
        if (_action == IDiamondCut.FacetCutAction.Add) {
            enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code");
            for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
                bytes4 selector = _selectors[selectorIndex];
                bytes32 oldFacet = ds.facets[selector];
                require(address(bytes20(oldFacet)) == address(0), "LibDiamondCut: Can't add function that already exists");
                // add facet for selector
                ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount);
                // "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8"
                // " << 5 is the same as multiplying by 32 ( * 32)
                uint256 selectorInSlotPosition = (_selectorCount & 7) << 5;
                // clear selector position in slot and add selector
                _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) | (bytes32(selector) >> selectorInSlotPosition);
                // if slot is full then write it to storage
                if (selectorInSlotPosition == 224) {
                    // "_selectorSlot >> 3" is a gas efficient division by 8 "_selectorSlot / 8"
                    ds.selectorSlots[_selectorCount >> 3] = _selectorSlot;
                    _selectorSlot = 0;
                }
                _selectorCount++;
            }
        } else if (_action == IDiamondCut.FacetCutAction.Replace) {
            enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code");
            for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
                bytes4 selector = _selectors[selectorIndex];
                bytes32 oldFacet = ds.facets[selector];
                address oldFacetAddress = address(bytes20(oldFacet));
                // only useful if immutable functions exist
                require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function");
                require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function");
                require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist");
                // replace old facet address
                ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress);
            }
        } else if (_action == IDiamondCut.FacetCutAction.Remove) {
            require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
            // "_selectorCount >> 3" is a gas efficient division by 8 "_selectorCount / 8"
            uint256 selectorSlotCount = _selectorCount >> 3;
            // "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8"
            uint256 selectorInSlotIndex = _selectorCount & 7;
            for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
                if (_selectorSlot == 0) {
                    // get last selectorSlot
                    selectorSlotCount--;
                    _selectorSlot = ds.selectorSlots[selectorSlotCount];
                    selectorInSlotIndex = 7;
                } else {
                    selectorInSlotIndex--;
                }
                bytes4 lastSelector;
                uint256 oldSelectorsSlotCount;
                uint256 oldSelectorInSlotPosition;
                // adding a block here prevents stack too deep error
                {
                    bytes4 selector = _selectors[selectorIndex];
                    bytes32 oldFacet = ds.facets[selector];
                    require(address(bytes20(oldFacet)) != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
                    // only useful if immutable functions exist
                    require(address(bytes20(oldFacet)) != address(this), "LibDiamondCut: Can't remove immutable function");
                    // replace selector with last selector in ds.facets
                    // gets the last selector
                    // " << 5 is the same as multiplying by 32 ( * 32)
                    lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex << 5));
                    if (lastSelector != selector) {
                        // update last selector slot position info
                        ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]);
                    }
                    delete ds.facets[selector];
                    uint256 oldSelectorCount = uint16(uint256(oldFacet));
                    // "oldSelectorCount >> 3" is a gas efficient division by 8 "oldSelectorCount / 8"
                    oldSelectorsSlotCount = oldSelectorCount >> 3;
                    // "oldSelectorCount & 7" is a gas efficient modulo by eight "oldSelectorCount % 8"
                    // " << 5 is the same as multiplying by 32 ( * 32)
                    oldSelectorInSlotPosition = (oldSelectorCount & 7) << 5;
                }
                if (oldSelectorsSlotCount != selectorSlotCount) {
                    bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount];
                    // clears the selector we are deleting and puts the last selector in its place.
                    oldSelectorSlot =
                        (oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) |
                        (bytes32(lastSelector) >> oldSelectorInSlotPosition);
                    // update storage with the modified slot
                    ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot;
                } else {
                    // clears the selector we are deleting and puts the last selector in its place.
                    _selectorSlot =
                        (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) |
                        (bytes32(lastSelector) >> oldSelectorInSlotPosition);
                }
                if (selectorInSlotIndex == 0) {
                    delete ds.selectorSlots[selectorSlotCount];
                    _selectorSlot = 0;
                }
            }
            _selectorCount = selectorSlotCount * 8 + selectorInSlotIndex;
        } else {
            revert("LibDiamondCut: Incorrect FacetCutAction");
        }
        return (_selectorCount, _selectorSlot);
    }

    function initializeDiamondCut(address _init, bytes memory _calldata) internal {
        if (_init == address(0)) {
            return;
        }
        enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
        (bool success, bytes memory error) = _init.delegatecall(_calldata);
        if (!success) {
            if (error.length > 0) {
                // bubble up error
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(error)
                    revert(add(32, error), returndata_size)
                }
            } else {
                revert("InitializationFunctionReverted(address, bytes)");
            }
        }
    }

    function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
        uint256 contractSize;
        assembly {
            contractSize := extcodesize(_contract)
        }
        require(contractSize > 0, _errorMessage);
    }
}

contracts/utils/EIP2535Initializable.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "@gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/Initializable.sol";
import "@gnus.ai/contracts-upgradeable-diamond/contracts/proxy/utils/InitializableStorage.sol";
import "../libraries/LibDiamond.sol";

abstract contract EIP2535Initializable is Initializable {

    // override Initializable::initializer modifier
    modifier EIP2535Initializer() {
        require(!InitializableStorage.layout()._initializing && InitializableStorage.layout()._initialized < 1, "Initializable: contract is already initialized");
        InitializableStorage.layout()._initialized = 1;
        InitializableStorage.layout()._initializing = true;
        _;
        // multiple facet contracts needed initialization on deployment
        InitializableStorage.layout()._initialized = 0;
        InitializableStorage.layout()._initializing = false;
    }

    modifier EIP2535Reinitializer(uint8 version) {
        require(!InitializableStorage.layout()._initializing && InitializableStorage.layout()._initialized < version, "Initializable: contract is already initialized");
        InitializableStorage.layout()._initialized = version;
        InitializableStorage.layout()._initializing = true;
        _;
        // multiple facet contracts needed re-initialization on ugrades for instance
        InitializableStorage.layout()._initialized = 0;
        InitializableStorage.layout()._initializing = false;
        }

}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "none"
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "london",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.