Skip to content
Verified contractExactMIT

StakeManager

Address0xc37830d3f38cbc733f04020498d475d7bf2f28a7
Balance

0 ETH

 

Transactions

29

 

Compiler

solc 0.8.38

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.38+commit.1835d247
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,491,899
Creation transaction
0x0e1b622832…3cd3ab34e6

project/contracts/StakeManager.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {OperatorLockable} from "./OperatorLockable.sol";
import {DexTreasury} from "./DexTreasury.sol";
import {IOperatorLockable} from "./interfaces/IOperatorLockable.sol";
import {IStakeHook} from "./interfaces/IStakeHook.sol";
import {IStakeManager} from "./interfaces/IStakeManager.sol";
import {ICouncil} from "./interfaces/ICouncil.sol";
import {Venue} from "./types/Dex.sol";

contract StakeManager is OperatorLockable, DexTreasury, IStakeManager {
    using SafeERC20 for IERC20;
    using SafeERC20 for IERC20Metadata;

    struct Stake {
        uint256 amount;
        address owner;
        uint8 tier;
        uint256 stakedAt;
        uint256 ownedAt;
    }

    struct Account {
        uint256 accruedNum;
        uint256 lastAccrualAt;
        uint256 lastClaimAt;
        uint256 firstStakeAt;
        uint256 stakeCount;
    }

    uint256 public constant MAX_STAKES = 100;
    uint256 public constant CLAIM_COOLDOWN = 1 days;

    uint256 public constant DENOM = 3650 days;
    uint256 public constant YEAR = 365 days;
    uint8 public constant TIERS = 3;

    IERC20Metadata private immutable _stakingToken;

    uint256 public nextStakeId = 1;
    uint256 public totalStaked;
    uint256 public activeStakes;
    IStakeHook private immutable _stakeHook;
    address private immutable _stakeExchange;

    mapping(uint8 tier => uint256) public totalStakedIn;
    mapping(uint8 tier => uint256) public activeStakesIn;
    mapping(address owner => Account) private _accounts;
    mapping(address owner => mapping(uint8 tier => uint256)) private _tierTotal;
    mapping(uint256 stakeId => Stake) private _stakes;
    mapping(address account => bool) private _freeUnstake;

    constructor(
        IERC20Metadata stakingToken_,
        uint256 dexSellCap_,
        address stakeHook_,
        address stakeExchange_,
        Venue memory uniswap_,
        Venue memory pancake_,
        address council_
    ) DexTreasury(council_, uniswap_, pancake_, stakingToken_, dexSellCap_) {
        require(address(stakingToken_) != address(0) && stakeExchange_ != address(0), ZeroAddress());
        require(stakeHook_ == address(0) || stakeHook_.code.length != 0, AddressWithoutCode(stakeHook_));
        require(stakeExchange_.code.length != 0, AddressWithoutCode(stakeExchange_));

        _stakingToken = stakingToken_;
        _stakeHook = IStakeHook(stakeHook_);
        _stakeExchange = stakeExchange_;
    }

    function stake(uint8 tier, uint256 amount, address referrer) external returns (uint256 id) {
        require(tier < TIERS, InvalidTier(tier));
        require(amount != 0, ZeroAmount());

        address sender = _msgSender();
        _requireSlot(sender);

        _stakingToken.safeTransferFrom(sender, address(this), amount);

        id = _stake(sender, tier, amount);
        _notifyStakeHook(sender, referrer, amount);
    }

    function unstake(uint256[] calldata ids) external returns (uint256 released) {
        require(ids.length != 0, InvalidListLength(ids.length, 1));

        released = 0;

        address sender = _msgSender();
        _settle(sender);
        uint256 before = totalStakedOf(sender);

        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids[i];
            Stake memory stake_ = _requireStakeOf(sender, id);

            _requireFree(id);

            _requireMatured(sender, id, stake_);

            released += stake_.amount;

            _tierTotal[sender][stake_.tier] -= stake_.amount;
            totalStakedIn[stake_.tier] -= stake_.amount;
            _destroy(sender, id);

            emit Unstaked(id, sender, stake_.tier, stake_.amount, 0);
        }

        totalStaked -= released;
        _notifyCouncil(sender, before, before - released);

        _stakingToken.safeTransfer(sender, released);
    }

    function unstakeOne(uint256 id, uint256 amount) external {
        require(amount != 0, ZeroAmount());

        address sender = _msgSender();
        Stake memory stake_ = _requireStakeOf(sender, id);

        _requireFree(id);
        require(amount <= stake_.amount, InsufficientStake(id, stake_.amount, amount));

        _requireMatured(sender, id, stake_);

        _settle(sender);

        uint256 left = stake_.amount - amount;
        if (left == 0) {
            _destroy(sender, id);
        } else {
            _stakes[id].amount = left;
            emit StakeChanged(id);
        }

        uint256 before = totalStakedOf(sender);
        _tierTotal[sender][stake_.tier] -= amount;
        totalStaked -= amount;
        totalStakedIn[stake_.tier] -= amount;
        _notifyCouncil(sender, before, before - amount);

        _stakingToken.safeTransfer(sender, amount);

        emit Unstaked(id, sender, stake_.tier, amount, left);
    }

    function merge(uint256[] calldata ids) external returns (uint256 newId) {
        require(ids.length >= 2, InvalidListLength(ids.length, 2));

        address sender = _msgSender();
        _settle(sender);

        uint8 tier = _requireStakeOf(sender, ids[0]).tier;
        uint256 mergedAmount;
        uint256 mergedStakedAt;
        uint256[] memory amounts = new uint256[](ids.length);

        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids[i];
            Stake memory stake_ = _requireStakeOf(sender, id);

            _requireFree(id);
            require(stake_.tier == tier, TierMismatch(id, stake_.tier, tier));

            amounts[i] = stake_.amount;
            mergedAmount += stake_.amount;
            if (stake_.stakedAt > mergedStakedAt) {
                mergedStakedAt = stake_.stakedAt;
            }

            _destroy(sender, id);
        }

        newId = _create(sender, tier, mergedAmount, mergedStakedAt, block.timestamp);

        for (uint256 i = 0; i < ids.length; ++i) {
            emit Merged(ids[i], newId, sender, tier, amounts[i]);
        }
    }

    function upgrade(uint256 id, uint8 newTier) external {
        require(newTier < TIERS, InvalidTier(newTier));

        address sender = _msgSender();
        Stake memory stake_ = _requireStakeOf(sender, id);
        require(newTier > stake_.tier, NotAnUpgrade(id, stake_.tier, newTier));

        _requireFree(id);

        _settle(sender);

        _tierTotal[sender][stake_.tier] -= stake_.amount;
        _tierTotal[sender][newTier] += stake_.amount;
        totalStakedIn[stake_.tier] -= stake_.amount;
        totalStakedIn[newTier] += stake_.amount;
        activeStakesIn[stake_.tier] -= 1;
        activeStakesIn[newTier] += 1;

        _stakes[id].tier = newTier;
        _stakes[id].stakedAt = block.timestamp;
        _stakes[id].ownedAt = block.timestamp;

        emit Upgraded(id, sender, stake_.tier, newTier, stake_.amount, block.timestamp);
        emit StakeChanged(id);
    }

    function claim() external {
        address sender = _msgSender();

        uint256 availableAt = _accounts[sender].lastClaimAt + CLAIM_COOLDOWN;
        require(block.timestamp >= availableAt, ClaimTooEarly(sender, availableAt));
        require(_pending(sender) != 0, NothingToClaim(sender));

        _settle(sender);

        Account storage account = _accounts[sender];
        uint256 accrued = account.accruedNum / DENOM;
        uint256 available = availableRewards();
        uint256 claimAmount = accrued < available ? accrued : available;
        require(claimAmount != 0, RewardsDepleted());

        account.accruedNum -= claimAmount * DENOM;
        account.lastClaimAt = block.timestamp;

        _stakingToken.safeTransfer(sender, claimAmount);

        emit Claimed(sender, claimAmount);
    }

    function lock(uint256 id, uint256 lockTill) public override(IOperatorLockable, OperatorLockable) {
        super.lock(id, lockTill);

        emit StakeChanged(id);
    }

    function unlock(uint256 id) public override(IOperatorLockable, OperatorLockable) {
        bool wasLocked = isLocked(id);

        super.unlock(id);

        if (wasLocked) {
            emit StakeChanged(id);
        }
    }

    function transferPart(
        address from,
        uint256 id,
        uint256 amount,
        address to
    ) external returns (uint256 remainderId) {
        require(_msgSender() == _stakeExchange, OnlyExchangeAccess());
        require(to != address(0) && to != address(this) && to != from, InvalidReceiver(to));
        require(amount != 0, ZeroAmount());

        Stake memory stake_ = _requireStakeOf(from, id);
        require(amount <= stake_.amount, InsufficientStake(id, stake_.amount, amount));

        address lockedFor = lockedForOf(id);
        require(lockedFor == address(0) || lockedFor == from, StakeLocked(id, lockTillOf(id)));

        _requireAllowance(from, _msgSender());
        _requireSlot(to);

        remainderId = _move(id, stake_, amount, to);

        emit Transferred(id, remainderId, from, to, stake_.tier, amount, stake_.stakedAt, lockTillOf(id));
    }

    function returnLocked(uint256 id) external {
        require(_msgSender() == _stakeExchange, OnlyExchangeAccess());
        address to = lockedForOf(id);
        require(to != address(0), StakeNotLocked(id));

        _requireAllowance(to, _msgSender());

        Stake memory stake_ = _requireStake(id);

        require(to != stake_.owner, InvalidReceiver(to));

        _requireSlot(to);

        _move(id, stake_, stake_.amount, to);
        _unlock(id);

        emit Returned(id, stake_.owner, to, stake_.tier, stake_.amount);
    }

    function setFreeUnstake(address account, bool enabled) external onlyCouncil {
        require(_freeUnstake[account] != enabled, SameFreeUnstake(account, enabled));
        require(!enabled || isClean(account), NotClean(account));

        _freeUnstake[account] = enabled;

        emit FreeUnstakeSet(account, enabled);
    }

    function token() public view override returns (IERC20) {
        return _stakingToken;
    }

    function stakeExchange() external view returns (address) {
        return _stakeExchange;
    }

    function stakeHook() external view returns (address) {
        return address(_stakeHook);
    }

    function getAccount(address owner) external view returns (AccountView memory) {
        Account memory account = _accounts[owner];

        return AccountView({
            accruedNum: account.accruedNum,
            lastAccrualAt: account.lastAccrualAt,
            lastClaimAt: account.lastClaimAt,
            firstStakeAt: account.firstStakeAt,
            stakeCount: account.stakeCount,
            stakedTotal: totalStakedOf(owner)
        });
    }

    function totalStakedOf(address owner) public view returns (uint256 total) {
        total = 0;
        for (uint8 tier = 0; tier < TIERS; ++tier) {
            total += _tierTotal[owner][tier];
        }
    }

    function totalStakedByTierOf(address owner) external view returns (uint256[] memory out) {
        out = new uint256[](TIERS);
        for (uint8 tier = 0; tier < TIERS; ++tier) {
            out[tier] = _tierTotal[owner][tier];
        }
    }

    function pendingOf(address owner) external view returns (uint256) {
        return _pending(owner);
    }

    function tierTotalOf(address owner, uint8 tier) external view returns (uint256) {
        return _tierTotal[owner][tier];
    }

    function tiers() external pure returns (TierInfo[] memory out) {
        out = new TierInfo[](TIERS);
        for (uint8 tier = 0; tier < TIERS; ++tier) {
            out[tier] = TierInfo({tier: tier, term: _term(tier), weight: _weight(tier)});
        }
    }

    function totalStakedByTier() external view returns (uint256[] memory out) {
        out = new uint256[](TIERS);
        for (uint8 tier = 0; tier < TIERS; ++tier) {
            out[tier] = totalStakedIn[tier];
        }
    }

    function activeStakesByTier() external view returns (uint256[] memory out) {
        out = new uint256[](TIERS);
        for (uint8 tier = 0; tier < TIERS; ++tier) {
            out[tier] = activeStakesIn[tier];
        }
    }

    function unstakeAtOf(uint256 id) external view returns (uint256) {
        Stake memory stake_ = _stakes[id];
        return stake_.owner == address(0) ? 0 : _unstakeAt(stake_);
    }

    function getStake(uint256 id) external view returns (StakeView memory) {
        return _stakeView(id);
    }

    function getStakes(uint256[] calldata ids) external view returns (StakeView[] memory out) {
        out = new StakeView[](ids.length);
        for (uint256 i = 0; i < ids.length; ++i) {
            out[i] = _stakeView(ids[i]);
        }
    }

    function availableRewards() public view returns (uint256) {
        uint256 balance = _stakingToken.balanceOf(address(this));
        return balance > totalStaked ? balance - totalStaked : 0;
    }

    function hasFreeUnstake(address account) external view returns (bool) {
        return _freeUnstake[account];
    }

    function isClean(address account) public view returns (bool) {
        return _accounts[account].lastAccrualAt == 0;
    }

    function isApprovedForAll(address owner, address operator) public view override(IOperatorLockable, OperatorLockable) returns (bool) {
        return _operatorPermitted(operator) && super.isApprovedForAll(owner, operator);
    }

    function _stake(address owner, uint8 tier, uint256 amount) private returns (uint256 id) {
        _settle(owner);

        Account storage account = _accounts[owner];
        if (account.firstStakeAt == 0) {
            account.firstStakeAt = block.timestamp;
        }

        id = _create(owner, tier, amount, block.timestamp, block.timestamp);

        uint256 before = totalStakedOf(owner);
        _tierTotal[owner][tier] += amount;
        totalStaked += amount;
        totalStakedIn[tier] += amount;
        _notifyCouncil(owner, before, before + amount);

        emit Staked(id, owner, tier, amount);
    }

    function _move(uint256 id, Stake memory stake_, uint256 amount, address to) private returns (uint256 remainderId) {
        remainderId = 0;

        _settle(stake_.owner);
        _settle(to);

        uint256 fromBefore = totalStakedOf(stake_.owner);
        uint256 toBefore = totalStakedOf(to);
        _tierTotal[stake_.owner][stake_.tier] -= amount;
        _tierTotal[to][stake_.tier] += amount;
        _notifyCouncil(stake_.owner, fromBefore, fromBefore - amount);
        _notifyCouncil(to, toBefore, toBefore + amount);

        _stakes[id].owner = to;
        _stakes[id].ownedAt = block.timestamp;
        _accounts[stake_.owner].stakeCount -= 1;
        _accounts[to].stakeCount += 1;

        if (amount != stake_.amount) {
            _stakes[id].amount = amount;
            remainderId = _create(stake_.owner, stake_.tier, stake_.amount - amount, stake_.stakedAt, stake_.ownedAt);
        }

        emit StakeChanged(id);
    }

    function _create(
        address owner,
        uint8 tier,
        uint256 amount,
        uint256 stakedAt,
        uint256 ownedAt
    ) private returns (uint256 id) {
        id = nextStakeId++;
        _stakes[id] = Stake({amount: amount, owner: owner, tier: tier, stakedAt: stakedAt, ownedAt: ownedAt});
        _accounts[owner].stakeCount += 1;
        activeStakes += 1;
        activeStakesIn[tier] += 1;

        emit StakeCreated(id, owner);
    }

    function _destroy(address owner, uint256 id) private {
        uint8 tier = _stakes[id].tier;

        delete _stakes[id];
        _accounts[owner].stakeCount -= 1;
        activeStakes -= 1;
        activeStakesIn[tier] -= 1;

        _unlock(id);

        emit StakeRemoved(id, owner);
    }

    function _settle(address owner) private {
        Account storage account = _accounts[owner];
        uint256 earned = _accruedNumSince(owner, account.lastAccrualAt);
        if (earned != 0) {
            account.accruedNum += earned;
        }
        account.lastAccrualAt = block.timestamp;
    }

    function _notifyStakeHook(address owner, address referrer, uint256 amount) private {
        IStakeHook hook = _stakeHook;
        if (address(hook) != address(0)) {
            address paid = _freeUnstake[owner] ? address(0) : referrer;
            hook.onStake(owner, paid, amount, _accounts[owner].firstStakeAt);
        }
    }

    function _notifyCouncil(address account, uint256 oldTotal, uint256 newTotal) private {
        ICouncil(council()).onStakeChanged(account, oldTotal, newTotal);
    }

    function _requireSlot(address owner) private view {
        require(_accounts[owner].stakeCount < MAX_STAKES, TooManyStakes(owner, MAX_STAKES));
    }

    function _requireStake(uint256 id) private view returns (Stake memory stake_) {
        stake_ = _stakes[id];
        require(stake_.owner != address(0), NonexistentStake(id));
    }

    function _requireStakeOf(address owner, uint256 id) private view returns (Stake memory stake_) {
        stake_ = _requireStake(id);
        require(stake_.owner == owner, IncorrectOwner(id, stake_.owner, owner));
    }

    function _requireFree(uint256 id) private view {
        require(!isLocked(id), StakeLocked(id, lockTillOf(id)));
    }

    function _requireMatured(address owner, uint256 id, Stake memory stake_) private view {
        if (_freeUnstake[owner]) {
            return;
        }
        uint256 unstakeAt = _unstakeAt(stake_);
        require(unstakeAt <= block.timestamp, StillStaking(id, unstakeAt));
    }

    function _accruedNumSince(address owner, uint256 since) private view returns (uint256) {
        if (since == 0 || since >= block.timestamp) {
            return 0;
        }

        uint256 elapsed = block.timestamp - since;
        uint256 weighted;
        for (uint8 tier = 0; tier < TIERS; ++tier) {
            uint256 total = _tierTotal[owner][tier];
            if (total != 0) {
                weighted += total * _weight(tier);
            }
        }
        return weighted * elapsed;
    }

    function _pending(address owner) private view returns (uint256) {
        Account storage account = _accounts[owner];
        return (account.accruedNum + _accruedNumSince(owner, account.lastAccrualAt)) / DENOM;
    }

    function _stakeView(uint256 id) private view returns (StakeView memory out) {
        Stake memory stake_ = _stakes[id];
        if (stake_.owner == address(0)) {
            return out;
        }

        out = StakeView({
            id: id,
            owner: stake_.owner,
            tier: stake_.tier,
            amount: stake_.amount,
            stakedAt: stake_.stakedAt,
            ownedAt: stake_.ownedAt,
            unstakeAt: _unstakeAt(stake_),
            lockedTill: lockTillOf(id),
            lockedFor: lockedForOf(id)
        });
    }

    function _ownerOf(uint256 id) internal view override returns (address) {
        return _stakes[id].owner;
    }

    function _operatorPermitted(address operator) internal view override returns (bool) {
        return operator == _stakeExchange;
    }

    function _requireAllowance(address owner, address operator) internal view override {
        _requireOperatorPermitted(operator);
        require(isApprovedForAll(owner, operator), NotApproved(owner, operator));
    }

    function _afterDexOperation() internal view override {
        uint256 balance = _stakingToken.balanceOf(address(this));
        require(balance >= totalStaked, TreasuryBelowStaked(balance, totalStaked));
    }

    function _unstakeAt(Stake memory stake_) private pure returns (uint256) {
        return stake_.stakedAt + _term(stake_.tier);
    }

    function _term(uint8 tier) private pure returns (uint256) {
        return (uint256(tier) * 2 + 1) * YEAR;
    }

    function _weight(uint8 tier) private pure returns (uint256) {
        return uint256(tier) + 1;
    }
}

npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

npm/@openzeppelin/[email protected]/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

npm/@openzeppelin/[email protected]/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

npm/@openzeppelin/[email protected]/interfaces/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

npm/@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
    function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
        bytes4 selector = IERC20Metadata.decimals.selector;
        assembly ("memory-safe") {
            mstore(0x00, selector)
            success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
            success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
            decimals := mul(success, mload(0x00))
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to approve
     * @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

npm/@openzeppelin/[email protected]/token/ERC721/IERC721Receiver.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity >=0.5.0;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

npm/@openzeppelin/[email protected]/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC 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);
}

project/contracts/DexTreasury.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Context} from "@openzeppelin/contracts/utils/Context.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";

import {IDexTreasury} from "./interfaces/IDexTreasury.sol";
import {IUniswapV3Factory} from "./interfaces/external/uniswap-v3/IUniswapV3Factory.sol";
import {INonfungiblePositionManager} from "./interfaces/external/uniswap-v3/INonfungiblePositionManager.sol";
import {UniswapV3} from "./libraries/UniswapV3.sol";
import {
    Dex,
    Venue,
    MintParams,
    IncreaseParams,
    DecreaseParams,
    IncreaseResult,
    DecreaseResult
} from "./types/Dex.sol";

abstract contract DexTreasury is Context, IDexTreasury, IERC721Receiver {
    using UniswapV3 for Venue;

    address private immutable _council;
    IERC20 private immutable _base;
    uint256 private immutable _sellCap;

    IUniswapV3Factory private immutable _uniswapFactory;
    INonfungiblePositionManager private immutable _uniswapPositionManager;
    IUniswapV3Factory private immutable _pancakeFactory;
    INonfungiblePositionManager private immutable _pancakePositionManager;

    uint256 private _sold;

    modifier onlyCouncil() {
        require(_msgSender() == _council, NotCouncil(_msgSender()));
        _;
    }

    constructor(
        address council_,
        Venue memory uniswap,
        Venue memory pancake,
        IERC20 base,
        uint256 sellCap
    ) {
        require(council_ != address(0), NoCouncil());
        require(address(base) != address(0), ZeroDexAddress());
        _requireVenue(uniswap);
        _requireVenue(pancake);

        _council = council_;
        _base = base;
        _sellCap = sellCap;

        _uniswapFactory = uniswap.factory;
        _uniswapPositionManager = uniswap.positionManager;
        _pancakeFactory = pancake.factory;
        _pancakePositionManager = pancake.positionManager;

        emit DexSellLeftChanged(0, sellCap);
    }

    function mintPosition(
        Dex dex,
        MintParams calldata params
    ) external onlyCouncil returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) {
        uint256 before = _baseBalance();
        IncreaseResult memory result = venue(dex).mint(params);

        emit PositionMinted(dex, result.tokenId, params.token0, params.token1, params.fee, params.tickLower, params.tickUpper);
        emit LiquidityIncreased(dex, result.tokenId, result.liquidity, result.amount0, result.amount1);

        _settle(before);
        return (result.tokenId, result.liquidity, result.amount0, result.amount1);
    }

    function increaseLiquidity(
        Dex dex,
        IncreaseParams calldata params
    ) external onlyCouncil returns (uint128 liquidity, uint256 amount0, uint256 amount1) {
        uint256 before = _baseBalance();
        IncreaseResult memory result = venue(dex).increaseLiquidity(params);

        emit LiquidityIncreased(dex, params.tokenId, result.liquidity, result.amount0, result.amount1);

        _settle(before);
        return (result.liquidity, result.amount0, result.amount1);
    }

    function decreaseLiquidity(
        Dex dex,
        DecreaseParams calldata params
    ) external onlyCouncil returns (uint256 amount0, uint256 amount1, uint256 fees0, uint256 fees1, bool burned) {
        uint256 before = _baseBalance();
        DecreaseResult memory result = venue(dex).decreaseLiquidity(params);

        emit LiquidityDecreased(
            dex,
            params.tokenId,
            params.liquidity,
            result.amount0,
            result.amount1,
            result.fees0,
            result.fees1,
            result.burned
        );

        _settle(before);
        return (result.amount0, result.amount1, result.fees0, result.fees1, result.burned);
    }

    function collectFees(Dex dex, uint256 tokenId) external onlyCouncil returns (uint256 amount0, uint256 amount1) {
        uint256 before = _baseBalance();
        (amount0, amount1) = venue(dex).collect(tokenId);

        emit FeesCollected(dex, tokenId, amount0, amount1);

        _settle(before);
    }

    function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
        return IERC721Receiver.onERC721Received.selector;
    }

    function council() public view returns (address) {
        return _council;
    }

    function venue(Dex dex) public view returns (Venue memory) {
        if (dex == Dex.Uniswap) {
            return Venue(_uniswapFactory, _uniswapPositionManager);
        }
        return Venue(_pancakeFactory, _pancakePositionManager);
    }

    function poolOf(Dex dex, uint256 tokenId) external view returns (address token0, address token1, uint24 fee) {
        return venue(dex).poolOf(tokenId);
    }

    function dexSellCap() external view returns (uint256) {
        return _sellCap;
    }

    function dexSold() external view returns (uint256) {
        return _sold;
    }

    function dexSellLeft() public view returns (uint256) {
        return _sellCap > _sold ? _sellCap - _sold : 0;
    }

    function _afterDexOperation() internal view virtual {}

    function _baseBalance() private view returns (uint256) {
        return _base.balanceOf(address(this));
    }

    function _settle(uint256 before) private {
        _book(before, _baseBalance());
        _afterDexOperation();
    }

    function _book(uint256 before, uint256 current) private {
        uint256 sold = _sold;
        if (current < before) {
            sold += before - current;
            require(sold <= _sellCap, DexSellCapExceeded(sold, _sellCap));
        } else {
            uint256 bought = current - before;
            sold = bought >= sold ? 0 : sold - bought;
        }

        if (sold != _sold) {
            _sold = sold;
            emit DexSellLeftChanged(sold, dexSellLeft());
        }
    }

    function _requireVenue(Venue memory v) private view {
        require(address(v.factory).code.length != 0, NoCode(address(v.factory)));
        require(address(v.positionManager).code.length != 0, NoCode(address(v.positionManager)));
    }
}

project/contracts/OperatorLockable.sol

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

import {Context} from "@openzeppelin/contracts/utils/Context.sol";

import {IOperatorLockable} from "./interfaces/IOperatorLockable.sol";

abstract contract OperatorLockable is Context, IOperatorLockable {
    mapping(address owner => mapping(address operator => bool approved)) private _approvals;

    mapping(uint256 id => address lockedFor) private _lockedFor;

    mapping(uint256 id => uint256 till) private _lockedTill;

    function approveOperator(address operator) public virtual {
        _requireOperatorPermitted(operator);

        _changeApprove(_msgSender(), operator, true);
    }

    function revokeOperatorApprove(address owner, address operator) public virtual {
        address sender = _msgSender();
        require(sender == owner || sender == operator, NotApproved(owner, operator));

        _changeApprove(owner, operator, false);
    }

    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
        return _isApprovedForAll(owner, operator);
    }

    function lock(uint256 id) public virtual {
        lock(id, type(uint256).max);
    }

    function lock(uint256 id, uint256 lockTill) public virtual {
        address operator = _msgSender();
        address owner = _ownerOf(id);

        require(owner != address(0), NonexistentId(id));
        require(lockTill > block.timestamp, LockTillInPast());

        _requireLockAllowed(id, lockTill);

        _requireAllowance(owner, operator);
        _requireRelockAllowed(id, owner);

        _lock(id, owner, lockTill);
    }

    function unlock(uint256 id) public virtual {
        address lockedFor = _lockedForOf(id);
        if (lockedFor != address(0)) {
            _requireAllowance(lockedFor, _msgSender());
        }

        _unlock(id);
    }

    function isLocked(uint256 id) public view virtual returns (bool) {
        return _isLocked(id);
    }

    function lockTillOf(uint256 id) public view virtual returns (uint256) {
        return _lockedTillOf(id);
    }

    function lockedForOf(uint256 id) public view virtual returns (address) {
        return _lockedForOf(id);
    }

    function _isApprovedForAll(address owner, address operator) internal view virtual returns (bool) {
        return owner == operator || _approvals[owner][operator];
    }

    function _ownerOf(uint256 id) internal view virtual returns (address);

    function _lockedForOf(uint256 id) internal view virtual returns (address) {
        if (_isLocked(id)) {
            return _lockedFor[id];
        }

        return address(0);
    }

    function _lockedTillOf(uint256 id) internal view virtual returns (uint256) {
        return _lockedTill[id];
    }

    function _isLocked(uint256 id) internal view virtual returns (bool) {
        return _lockedTillOf(id) > block.timestamp;
    }

    function _operatorPermitted(address operator) internal view virtual returns (bool) {
        return operator != address(0);
    }

    function _requireAllowance(address owner, address operator) internal view virtual {
        if (owner == operator) {
            return;
        }
        _requireOperatorPermitted(operator);
        require(_isApprovedForAll(owner, operator), NotApproved(owner, operator));
    }

    function _requireRelockAllowed(uint256 id, address owner) internal view virtual {
        address beneficiary = _lockedForOf(id);
        require(beneficiary == address(0) || beneficiary == owner, AlreadyLocked(id));
    }

    function _requireOperatorPermitted(address operator) internal view virtual {
        require(_operatorPermitted(operator), OperatorNotPermitted(operator));
    }

    function _requireLockAllowed(uint256 id, uint256 till) internal view virtual {}

    function _lock(uint256 id, address lockedFor, uint256 lockedTill) internal virtual {
        _lockedFor[id] = lockedFor;
        _lockedTill[id] = lockedTill;

        emit Locked(id, lockedFor, lockedTill);
    }

    function _unlock(uint256 id) internal virtual {
        if (_lockedFor[id] == address(0)) {
            return;
        }
        delete _lockedFor[id];
        delete _lockedTill[id];

        emit Unlocked(id);
    }

    function _changeApprove(address owner, address operator, bool approved) internal virtual {
        _approvals[owner][operator] = approved;

        if (approved) {
            emit OperatorApproved(owner, operator);
        } else {
            emit OperatorApproveRevoked(owner, operator);
        }
    }
}

project/contracts/interfaces/ICouncil.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import {IReferralProgram} from "./IReferralProgram.sol";
import {IStakeManager} from "./IStakeManager.sol";
import {Dex} from "../types/Dex.sol";

/// Council governing a stake manager. Mutating calls must come directly from an EOA.
interface ICouncil {
    enum Vote {
        None,
        For,
        Against
    }

    enum ProposalKind {
        Admission,
        Expel,
        Seats,
        ReferralMode,
        GrantFreeUnstake,
        RevokeFreeUnstake,
        Treasury,
        DypeTreasury,
        Election
    }

    /// Who may execute an accepted proposal.
    enum Executor {
        AuthorOrPresident,
        Candidate
    }

    /// Immutable rules of a proposal kind.
    struct KindRules {
        uint256 delay;
        bool needsApproval;
        bool approvalIsSignificant;
        bool cancellationIsSignificant;
        bool cancellationClearsElection;
        bool reportsInactivity;
        Executor executor;
        bool takesExtraData;
    }

    /// A pool: venue, sorted pair and fee tier.
    struct Pool {
        Dex dex;
        address token0;
        address token1;
        uint24 fee;
    }

    /// Allowed fee tiers of one pair on one venue.
    struct PoolConfig {
        Dex dex;
        address token0;
        address token1;
        uint24[] fees;
    }

    /// Lifecycle state of a proposal.
    enum ProposalState {
        Voting,
        VotingNotPassed,
        AwaitingApproval,
        ApprovalMissed,
        Timelocked,
        Executable,
        Expired,
        Executed,
        Cancelled
    }

    struct ProposalView {
        uint256 id;
        ProposalKind kind;
        ProposalState state;
        address author;
        /// ABI-encoded argument of the kind.
        bytes payload;
        uint256 forVotes;
        uint256 againstVotes;
        /// Threshold at acceptance.
        uint256 requiredVotes;
        uint256 createdAt;
        uint256 acceptedAt;
        uint256 approvedAt;
        uint256 expeditedAt;
        uint256 executedAt;
        uint256 cancelledAt;
        /// Zero until accepted (and approved).
        uint256 executableAt;
        uint256 executableUntil;
        /// Missed approval was reported.
        bool expiryReported;
    }

    /// Stake manager wired.
    event StakeManagerSet(address indexed stakeManager);
    /// Rules of a proposal kind; read them with {proposalRulesOf}.
    event ProposalRulesDefined(ProposalKind indexed kind);
    /// A pool allowed for treasury proposals.
    event PoolAllowed(Dex indexed dex, address indexed token0, address indexed token1, uint24 fee);

    /// The account applied for membership.
    event MembershipFeePaid(address indexed account, uint256 fee);
    /// A new member; votes from `votingFrom`.
    event MemberJoined(address indexed account, uint256 votingFrom);
    /// A member's or applicant's stake crossed {votingStake}.
    event VotingStakeChanged(address indexed account, bool enough);
    /// A member left the council.
    event MemberRemoved(address indexed account);
    /// Number of seats changed.
    event SeatsChanged(uint256 oldSeats, uint256 newSeats);

    /// A proposal created.
    event ProposalCreated(
        uint256 indexed id,
        ProposalKind indexed kind,
        address indexed author,
        bytes payload,
        string description
    );
    /// A vote cast.
    event Voted(uint256 indexed id, address indexed voter, bool support);
    /// A proposal reached the threshold.
    event ProposalAccepted(uint256 indexed id, uint256 forVotes, uint256 required);
    /// The president approved a proposal.
    event ProposalApproved(uint256 indexed id);
    /// The president expedited a proposal.
    event ProposalExpedited(uint256 indexed id);
    /// A proposal cancelled.
    event ProposalCancelled(uint256 indexed id, address indexed by);
    /// `result` is the stake manager's return data for treasury kinds.
    event ProposalExecuted(uint256 indexed id, address indexed executor, bytes result);
    /// Missed approval reported.
    event ApprovalExpired(uint256 indexed id);

    /// Voluntary election flag changed.
    event VoluntaryElectionSet(bool enabled);
    /// Inactivity election flag changed.
    event InactivityElectionSet(bool enabled);
    /// Presidency handed over to the next successor.
    event PresidencyHandedOver(address indexed from, address indexed to);
    /// A new president with its successors.
    event PresidentElected(address indexed previous, address indexed president, address[] successors);

    error NotDirectCall(address caller);
    error ZeroAddress();
    error StakeManagerAlreadySet(address stakeManager);
    error StakeManagerNotSet();
    error NotStakeManager(address caller);
    error ReferralProgramMismatch(address expected, address actual);
    error TokenMismatch(address expected, address actual);
    error CouncilMismatch(address council);

    error InvalidMemberCount(uint256 count, uint256 expected);
    error InvalidSuccessorCount(uint256 count, uint256 expected);
    error RoleTaken(address account);
    error EmptyList();

    error NotPresident(address caller);
    error NotVotingMember(address account);
    error NotMember(address account);
    error AlreadyMember(address account);
    error AlreadyApplied(address account);
    error NotApplicant(address account);
    error InsufficientStake(address account, uint256 stake, uint256 required);
    error NoFreeSeat(uint256 seats);
    error AppointmentClosed(uint256 votingMembers, uint256 threshold);
    error NotExpellable(address account);
    error TooFewMembers(uint256 members, uint256 minimum);
    error InvalidSeats(uint256 seats, uint256 current, uint256 members);
    error SameReferralMode(IReferralProgram.ReferralMode mode);
    error NotClean(address account);
    error SameFreeUnstake(address account, bool enabled);
    error NotProposable(bytes4 selector);
    error InvalidCalldata();
    error NoElectionGround();
    error InvalidCandidate(address account);
    error NoSuccessors();
    error SameElectionFlag(bool enabled);
    error DescriptionTooLong(uint256 length, uint256 max);
    error InvalidPayload();
    error KindMismatch(ProposalKind declared, ProposalKind actual);
    error InvalidPool(Dex dex, address token0, address token1, uint24 fee);
    error PoolNotAllowed(Dex dex, address token0, address token1, uint24 fee);
    error UnexpectedExtraData();

    error NonexistentProposal(uint256 id);
    error UnexpectedState(uint256 id, ProposalState state);
    error WrongKind(uint256 id, ProposalKind kind);
    error AlreadyVoted(uint256 id, address voter);
    error AlreadyApproved(uint256 id);
    error AlreadyExpedited(uint256 id);
    error AlreadyReported(uint256 id);
    error PresidentActive(uint256 lastSignificantActionAt);
    error NotAuthorized(uint256 id, address caller);

    /// Wires the stake manager and renounces ownership.
    function setStakeManager(IStakeManager stakeManager_) external;

    /// Applies for membership and pays the fee.
    function applyForCouncil() external;

    /// Admits members without a vote.
    function appoint(address[] calldata accounts) external;

    /// Removes a member without a vote.
    function expel(address account) external;

    /// Sets or clears the voluntary election flag.
    function setVoluntaryElection(bool enabled) external;

    /// Hands the presidency to the next successor.
    function handover() external;

    /// Approves a proposal.
    function approve(uint256 id) external;

    /// Shortens the timelock of a proposal.
    function expedite(uint256 id) external;

    /// Creates a proposal.
    function propose(ProposalKind kind, bytes calldata payload, string calldata description) external returns (uint256 id);

    /// Votes on a proposal.
    function vote(uint256 id, bool support) external;

    /// Re-checks whether a proposal is accepted.
    function recount(uint256 id) external returns (bool accepted);

    /// Cancels a proposal.
    function cancel(uint256 id) external;

    /// Executes a proposal.
    function execute(uint256 id, bytes calldata extraData) external;

    /// Reports a missed approval and flags the president as inactive.
    function expire(uint256 id) external;

    /// Stake manager governed by the council.
    function stakeManager() external view returns (IStakeManager);

    /// Staking token.
    function token() external view returns (IERC20);

    /// Referral program of the stake manager.
    function referralProgram() external view returns (IReferralProgram);

    /// Stake required to vote and to apply.
    function votingStake() external view returns (uint256);

    /// Fee paid to apply for membership.
    function membershipFee() external view returns (uint256);

    /// Current president.
    function president() external view returns (address);

    /// Remaining successors, next first.
    function successors() external view returns (address[] memory);

    /// Whether `account` is a remaining successor.
    function isSuccessor(address account) external view returns (bool);

    /// Whether the president opened an election.
    function voluntaryElection() external view returns (bool);

    /// Whether the president is flagged as inactive.
    function inactivityElection() external view returns (bool);

    /// Time of the president's last significant action.
    function lastSignificantActionAt() external view returns (uint256);

    /// Whether an election may be proposed.
    function hasElectionGround() external view returns (bool);

    /// Presidency state in one call.
    function presidency()
        external
        view
        returns (
            address president,
            address[] memory successors,
            bool voluntaryElection,
            bool inactivityElection,
            bool electionGround,
            uint256 lastSignificantActionAt
        );

    /// Council composition in one call.
    function membership()
        external
        view
        returns (uint256 seats, uint256 memberCount, uint256 requiredVotes, uint256 votingStake, uint256 membershipFee);

    /// Number of council seats.
    function seats() external view returns (uint256);

    /// Council members.
    function members() external view returns (address[] memory);

    /// Number of council members.
    function memberCount() external view returns (uint256);

    /// Number of free seats.
    function freeSeats() external view returns (uint256);

    /// Whether `account` is a council member.
    function isMember(address account) external view returns (bool);

    /// Whether `account` has paid the membership fee.
    function isApplicant(address account) external view returns (bool);

    /// Whether `account` is a member still in the newcomer period.
    function isNewcomer(address account) external view returns (bool);

    /// End of the newcomer period; zero for non-members.
    function votingFrom(address account) external view returns (uint256);

    /// Whether `account` may vote.
    function hasVotingRight(address account) external view returns (bool);

    /// Council data of `account` in one call.
    function councilAccount(address account) external view
    returns (bool member, bool applicant, uint256 votingFrom, bool enoughStake);

    /// Stake change hook for the stake manager.
    function onStakeChanged(address account, uint256 oldTotal, uint256 newTotal) external;

    /// Number of members with the voting right.
    function votingMemberCount() external view returns (uint256);

    /// Votes needed to accept a proposal now.
    function requiredVotes() external view returns (uint256);

    /// Rules of a proposal kind.
    function proposalRulesOf(ProposalKind kind) external pure returns (KindRules memory);

    /// Whether treasury proposals may use the pool.
    function isPoolAllowed(Dex dex, address token0, address token1, uint24 fee) external view returns (bool);

    /// State of a proposal.
    function state(uint256 id) external view returns (ProposalState);

    /// Proposal data.
    function getProposal(uint256 id) external view returns (ProposalView memory);

    /// Vote of `voter` on a proposal.
    function voteOf(uint256 id, address voter) external view returns (Vote);
}

project/contracts/interfaces/IDexTreasury.sol

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

import {Dex, Venue, MintParams, IncreaseParams, DecreaseParams} from "../types/Dex.sol";

/// Council-run liquidity operations on Uniswap v3 compatible DEXes.
interface IDexTreasury {
    /// A position opened.
    event PositionMinted(
        Dex indexed dex,
        uint256 indexed tokenId,
        address token0,
        address token1,
        uint24 fee,
        int24 tickLower,
        int24 tickUpper
    );

    /// Also emitted on mint.
    event LiquidityIncreased(Dex indexed dex, uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    /// Liquidity removed from a position.
    event LiquidityDecreased(
        Dex indexed dex,
        uint256 indexed tokenId,
        uint128 liquidity,
        uint256 amount0,
        uint256 amount1,
        uint256 fees0,
        uint256 fees1,
        bool burned
    );

    /// Fees collected from a position.
    event FeesCollected(Dex indexed dex, uint256 indexed tokenId, uint256 amount0, uint256 amount1);

    /// Sold amount and what is left under the cap changed.
    event DexSellLeftChanged(uint256 sold, uint256 left);

    error NotCouncil(address caller);
    error NoCouncil();
    error NoCode(address target);
    error ZeroDexAddress();
    error DexSellCapExceeded(uint256 sold, uint256 cap);
    error ZeroDexAmount();
    error UnsortedTokens(address token0, address token1);
    error PoolNotFound(address token0, address token1, uint24 fee);
    error ForeignPosition(uint256 tokenId, address owner);
    error InsufficientLiquidity(uint256 tokenId, uint128 available, uint128 requested);

    /// Opens a position on `dex`.
    function mintPosition(
        Dex dex,
        MintParams calldata params
    ) external returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    /// Adds liquidity to a position.
    function increaseLiquidity(
        Dex dex,
        IncreaseParams calldata params
    ) external returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    /// Removes liquidity and collects it with the fees.
    function decreaseLiquidity(
        Dex dex,
        DecreaseParams calldata params
    ) external returns (uint256 amount0, uint256 amount1, uint256 fees0, uint256 fees1, bool burned);

    /// Collects the fees of a position.
    function collectFees(Dex dex, uint256 tokenId) external returns (uint256 amount0, uint256 amount1);

    /// Account allowed to run treasury operations.
    function council() external view returns (address);

    /// Contracts of a venue.
    function venue(Dex dex) external view returns (Venue memory);

    /// Pool of a position.
    function poolOf(Dex dex, uint256 tokenId) external view returns (address token0, address token1, uint24 fee);

    /// Max net amount of the base token sold through DEXes.
    function dexSellCap() external view returns (uint256);

    /// Net amount of the base token sold through DEXes.
    function dexSold() external view returns (uint256);

    /// Amount left to sell under the cap.
    function dexSellLeft() external view returns (uint256);
}

project/contracts/interfaces/IOperatorLockable.sol

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

/// Ids that approved operators may lock for their owners.
interface IOperatorLockable {
    /// An operator approved.
    event OperatorApproved(address indexed owner, address indexed operator);

    /// An operator approval revoked.
    event OperatorApproveRevoked(address indexed owner, address indexed operator);

    /// An id locked.
    event Locked(uint256 indexed id, address indexed lockedFor, uint256 till);

    /// An id unlocked.
    event Unlocked(uint256 indexed id);

    error NotApproved(address owner, address operator);

    error AlreadyLocked(uint256 id);

    error LockTillInPast();

    error NonexistentId(uint256 id);

    error OperatorNotPermitted(address operator);

    /// Approves `operator` for all the caller's ids.
    function approveOperator(address operator) external;

    /// Revokes an operator approval.
    function revokeOperatorApprove(address owner, address operator) external;

    /// Whether `operator` is approved for `owner`.
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /// Locks `id` with no expiry.
    function lock(uint256 id) external;

    /// Locks `id` until `lockTill`.
    function lock(uint256 id, uint256 lockTill) external;

    /// Unlocks `id`.
    function unlock(uint256 id) external;

    /// Whether `id` is locked.
    function isLocked(uint256 id) external view returns (bool);

    /// When the lock on `id` expires.
    function lockTillOf(uint256 id) external view returns (uint256);

    /// Account `id` is locked for.
    function lockedForOf(uint256 id) external view returns (address);
}

project/contracts/interfaces/IReferralProgram.sol

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

import {IStakeHook} from "./IStakeHook.sol";
import {ITokenSource} from "./ITokenSource.sol";

/// Stake hook paying referral bonuses.
interface IReferralProgram is IStakeHook, ITokenSource {
    /// `Off` pays nobody, `WhitelistOnly` pays whitelisted referrers only, `On` pays everyone.
    enum ReferralMode {
        Off,
        WhitelistOnly,
        On
    }

    /// Referral bonus paid.
    event ReferralPaid(address indexed referrer, address indexed owner, uint256 amount);
    /// Referral mode switched.
    event ReferralModeChanged(ReferralMode oldMode, ReferralMode newMode);
    /// A referrer added to the whitelist.
    event Whitelisted(address indexed referrer);

    error ZeroAddress();
    error NotStakeManager(address caller);
    error NotCouncil(address caller);
    error StakeManagerAlreadySet(address stakeManager);
    error StakeManagerNotSet();
    error AddressWithoutCode(address address_);
    error SameReferralMode(ReferralMode mode);

    /// Wires the stake manager and renounces ownership.
    function setStakeManager(address stakeManager_) external;

    /// Switches the referral mode.
    function setMode(ReferralMode newMode) external;

    /// Current referral mode.
    function mode() external view returns (ReferralMode);

    /// Period after the first stake during which referrals are paid.
    function referralWindow() external view returns (uint256);

    /// Whether `referrer` is whitelisted.
    function isWhitelisted(address referrer) external view returns (bool);

    /// Total referral bonuses paid.
    function totalPaid() external view returns (uint256);

    /// Stake manager calling the hook.
    function stakeManager() external view returns (address);

    /// Balance left to pay referrals from.
    function available() external view returns (uint256);

    /// Referral rate of `referrer`, in basis points.
    function rateOf(address referrer) external view returns (uint256);

    /// Bonus `referrer` would earn on a stake of `amount`.
    function bonusFor(address referrer, uint256 amount) external view returns (uint256);
}

project/contracts/interfaces/IStakeHook.sol

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

/// Receiver of stake notifications.
interface IStakeHook {
    /// Called by the stake manager after each stake.
    function onStake(address owner, address referrer, uint256 amount, uint256 firstStakeAt) external;
}

project/contracts/interfaces/IStakeManager.sol

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

import {IOperatorLockable} from "./IOperatorLockable.sol";
import {IDexTreasury} from "./IDexTreasury.sol";
import {ITokenSource} from "./ITokenSource.sol";

/// Tiered staking with rewards; also the council-run treasury.
interface IStakeManager is IOperatorLockable, IDexTreasury, ITokenSource {
    struct StakeView {
        uint256 id;
        address owner;
        uint8 tier;
        uint256 amount;
        uint256 stakedAt;
        uint256 ownedAt;
        uint256 unstakeAt;
        uint256 lockedTill;
        address lockedFor;
    }

    struct AccountView {
        uint256 accruedNum;
        uint256 lastAccrualAt;
        uint256 lastClaimAt;
        uint256 firstStakeAt;
        uint256 stakeCount;
        uint256 stakedTotal;
    }

    struct TierInfo {
        uint8 tier;
        uint256 term;
        uint256 weight;
    }

    /// A stake id created.
    event StakeCreated(uint256 indexed id, address indexed owner);
    /// Data of a stake changed.
    event StakeChanged(uint256 indexed id);
    /// A stake id removed.
    event StakeRemoved(uint256 indexed id, address indexed owner);
    /// Tokens staked.
    event Staked(uint256 indexed id, address indexed owner, uint8 tier, uint256 amount);
    /// Tokens withdrawn from a stake; `left` stays staked.
    event Unstaked(uint256 indexed id, address indexed owner, uint8 tier, uint256 amount, uint256 left);
    /// A stake merged into `intoId`.
    event Merged(uint256 indexed id, uint256 indexed intoId, address indexed owner, uint8 tier, uint256 amount);

    /// A stake moved to a longer tier.
    event Upgraded(uint256 indexed id, address indexed owner, uint8 fromTier, uint8 toTier, uint256 amount, uint256 stakedAt);
    /// Part of a stake moved by the exchange.
    event Transferred(
        uint256 indexed id,
        uint256 indexed remainderId,
        address indexed from,
        address to,
        uint8 tier,
        uint256 amount,
        uint256 stakedAt,
        uint256 lockedTill
    );
    /// A stake returned by a buyback.
    event Returned(uint256 indexed id, address indexed from, address indexed to, uint8 tier, uint256 amount);
    /// Rewards paid out.
    event Claimed(address indexed owner, uint256 claimAmount);
    /// Free unstake granted or revoked.
    event FreeUnstakeSet(address indexed account, bool enabled);

    error InvalidTier(uint8 tier);
    error ZeroAmount();
    error ZeroAddress();
    error InvalidReceiver(address to);
    error NonexistentStake(uint256 id);
    error IncorrectOwner(uint256 id, address owner, address expected);
    error StakeLocked(uint256 id, uint256 lockedTill);
    error StakeNotLocked(uint256 id);
    error StillStaking(uint256 id, uint256 unstakeAt);
    error InsufficientStake(uint256 id, uint256 balance, uint256 needed);
    error TooManyStakes(address owner, uint256 max);
    error TierMismatch(uint256 id, uint8 tier, uint8 expected);
    error NotAnUpgrade(uint256 id, uint8 tier, uint8 newTier);
    error InvalidListLength(uint256 length, uint256 minimum);
    error ClaimTooEarly(address owner, uint256 availableAt);
    error NothingToClaim(address owner);
    error RewardsDepleted();
    error AddressWithoutCode(address address_);
    error TreasuryBelowStaked(uint256 balance, uint256 staked);
    error OnlyExchangeAccess();
    error NotClean(address account);
    error SameFreeUnstake(address account, bool enabled);

    /// Creates a stake.
    function stake(uint8 tier, uint256 amount, address referrer) external returns (uint256 id);

    /// Withdraws whole matured stakes.
    function unstake(uint256[] calldata ids) external returns (uint256 released);

    /// Withdraws part of a matured stake.
    function unstakeOne(uint256 id, uint256 amount) external;

    /// Merges same-tier stakes into a new one.
    function merge(uint256[] calldata ids) external returns (uint256 newId);

    /// Moves a stake to a longer tier.
    function upgrade(uint256 id, uint8 newTier) external;

    /// Pays out accrued rewards.
    function claim() external;

    /// Moves part of a stake to another account.
    function transferPart(address from, uint256 id, uint256 amount, address to) external returns (uint256 remainderId);

    /// Returns a stake locked by a buyback.
    function returnLocked(uint256 id) external;

    /// Grants or revokes free unstake for `account`.
    function setFreeUnstake(address account, bool enabled) external;

    /// Number of tiers.
    function TIERS() external view returns (uint8);

    /// Id the next stake will get.
    function nextStakeId() external view returns (uint256);

    /// Total amount staked.
    function totalStaked() external view returns (uint256);

    /// Number of active stakes.
    function activeStakes() external view returns (uint256);

    /// Total amount staked in a tier.
    function totalStakedIn(uint8 tier) external view returns (uint256);

    /// Number of active stakes in a tier.
    function activeStakesIn(uint8 tier) external view returns (uint256);

    /// Stake exchange allowed to move stakes.
    function stakeExchange() external view returns (address);

    /// Hook notified on each stake.
    function stakeHook() external view returns (address);

    /// Account data of `owner`.
    function getAccount(address owner) external view returns (AccountView memory);

    /// Total amount staked by `owner`.
    function totalStakedOf(address owner) external view returns (uint256 total);

    /// Amounts staked by `owner` per tier.
    function totalStakedByTierOf(address owner) external view returns (uint256[] memory);

    /// Rewards `owner` can claim.
    function pendingOf(address owner) external view returns (uint256);

    /// Amount staked by `owner` in a tier.
    function tierTotalOf(address owner, uint8 tier) external view returns (uint256);

    /// Term and weight of each tier.
    function tiers() external pure returns (TierInfo[] memory);

    /// Total amounts staked per tier.
    function totalStakedByTier() external view returns (uint256[] memory);

    /// Numbers of active stakes per tier.
    function activeStakesByTier() external view returns (uint256[] memory);

    /// When a stake can be withdrawn.
    function unstakeAtOf(uint256 id) external view returns (uint256);

    /// Stake data.
    function getStake(uint256 id) external view returns (StakeView memory);

    /// Data of several stakes.
    function getStakes(uint256[] calldata ids) external view returns (StakeView[] memory);

    /// Balance left to pay rewards from.
    function availableRewards() external view returns (uint256);

    /// Whether `account` has free unstake.
    function hasFreeUnstake(address account) external view returns (bool);

    /// Whether `account` has never held a stake.
    function isClean(address account) external view returns (bool);
}

project/contracts/interfaces/ITokenSource.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// A contract working with one primary token.
interface ITokenSource {
    /// Primary token of this contract.
    function token() external view returns (IERC20);
}

project/contracts/interfaces/external/uniswap-v3/INonfungiblePositionManager.sol

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

/// Uniswap v3 position manager (PancakeSwap v3 is ABI-identical).
interface INonfungiblePositionManager {
    /// Parameters of {mint}.
    struct MintParams {
        address token0;
        address token1;
        uint24 fee;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

    /// Parameters of {increaseLiquidity}.
    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// Parameters of {decreaseLiquidity}.
    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// Parameters of {collect}.
    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }

    /// Creates a position and mints its NFT to `recipient`.
    function mint(
        MintParams calldata params
    ) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    /// Adds liquidity to an existing position.
    function increaseLiquidity(
        IncreaseLiquidityParams calldata params
    ) external payable returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    /// Removes liquidity from a position.
    function decreaseLiquidity(
        DecreaseLiquidityParams calldata params
    ) external payable returns (uint256 amount0, uint256 amount1);

    /// Collects what the position is owed: released principal and fees.
    function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);

    /// Burns an empty position.
    function burn(uint256 tokenId) external payable;

    /// Owner of a position.
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /// Full data of a position.
    function positions(
        uint256 tokenId
    )
        external
        view
        returns (
            uint96 nonce,
            address operator,
            address token0,
            address token1,
            uint24 fee,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );
}

project/contracts/interfaces/external/uniswap-v3/IUniswapV3Factory.sol

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

/// Uniswap v3 factory (PancakeSwap v3 is ABI-identical).
interface IUniswapV3Factory {
    /// Returns the pool for a pair and fee tier, zero when none exists.
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}

project/contracts/libraries/UniswapV3.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {IDexTreasury} from "../interfaces/IDexTreasury.sol";
import {INonfungiblePositionManager} from "../interfaces/external/uniswap-v3/INonfungiblePositionManager.sol";
import {
    Venue,
    MintParams,
    IncreaseParams,
    DecreaseParams,
    IncreaseResult,
    DecreaseResult
} from "../types/Dex.sol";

library UniswapV3 {
    using SafeERC20 for IERC20;

    function tokensOf(Venue memory venue, uint256 tokenId) internal view returns (address token0, address token1) {
        (, , token0, token1, , , , , , , , ) = venue.positionManager.positions(tokenId);
    }

    function poolOf(Venue memory venue, uint256 tokenId) internal view returns (address token0, address token1, uint24 fee) {
        (, , token0, token1, fee, , , , , , , ) = venue.positionManager.positions(tokenId);
    }

    function mint(
        Venue memory venue,
        MintParams calldata params
    ) internal returns (IncreaseResult memory result) {
        require(params.token0 < params.token1, IDexTreasury.UnsortedTokens(params.token0, params.token1));
        _requirePool(venue, params.token0, params.token1, params.fee);

        address spender = address(venue.positionManager);
        IERC20(params.token0).forceApprove(spender, params.amount0Desired);
        IERC20(params.token1).forceApprove(spender, params.amount1Desired);

        (result.tokenId, result.liquidity, result.amount0, result.amount1) = venue.positionManager.mint(
            INonfungiblePositionManager.MintParams({
                token0: params.token0,
                token1: params.token1,
                fee: params.fee,
                tickLower: params.tickLower,
                tickUpper: params.tickUpper,
                amount0Desired: params.amount0Desired,
                amount1Desired: params.amount1Desired,
                amount0Min: params.amount0Min,
                amount1Min: params.amount1Min,
                recipient: address(this),
                deadline: block.timestamp
            })
        );

        IERC20(params.token0).forceApprove(spender, 0);
        IERC20(params.token1).forceApprove(spender, 0);

        result.token0 = params.token0;
        result.token1 = params.token1;
    }

    function increaseLiquidity(
        Venue memory venue,
        IncreaseParams calldata params
    ) internal returns (IncreaseResult memory result) {
        _requireOwned(venue, params.tokenId);
        (result.token0, result.token1) = tokensOf(venue, params.tokenId);

        address spender = address(venue.positionManager);
        IERC20(result.token0).forceApprove(spender, params.amount0Desired);
        IERC20(result.token1).forceApprove(spender, params.amount1Desired);

        (result.liquidity, result.amount0, result.amount1) = venue.positionManager.increaseLiquidity(
            INonfungiblePositionManager.IncreaseLiquidityParams({
                tokenId: params.tokenId,
                amount0Desired: params.amount0Desired,
                amount1Desired: params.amount1Desired,
                amount0Min: params.amount0Min,
                amount1Min: params.amount1Min,
                deadline: block.timestamp
            })
        );

        result.tokenId = params.tokenId;

        IERC20(result.token0).forceApprove(spender, 0);
        IERC20(result.token1).forceApprove(spender, 0);
    }

    function decreaseLiquidity(
        Venue memory venue,
        DecreaseParams calldata params
    ) internal returns (DecreaseResult memory result) {
        require(params.liquidity != 0, IDexTreasury.ZeroDexAmount());
        _requireOwned(venue, params.tokenId);

        uint128 available;
        (, , result.token0, result.token1, , , , available, , , , ) = venue.positionManager.positions(params.tokenId);
        require(
            params.liquidity <= available,
            IDexTreasury.InsufficientLiquidity(params.tokenId, available, params.liquidity)
        );

        (result.amount0, result.amount1) = venue.positionManager.decreaseLiquidity(
            INonfungiblePositionManager.DecreaseLiquidityParams({
                tokenId: params.tokenId,
                liquidity: params.liquidity,
                amount0Min: params.amount0Min,
                amount1Min: params.amount1Min,
                deadline: block.timestamp
            })
        );

        (uint256 collected0, uint256 collected1) = _collectAll(venue, params.tokenId);
        result.fees0 = collected0 - result.amount0;
        result.fees1 = collected1 - result.amount1;

        if (params.liquidity == available) {
            venue.positionManager.burn(params.tokenId);
            result.burned = true;
        }

        result.tokenId = params.tokenId;
    }

    function collect(Venue memory venue, uint256 tokenId) internal returns (uint256 amount0, uint256 amount1) {
        _requireOwned(venue, tokenId);
        (amount0, amount1) = _collectAll(venue, tokenId);
    }

    function _collectAll(Venue memory venue, uint256 tokenId) private returns (uint256 amount0, uint256 amount1) {
        (amount0, amount1) = venue.positionManager.collect(
            INonfungiblePositionManager.CollectParams({
                tokenId: tokenId,
                recipient: address(this),
                amount0Max: type(uint128).max,
                amount1Max: type(uint128).max
            })
        );
    }

    function _requireOwned(Venue memory venue, uint256 tokenId) private view {
        address owner = venue.positionManager.ownerOf(tokenId);
        require(owner == address(this), IDexTreasury.ForeignPosition(tokenId, owner));
    }

    function _requirePool(Venue memory venue, address token0, address token1, uint24 fee) private view {
        require(
            venue.factory.getPool(token0, token1, fee) != address(0),
            IDexTreasury.PoolNotFound(token0, token1, fee)
        );
    }
}

project/contracts/types/Dex.sol

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

import {IUniswapV3Factory} from "../interfaces/external/uniswap-v3/IUniswapV3Factory.sol";
import {INonfungiblePositionManager} from "../interfaces/external/uniswap-v3/INonfungiblePositionManager.sol";

enum Dex {
    Uniswap,
    Pancake
}

struct Venue {
    IUniswapV3Factory factory;
    INonfungiblePositionManager positionManager;
}

struct MintParams {
    address token0;
    address token1;
    uint24 fee;
    int24 tickLower;
    int24 tickUpper;
    uint256 amount0Desired;
    uint256 amount1Desired;
    uint256 amount0Min;
    uint256 amount1Min;
}

struct IncreaseParams {
    uint256 tokenId;
    uint256 amount0Desired;
    uint256 amount1Desired;
    uint256 amount0Min;
    uint256 amount1Min;
}

struct DecreaseParams {
    uint256 tokenId;
    uint128 liquidity;
    uint256 amount0Min;
    uint256 amount1Min;
}

struct IncreaseResult {
    uint256 tokenId;
    address token0;
    address token1;
    uint128 liquidity;
    uint256 amount0;
    uint256 amount1;
}

struct DecreaseResult {
    uint256 tokenId;
    address token0;
    address token1;
    uint256 amount0;
    uint256 amount1;
    uint256 fees0;
    uint256 fees1;
    bool burned;
}
Compiler settingsShow
{
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": [
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.