MON Price: $0.018794 (+2.59%)

Contract

0xc6721b0b0dC86D7481A6E6888f8bB865F2BF15ca

Overview

MON Balance

Monad Chain LogoMonad Chain LogoMonad Chain Logo0 MON

MON Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
RiskStore

Compiler Version
v0.8.17+commit.8df45f5f

Optimization Enabled:
Yes with 200 runs

Other Settings:
london EvmVersion
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import {DataStore} from "./DataStore.sol";
import {PoolStore} from "./PoolStore.sol";
import {PositionStore} from "./PositionStore.sol";

import "./Roles.sol";

/// @title RiskStore
/// @notice Implementation of risk mitigation measures such as maximum open interest and maximum pool drawdown
contract RiskStore is Roles {
    // Constants
    uint256 public constant BPS_DIVIDER = 10000;

    mapping(string => mapping(address => uint256)) private maxOI; // market => asset => amount

    // Pool Risk Measures
    uint256 public poolHourlyDecay; // bps = 4.16% hourly, disappears after 24 hours
    mapping(address => int256) private poolProfitTracker; // asset => amount (amortized)
    mapping(address => uint256) private poolProfitLimit; // asset => bps
    mapping(address => uint256) private poolLastChecked; // asset => timestamp

    // Contracts
    DataStore public DS;

    /// @dev Initialize DataStore address
    function initialize(address rs, address ds) external initializer {
        DS = DataStore(ds);
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
        poolHourlyDecay = 416;
    }

    // V2 Delta Long-Short
    mapping(string => mapping(address => uint256)) private maxDelta; // market => asset => amount

    // V3 Max Position Size
    uint256 private maxPositionSizeFactor; // 10000 = 100%

    // V4 ADL
    mapping(address => uint256) private adlThreshold; // asset => threshold (bps)

    /// @notice Set maximum delta between longs and shorts
    /// @dev Only callable by governance
    /// @param market Market to set, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    /// @param amount Max delta to set
    function setMaxDelta(
        string calldata market,
        address asset,
        uint256 amount
    ) external onlyGov {
        require(amount > 0, "!amount");
        maxDelta[market][asset] = amount;
    }

    /// @notice Set maximum open interest
    /// @notice Once current open interest exceeds this value, orders are no longer accepted
    /// @dev Only callable by governance
    /// @param market Market to set, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    /// @param amount Max open interest to set
    function setMaxOI(
        string calldata market,
        address asset,
        uint256 amount
    ) external onlyGov {
        require(amount > 0, "!amount");
        maxOI[market][asset] = amount;
    }

    /// @notice Set maximum position size factor
    /// @dev Only callable by governance
    /// @param factor Max position size factor
    function setMaxPositionSizeFactor(uint256 factor) external onlyGov {
        maxPositionSizeFactor = factor;
    }

    /// @notice Set hourly pool decay
    /// @dev Only callable by governance
    /// @param bps Hourly pool decay in bps
    function setPoolHourlyDecay(uint256 bps) external onlyGov {
        require(bps < BPS_DIVIDER, "!bps");
        poolHourlyDecay = bps;
    }

    /// @notice Set pool profit limit of `asset`
    /// @dev Only callable by governance
    /// @param asset Address of asset, e.g. address(0) for ETH
    /// @param bps Pool profit limit in bps
    function setPoolProfitLimit(address asset, uint256 bps) external onlyGov {
        require(bps < BPS_DIVIDER, "!bps");
        poolProfitLimit[asset] = bps;
    }

    /// @notice Set ADL threshold of `asset`
    /// @dev Only callable by governance
    /// @param asset Address of asset, e.g. address(0) for ETH
    /// @param bps ADL threshold in bps
    function setADLThreshold(address asset, uint256 bps) external onlyGov {
        require(bps < BPS_DIVIDER, "!bps");
        adlThreshold[asset] = bps;
    }

    /// @notice Measures the net loss of a pool over time
    /// @notice Reverts if time-weighted drawdown is higher than the allowed profit limit
    /// @dev Only callable by other protocol contracts
    /// @dev Invoked by Positions.decreasePosition
    function checkPoolDrawdown(
        address asset,
        int256 pnl
    ) external onlyContract {
        // Get available amount of `asset` in the pool (pool balance + buffer balance)
        uint256 poolAvailable = PoolStore(DS.getAddress("PoolStore"))
            .getAvailable(asset);

        // Get profit tracker, pnl > 0 means trader win
        int256 profitTracker = getPoolProfitTracker(asset) + pnl;
        // get profit limit of pool
        uint256 profitLimit = poolProfitLimit[asset];

        // update storage vars
        poolProfitTracker[asset] = profitTracker;
        poolLastChecked[asset] = block.timestamp;

        // return if profit limit or profit tracker is zero / less than zero
        if (profitLimit == 0 || profitTracker <= 0) return;

        // revert if profitTracker > profitLimit * available funds
        require(
            uint256(profitTracker) <
                (profitLimit * poolAvailable) / BPS_DIVIDER,
            "!pool-risk"
        );
    }

    /// @notice Checks if maximum delta and maximum open interest are reached
    /// @param asset Address of base asset, e.g. address(0) for ETH
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param size Size of the position
    /// @param isLong Whether position is long (true) or short (false)
    function checkMaxDelta(
        address asset,
        string calldata market,
        uint256 size,
        bool isLong
    ) external view {
        // Get current OI values
        uint256 oiLong = PositionStore(DS.getAddress("PositionStore"))
            .getOILong(asset, market);
        uint256 oiShort = PositionStore(DS.getAddress("PositionStore"))
            .getOIShort(asset, market);
        uint256 _maxDelta = maxDelta[market][asset];

        if (_maxDelta > 0) {
            if (isLong) {
                // available long = maxDelta - oiLong + oiShort
                int256 availableLong = int256(_maxDelta) -
                    int256(oiLong) +
                    int256(oiShort);
                if (availableLong < 0) {
                    availableLong = 0;
                }
                require(size <= uint256(availableLong), "!max-delta");
            } else {
                // available short = maxDelta + oiLong - oiShort
                int256 availableShort = int256(_maxDelta) +
                    int256(oiLong) -
                    int256(oiShort);
                if (availableShort < 0) {
                    availableShort = 0;
                }
                require(size <= uint256(availableShort), "!max-delta");
            }
        }

        // Check max OI
        // uint256 openInterest = PositionStore(DS.getAddress('PositionStore')).getOI(asset, market);
        uint256 openInterest = oiLong + oiShort;
        uint256 _maxOI = maxOI[market][asset];
        if (_maxOI > 0 && openInterest + size > _maxOI) revert("!max-oi");
    }

    /// @notice Checks if maximum open interest is reached
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    function checkMaxOI(
        address asset,
        string calldata market,
        uint256 size
    ) external view {
        uint256 openInterest = PositionStore(DS.getAddress("PositionStore"))
            .getOI(asset, market);
        uint256 _maxOI = maxOI[market][asset];
        if (_maxOI > 0 && openInterest + size > _maxOI) revert("!max-oi");
    }

    /// @notice Get maximum position size of `market`
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    function getMaxPositionSize(
        string calldata market,
        address asset
    ) external view returns (uint256) {
        return (maxOI[market][asset] * maxPositionSizeFactor) / 10000;
    }

    /// @notice Checks if maximum position size is reached
    /// @param asset Address of base asset, e.g. address(0) for ETH
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param sizeToAdd Size of the position to add
    /// @param currentSize Current size of the position
    /// @param isLongOrder Whether the order is long or short
    /// @param isLongPosition Whether the position is long or short
    function checkMaxPositionSize(
        address asset,
        string calldata market,
        uint256 sizeToAdd,
        uint256 currentSize,
        bool isLongOrder,
        bool isLongPosition
    ) external view {
        if (maxPositionSizeFactor == 0) return;
        uint256 maxPositionSize = (maxOI[market][asset] *
            maxPositionSizeFactor) / 10000;
        uint256 newSize;
        if (currentSize == 0) {
            newSize = sizeToAdd;
        } else if (isLongOrder == isLongPosition) {
            newSize = currentSize + sizeToAdd;
        } else {
            newSize = currentSize > sizeToAdd
                ? currentSize - sizeToAdd
                : sizeToAdd - currentSize;
        }
        require(newSize <= maxPositionSize, "!max-position-size");
    }

    /// @notice Get maximum delta of `market`
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    function getMaxDelta(
        string calldata market,
        address asset
    ) external view returns (uint256) {
        return maxDelta[market][asset];
    }

    /// @notice Get maximum open interest of `market`
    /// @param market Market to check, e.g. "ETH-USD"
    /// @param asset Address of base asset, e.g. address(0) for ETH
    function getMaxOI(
        string calldata market,
        address asset
    ) external view returns (uint256) {
        return maxOI[market][asset];
    }

    /// @notice Returns pool profit tracker of `asset`
    /// @dev Amortized every hour by 4.16% unless otherwise set
    function getPoolProfitTracker(address asset) public view returns (int256) {
        int256 profitTracker = poolProfitTracker[asset];
        uint256 lastCheckedHourId = poolLastChecked[asset] / (1 hours);
        uint256 currentHourId = block.timestamp / (1 hours);

        if (currentHourId > lastCheckedHourId) {
            // hours passed since last check
            uint256 hoursPassed = currentHourId - lastCheckedHourId;
            if (hoursPassed >= BPS_DIVIDER / poolHourlyDecay) {
                profitTracker = 0;
            } else {
                // reduce profit tracker by `poolHourlyDecay` for every hour that passed since last check
                for (uint256 i = 0; i < hoursPassed; i++) {
                    profitTracker *=
                        (int256(BPS_DIVIDER) - int256(poolHourlyDecay)) /
                        int256(BPS_DIVIDER);
                }
            }
        }

        return profitTracker;
    }

    /// @notice Returns pool profit limit of `asset`
    function getPoolProfitLimit(address asset) external view returns (uint256) {
        return poolProfitLimit[asset];
    }

    /// @notice Get ADL threshold of `asset`
    /// @param asset Address of asset, e.g. address(0) for ETH
    function getADLThreshold(address asset) external view returns (uint256) {
        return adlThreshold[asset];
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

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

/// @title DataStore
/// @notice General purpose storage contract
/// @dev Access is restricted to governance
contract DataStore is Governable {
    // Key-value stores
    mapping(bytes32 => uint256) public uintValues;
    mapping(bytes32 => int256) public intValues;
    mapping(bytes32 => address) public addressValues;
    mapping(bytes32 => bytes32) public dataValues;
    mapping(bytes32 => bool) public boolValues;
    mapping(bytes32 => string) public stringValues;

    function initialize() external initializer {
        _setGov(msg.sender);
    }

    /// @param key The key for the record
    /// @param value value to store
    /// @param overwrite Overwrites existing value if set to true
    function setUint(
        string calldata key,
        uint256 value,
        bool overwrite
    ) external onlyGov returns (bool) {
        bytes32 hash = getHash(key);
        if (overwrite || uintValues[hash] == 0) {
            uintValues[hash] = value;
            return true;
        }
        return false;
    }

    /// @param key The key for the record
    function getUint(string calldata key) external view returns (uint256) {
        return uintValues[getHash(key)];
    }

    /// @param key The key for the record
    /// @param value value to store
    /// @param overwrite Overwrites existing value if set to true
    function setInt(
        string calldata key,
        int256 value,
        bool overwrite
    ) external onlyGov returns (bool) {
        bytes32 hash = getHash(key);
        if (overwrite || intValues[hash] == 0) {
            intValues[hash] = value;
            return true;
        }
        return false;
    }

    /// @param key The key for the record
    function getInt(string calldata key) external view returns (int256) {
        return intValues[getHash(key)];
    }

    /// @param key The key for the record
    /// @param value address to store
    /// @param overwrite Overwrites existing value if set to true
    function setAddress(
        string calldata key,
        address value,
        bool overwrite
    ) external onlyGov returns (bool) {
        bytes32 hash = getHash(key);
        if (overwrite || addressValues[hash] == address(0)) {
            addressValues[hash] = value;
            return true;
        }
        return false;
    }

    /// @param key The key for the record
    function getAddress(string calldata key) external view returns (address) {
        return addressValues[getHash(key)];
    }

    /// @param key The key for the record
    /// @param value byte value to store
    function setData(
        string calldata key,
        bytes32 value
    ) external onlyGov returns (bool) {
        dataValues[getHash(key)] = value;
        return true;
    }

    /// @param key The key for the record
    function getData(string calldata key) external view returns (bytes32) {
        return dataValues[getHash(key)];
    }

    /// @param key The key for the record
    /// @param value value to store (true / false)
    function setBool(
        string calldata key,
        bool value
    ) external onlyGov returns (bool) {
        boolValues[getHash(key)] = value;
        return true;
    }

    /// @param key The key for the record
    function getBool(string calldata key) external view returns (bool) {
        return boolValues[getHash(key)];
    }

    /// @param key The key for the record
    /// @param value string to store
    function setString(
        string calldata key,
        string calldata value
    ) external onlyGov returns (bool) {
        stringValues[getHash(key)] = value;
        return true;
    }

    /// @param key The key for the record
    function getString(
        string calldata key
    ) external view returns (string memory) {
        return stringValues[getHash(key)];
    }

    /// @param key string to hash
    function getHash(string memory key) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(key));
    }
}

File 3 of 10 : PoolStore.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./Roles.sol";

/// @title PoolStore
/// @notice Persistent storage for Pool.sol
contract PoolStore is Roles {
    // Constants
    uint256 public constant BPS_DIVIDER = 10000;

    // State variables
    uint256 public feeShare;
    uint256 public depositId;
    uint256[] public lockupPeriods;

    mapping(address => uint256) private clpSupply; // asset => clp supply

    mapping(address => uint256) private balances; // asset => balance
    mapping(address => mapping(address => uint256)) private userClpBalances; // asset => account => clp amount

    mapping(address => mapping(address => uint256[]))
        private depositIdsForAccount; // account => asset => [depositIds..]
    mapping(uint256 => uint256) private depositClpBalances; // depositId => clp balance
    mapping(uint256 => uint256) private depositTimestamps; // depositId => timestamp

    mapping(address => uint256) private bufferBalances; // asset => balance
    mapping(address => uint256) private lastPaid; // asset => timestamp

    mapping(address => uint256) private bufferPayoutPeriods; // asset => period

    // Custom fees (deposit/withdraw) configuration
    mapping(address => bool) private customWithdrawalTaxesActive; // asset => is custom withdrawal tax active
    mapping(address => uint256) private withdrawalTaxes; // asset => custom withdrawal tax bps

    mapping(address => bool) private customDepositTaxesUnlocked; // asset => is custom deposit tax unlocked
    mapping(address => bool) private customDepositTaxesLocked; // asset => is custom deposit tax locked
    mapping(address => uint256) private depositTaxesUnlocked; // asset => custom deposit tax bps for unlocked deposits
    mapping(address => uint256) private depositTaxLocked; // asset => custom deposit tax bps for locked deposits

    function initialize(
        address rs,
        uint256[] calldata periods
    ) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
        feeShare = 5000;
        depositId = 0;
        for (uint256 i = 0; i < periods.length; i++) {
            lockupPeriods.push(periods[i]);
        }
    }

    /// @notice Set pool fee
    /// @dev Only callable by governance
    /// @param bps fee share in bps
    function setFeeShare(uint256 bps) external onlyGov {
        require(bps < BPS_DIVIDER, "!bps");
        feeShare = bps;
    }

    /// @notice Set lockup periods
    /// @dev Only callable by governance
    /// @param periods Lockup periods in seconds (can include 0 for no lockup)
    function setLockupPeriods(uint256[] calldata periods) external onlyGov {
        require(periods.length > 0, "!length");

        delete lockupPeriods;
        for (uint256 i = 0; i < periods.length; i++) {
            lockupPeriods.push(periods[i]);
        }
    }

    /// @notice Set buffer payout periods
    /// @dev Only callable by governance
    /// @param assets Assets
    /// @param periods Buffer payout periods in seconds
    function setBufferPayoutPeriods(
        address[] calldata assets,
        uint256[] calldata periods
    ) external onlyGov {
        require(periods.length == assets.length, "!length");
        for (uint256 i = 0; i < assets.length; i++) {
            require(periods[i] > 0, "!period");
            bufferPayoutPeriods[assets[i]] = periods[i];
        }
    }

    /// @notice Returns buffer payout period for an asset
    /// @param asset Asset
    /// @return Buffer payout period in seconds
    function getBufferPayoutPeriod(
        address asset
    ) external view returns (uint256) {
        return bufferPayoutPeriods[asset];
    }

    /// @notice Enable/disable custom deposit tax for an asset
    /// @param _isActive Whether custom deposit tax is active
    /// @param asset Asset address
    function setCustomDepositTaxesLocked(
        bool _isActive,
        address asset
    ) external onlyGov {
        customDepositTaxesLocked[asset] = _isActive;
    }

    /// @notice Set custom deposit tax (in bps) for an asset
    /// @param asset Asset address
    /// @param tax Custom deposit tax in bps
    function setDepositTaxLocked(address asset, uint256 tax) external onlyGov {
        require(tax < BPS_DIVIDER, "!tax");
        depositTaxLocked[asset] = tax;
    }

    /// @notice Enable/disable custom deposit tax for an asset
    /// @param _isActive Whether custom deposit tax is active
    /// @param asset Asset address
    function setCustomDepositTaxesUnlocked(
        bool _isActive,
        address asset
    ) external onlyGov {
        customDepositTaxesUnlocked[asset] = _isActive;
    }

    /// @notice Set custom deposit tax (in bps) for an asset
    /// @param asset Asset address
    /// @param tax Custom deposit tax in bps
    function setDepositTaxUnlocked(
        address asset,
        uint256 tax
    ) external onlyGov {
        require(tax < BPS_DIVIDER, "!tax");
        depositTaxesUnlocked[asset] = tax;
    }

    /// @notice Returns whether custom deposit tax (locked) is active for an asset
    /// @param asset Asset address
    function isCustomDepositTaxesLockedActive(
        address asset
    ) external view returns (bool) {
        return customDepositTaxesLocked[asset];
    }

    /// @notice Returns whether custom deposit tax (unlocked) is active for an asset
    /// @param asset Asset address
    function isCustomDepositTaxesUnlockedActive(
        address asset
    ) external view returns (bool) {
        return customDepositTaxesUnlocked[asset];
    }

    /// @notice Returns custom deposit tax (in bps) for an asset
    /// @param asset Asset address
    function getDepositTaxLocked(
        address asset
    ) external view returns (uint256) {
        return depositTaxLocked[asset];
    }

    /// @notice Returns custom deposit tax (in bps) for an asset
    /// @param asset Asset address
    function getDepositTaxUnlocked(
        address asset
    ) external view returns (uint256) {
        return depositTaxesUnlocked[asset];
    }

    /// @notice Enable/disable custom withdrawal tax for an asset
    /// @param _isActive Whether custom withdrawal tax is active
    /// @param asset Asset address
    function setCustomWithdrawalTaxes(
        bool _isActive,
        address asset
    ) external onlyGov {
        customWithdrawalTaxesActive[asset] = _isActive;
    }

    /// @notice Set custom withdrawal tax (in bps) for an asset
    /// @param asset Asset address
    /// @param tax Custom withdrawal tax in bps
    function setWithdrawalTax(address asset, uint256 tax) external onlyGov {
        withdrawalTaxes[asset] = tax;
    }

    /// @notice Returns whether custom withdrawal tax is active for an asset
    /// @param asset Asset address
    function isCustomWithdrawalTaxesActive(
        address asset
    ) external view returns (bool) {
        return customWithdrawalTaxesActive[asset];
    }

    /// @notice Returns custom withdrawal tax (bps) for an asset
    /// @param asset Asset address
    function getWithdrawalTax(address asset) external view returns (uint256) {
        return withdrawalTaxes[asset];
    }

    /// @notice Increments pool balance
    /// @dev Only callable by other protocol contracts
    function incrementBalance(
        address asset,
        uint256 amount
    ) external onlyContract {
        balances[asset] += amount;
    }

    /// @notice Decrements pool balance
    /// @dev Only callable by other protocol contracts
    function decrementBalance(
        address asset,
        uint256 amount
    ) external onlyContract {
        balances[asset] = balances[asset] <= amount
            ? 0
            : balances[asset] - amount;
    }

    /// @notice Increments buffer balance
    /// @dev Only callable by other protocol contracts
    function incrementBufferBalance(
        address asset,
        uint256 amount
    ) external onlyContract {
        bufferBalances[asset] += amount;
    }

    /// @notice Decrements buffer balance
    /// @dev Only callable by other protocol contracts
    function decrementBufferBalance(
        address asset,
        uint256 amount
    ) external onlyContract {
        bufferBalances[asset] = bufferBalances[asset] <= amount
            ? 0
            : bufferBalances[asset] - amount;
    }

    /// @notice Updates `lastPaid`
    /// @dev Only callable by other protocol contracts
    function setLastPaid(
        address asset,
        uint256 timestamp
    ) external onlyContract {
        lastPaid[asset] = timestamp;
    }

    /// @notice Increments `clpSupply`, `userClpBalances` and `depositIdsForAccount`
    /// @dev Only callable by other protocol contracts
    /// @param asset Asset
    /// @param user User
    /// @param amount Amount
    /// @param lockupPeriodIndex Lockup period index
    /// @return depositId Deposit ID
    /// @return lockupPeriod Lockup period
    function incrementUserClpBalance(
        address asset,
        address user,
        uint256 amount,
        uint256 lockupPeriodIndex
    ) external onlyContract returns (uint256, uint256) {
        require(amount > 0, "!amount");
        require(
            lockupPeriodIndex < lockupPeriods.length,
            "!lockup-period-index"
        );
        clpSupply[asset] += amount;
        userClpBalances[asset][user] += amount;

        uint256 lockupPeriod = lockupPeriods[lockupPeriodIndex];
        uint256 currentDepositId = depositId;
        depositIdsForAccount[user][asset].push(currentDepositId);
        depositClpBalances[currentDepositId] = amount;
        if (lockupPeriod > 0) {
            depositTimestamps[currentDepositId] =
                block.timestamp +
                lockupPeriod;
        } else {
            depositTimestamps[currentDepositId] = 0;
        }

        unchecked {
            depositId++;
        }

        return (currentDepositId, lockupPeriod);
    }

    /// @notice Decrements `clpSupply` and `userClpBalances`
    /// @dev Only callable by other protocol contracts
    /// @param asset Asset
    /// @param user User
    /// @param amount Amount
    /// @return depositIds Array of deposit IDs
    /// @return amounts Array of deposit amounts
    function decrementUserClpBalance(
        address asset,
        address user,
        uint256 amount
    ) external onlyContract returns (uint256[] memory, uint256[] memory) {
        require(amount > 0, "!amount");
        clpSupply[asset] = clpSupply[asset] <= amount
            ? 0
            : clpSupply[asset] - amount;

        userClpBalances[asset][user] = userClpBalances[asset][user] <= amount
            ? 0
            : userClpBalances[asset][user] - amount;

        uint256[] storage userDeposits = depositIdsForAccount[user][asset];
        uint256 len = userDeposits.length;
        uint256[] memory depositIds = new uint256[](len);
        uint256[] memory amounts = new uint256[](len);
        uint256 remainingAmount = amount;
        uint256 writeIndex = 0;
        uint256 upd = 0;

        for (uint256 i = 0; i < len; i++) {
            uint256 dId = userDeposits[i];
            uint256 depositBalance = depositClpBalances[dId];
            uint256 depositTimestamp = depositTimestamps[dId];

            if (depositBalance > 0) {
                bool isUnlocked = block.timestamp >= depositTimestamp;

                if (isUnlocked && remainingAmount > 0) {
                    if (depositBalance > remainingAmount) {
                        uint256 newBal = depositBalance - remainingAmount;
                        depositClpBalances[dId] = newBal;
                        remainingAmount = 0;
                        if (writeIndex != i) {
                            userDeposits[writeIndex] = dId;
                        }
                        writeIndex++;
                        depositIds[upd] = dId;
                        amounts[upd] = newBal;
                        upd++;
                    } else {
                        remainingAmount -= depositBalance;
                        depositIds[upd] = dId;
                        amounts[upd] = 0;
                        delete depositClpBalances[dId];
                        delete depositTimestamps[dId];
                        upd++;
                    }
                } else {
                    if (writeIndex != i) {
                        userDeposits[writeIndex] = dId;
                    }
                    writeIndex++;
                }
            }
        }

        while (userDeposits.length > writeIndex) {
            userDeposits.pop();
        }

        require(remainingAmount == 0, "!locked-amount");

        assembly {
            mstore(depositIds, upd)
            mstore(amounts, upd)
        }

        return (depositIds, amounts);
    }

    /// @notice Reset lockup timestamp for a deposit
    /// @dev Only callable by governance
    /// @param _depositId Deposit ID
    function resetLockupTimestamp(uint256 _depositId) external onlyGov {
        depositTimestamps[_depositId] = 0;
    }

    /// @notice Returns the sum of buffer and pool balance of `asset`
    /// @param asset Asset address
    /// @return Available balance
    function getAvailable(address asset) external view returns (uint256) {
        return balances[asset] + bufferBalances[asset];
    }

    /// @notice Returns amount of `asset` in pool
    /// @param asset Asset address
    /// @return Balance
    function getBalance(address asset) external view returns (uint256) {
        return balances[asset];
    }

    /// @notice Returns amount of `asset` in buffer
    /// @param asset Asset address
    /// @return Buffer balance
    function getBufferBalance(address asset) external view returns (uint256) {
        return bufferBalances[asset];
    }

    /// @notice Returns pool balances of `_assets`
    /// @param _assets Assets
    /// @return Balances
    function getBalances(
        address[] calldata _assets
    ) external view returns (uint256[] memory) {
        uint256 length = _assets.length;
        uint256[] memory _balances = new uint256[](length);

        for (uint256 i = 0; i < length; i++) {
            _balances[i] = balances[_assets[i]];
        }

        return _balances;
    }

    /// @notice Returns buffer balances of `_assets`
    /// @param _assets Assets
    /// @return Balances
    function getBufferBalances(
        address[] calldata _assets
    ) external view returns (uint256[] memory) {
        uint256 length = _assets.length;
        uint256[] memory _balances = new uint256[](length);

        for (uint256 i = 0; i < length; i++) {
            _balances[i] = bufferBalances[_assets[i]];
        }

        return _balances;
    }

    /// @notice Returns last time pool was paid
    /// @param asset Asset address
    /// @return Last paid timestamp
    function getLastPaid(address asset) external view returns (uint256) {
        return lastPaid[asset];
    }

    /// @notice Returns `asset` balance of `account`
    /// @param asset Asset address
    /// @param account User address
    /// @return Balance
    function getUserBalance(
        address asset,
        address account
    ) public view returns (uint256) {
        if (clpSupply[asset] == 0) return 0;
        return
            (userClpBalances[asset][account] * balances[asset]) /
            clpSupply[asset];
    }

    /// @notice Returns `_assets` balance of `account`
    /// @param _assets Assets
    /// @param account User address
    /// @return Balances
    function getUserBalances(
        address[] calldata _assets,
        address account
    ) external view returns (uint256[] memory) {
        uint256 length = _assets.length;
        uint256[] memory _balances = new uint256[](length);

        for (uint256 i = 0; i < length; i++) {
            _balances[i] = getUserBalance(_assets[i], account);
        }

        return _balances;
    }

    /// @notice Returns `asset` balances of multiple `accounts`
    /// @param asset Asset address
    /// @param accounts User addresses
    /// @return Balances
    function getUsersBalances(
        address asset,
        address[] calldata accounts
    ) external view returns (uint256[] memory) {
        uint256[] memory _balances = new uint256[](accounts.length);
        for (uint256 i = 0; i < accounts.length; i++) {
            _balances[i] = getUserBalance(asset, accounts[i]);
        }
        return _balances;
    }

    /// @notice Returns total amount of CLP for `asset`
    /// @param asset Asset address
    /// @return CLP supply
    function getClpSupply(address asset) public view returns (uint256) {
        return clpSupply[asset];
    }

    /// @notice Returns amount of CLP of `account` for `asset`
    /// @param asset Asset address
    /// @param account User address
    /// @return CLP amount
    function getUserClpBalance(
        address asset,
        address account
    ) public view returns (uint256) {
        return userClpBalances[asset][account];
    }

    /// @notice Returns CLP balances of `accounts` for `asset`
    /// @param asset Asset address
    /// @param accounts User addresses
    /// @return clpAmounts CLP amounts
    function getUsersClpBalances(
        address asset,
        address[] calldata accounts
    ) external view returns (uint256[] memory clpAmounts) {
        uint256 len = accounts.length;
        clpAmounts = new uint256[](len);
        for (uint256 i = 0; i < len; i++) {
            clpAmounts[i] = userClpBalances[asset][accounts[i]];
        }

        return clpAmounts;
    }

    /// @notice Returns deposit IDs for a user and asset
    /// @param user User address
    /// @param asset Asset address
    /// @return Deposit IDs
    function getDepositIdsForAccount(
        address user,
        address asset
    ) external view returns (uint256[] memory) {
        return depositIdsForAccount[user][asset];
    }

    /// @notice Returns deposit info for a specific deposit ID
    /// @param dId Deposit ID
    /// @return balance Deposit balance
    /// @return timestamp Deposit timestamp
    function getDepositInfo(
        uint256 dId
    ) external view returns (uint256 balance, uint256 timestamp) {
        return (depositClpBalances[dId], depositTimestamps[dId]);
    }

    /// @notice Returns the amount of unlocked CLP for a user
    /// @param asset Asset address
    /// @param account User address
    /// @return Unlocked CLP amount
    function getUnlockedClpBalance(
        address asset,
        address account
    ) external view returns (uint256) {
        uint256[] memory userDeposits = depositIdsForAccount[account][asset];
        uint256 unlockedAmount = 0;

        for (uint256 i = 0; i < userDeposits.length; i++) {
            uint256 dId = userDeposits[i];
            uint256 depositBalance = depositClpBalances[dId];
            uint256 unlockTimestamp = depositTimestamps[dId];

            if (depositBalance > 0 && block.timestamp >= unlockTimestamp) {
                unlockedAmount += depositBalance;
            }
        }

        return unlockedAmount;
    }

    /// @notice Returns the amount of locked CLP for a user
    /// @param asset Asset address
    /// @param account User address
    /// @return Locked CLP amount
    function getLockedClpBalance(
        address asset,
        address account
    ) external view returns (uint256) {
        uint256[] memory userDeposits = depositIdsForAccount[account][asset];
        uint256 lockedAmount = 0;

        for (uint256 i = 0; i < userDeposits.length; i++) {
            uint256 dId = userDeposits[i];
            uint256 depositBalance = depositClpBalances[dId];
            uint256 unlockTimestamp = depositTimestamps[dId];

            if (depositBalance > 0 && block.timestamp < unlockTimestamp) {
                lockedAmount += depositBalance;
            }
        }

        return lockedAmount;
    }

    // @notice Returns lockup period for a given index
    /// @param index Lockup period index
    /// @return Lockup period in seconds
    function getLockupPeriod(uint256 index) external view returns (uint256) {
        return lockupPeriods[index];
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./EnumerableSet.sol";

import "./Roles.sol";

/// @title PositionStore
/// @notice Persistent storage for Positions.sol
contract PositionStore is Roles {
    // Libraries
    using EnumerableSet for EnumerableSet.Bytes32Set;

    // Position struct
    struct Position {
        address user; // User that submitted the position
        address asset; // Asset address, e.g. address(0) for ETH
        string market; // Market this position was submitted on
        bool isLong; // Wether the position is long or short
        uint256 size; // The position's size (margin * leverage)
        uint256 margin; // Collateral tied to this position. In wei
        int256 fundingTracker; // Market funding rate tracker
        uint256 price; // The position's average execution price
        uint256 timestamp; // Time at which the position was created
    }

    // Constants
    uint256 public constant BPS_DIVIDER = 10000;
    uint256 public constant MAX_KEEPER_FEE_SHARE = 2000; // 20%

    // State variables
    uint256 public removeMarginBuffer;
    uint256 public keeperFeeShare;

    // Mappings
    mapping(address => mapping(string => uint256)) private OI; // open interest. market => asset => amount
    mapping(address => mapping(string => uint256)) private OILong; // open interest. market => asset => amount
    mapping(address => mapping(string => uint256)) private OIShort; // open interest. market => asset => amount]

    mapping(bytes32 => Position) private positions; // key = asset,user,market
    EnumerableSet.Bytes32Set private positionKeys; // [position keys..]
    mapping(address => EnumerableSet.Bytes32Set) private positionKeysForUser; // user => [position keys..]

    function initialize(address rs) external initializer {
        roleStore = RoleStore(rs);
        _setGov(msg.sender);
        removeMarginBuffer = 1000;
        keeperFeeShare = 500;
    }

    /// @notice Updates `removeMarginBuffer`
    /// @dev Only callable by governance
    /// @param bps new `removeMarginBuffer` in bps
    function setRemoveMarginBuffer(uint256 bps) external onlyGov {
        require(bps < BPS_DIVIDER, "!bps");
        removeMarginBuffer = bps;
    }

    /// @notice Sets keeper fee share
    /// @dev Only callable by governance
    /// @param bps new `keeperFeeShare` in bps
    function setKeeperFeeShare(uint256 bps) external onlyGov {
        require(bps <= MAX_KEEPER_FEE_SHARE, "!keeper-fee-share");
        keeperFeeShare = bps;
    }

    /// @notice Adds new position or updates exisiting one
    /// @dev Only callable by other protocol contracts
    /// @param position Position to add/update
    function addOrUpdate(Position memory position) external onlyContract {
        bytes32 key = _getPositionKey(
            position.user,
            position.asset,
            position.market
        );
        positions[key] = position;
        positionKeysForUser[position.user].add(key);
        positionKeys.add(key);
    }

    /// @notice Removes position
    /// @dev Only callable by other protocol contracts
    function remove(
        address user,
        address asset,
        string calldata market
    ) external onlyContract {
        bytes32 key = _getPositionKey(user, asset, market);
        positionKeysForUser[user].remove(key);
        positionKeys.remove(key);
        delete positions[key];
    }

    /// @notice Increments open interest
    /// @dev Only callable by other protocol contracts
    /// @dev Invoked by Positions.increasePosition
    function incrementOI(
        address asset,
        string calldata market,
        uint256 amount,
        bool isLong
    ) external onlyContract {
        OI[asset][market] += amount;
        if (isLong) {
            OILong[asset][market] += amount;
        } else {
            OIShort[asset][market] += amount;
        }
    }

    /// @notice Decrements open interest
    /// @dev Only callable by other protocol contracts
    /// @dev Invoked whenever a position is closed or decreased
    function decrementOI(
        address asset,
        string calldata market,
        uint256 amount,
        bool isLong
    ) external onlyContract {
        OI[asset][market] = OI[asset][market] <= amount
            ? 0
            : OI[asset][market] - amount;
        if (isLong) {
            OILong[asset][market] = OILong[asset][market] <= amount
                ? 0
                : OILong[asset][market] - amount;
        } else {
            OIShort[asset][market] = OIShort[asset][market] <= amount
                ? 0
                : OIShort[asset][market] - amount;
        }
    }

    /// @notice Returns open interest of `asset` and `market`
    function getOI(
        address asset,
        string calldata market
    ) external view returns (uint256) {
        return OILong[asset][market] + OIShort[asset][market];
    }

    /// @notice Sets open interest of long positions
    function setOILong(
        address asset,
        string calldata market,
        uint256 amount
    ) external onlyGov {
        OILong[asset][market] = amount;
    }

    /// @notice Sets open interest of short positions
    function setOIShort(
        address asset,
        string calldata market,
        uint256 amount
    ) external onlyGov {
        OIShort[asset][market] = amount;
    }

    /// @notice Returns open interest of long positions
    function getOILong(
        address asset,
        string calldata market
    ) external view returns (uint256) {
        return OILong[asset][market];
    }

    /// @notice Returns open interest of short positions
    function getOIShort(
        address asset,
        string calldata market
    ) external view returns (uint256) {
        return OIShort[asset][market];
    }

    /// @notice Returns position of `user`
    /// @param asset Base asset of position
    /// @param market Market this position was submitted on
    function getPosition(
        address user,
        address asset,
        string memory market
    ) public view returns (Position memory) {
        bytes32 key = _getPositionKey(user, asset, market);
        return positions[key];
    }

    /// @notice Returns positions of `users`
    /// @param assets Base assets of positions
    /// @param markets Markets of positions
    function getPositions(
        address[] calldata users,
        address[] calldata assets,
        string[] calldata markets
    ) external view returns (Position[] memory) {
        uint256 length = users.length;
        Position[] memory _positions = new Position[](length);

        for (uint256 i = 0; i < length; i++) {
            _positions[i] = getPosition(users[i], assets[i], markets[i]);
        }

        return _positions;
    }

    /// @notice Returns positions
    /// @param keys Position keys
    function getPositions(
        bytes32[] calldata keys
    ) external view returns (Position[] memory) {
        uint256 length = keys.length;
        Position[] memory _positions = new Position[](length);

        for (uint256 i = 0; i < length; i++) {
            _positions[i] = positions[keys[i]];
        }

        return _positions;
    }

    /// @notice Returns number of positions
    function getPositionCount() external view returns (uint256) {
        return positionKeys.length();
    }

    /// @notice Returns `length` amount of positions starting from `offset`
    function getPositions(
        uint256 length,
        uint256 offset
    ) external view returns (Position[] memory) {
        uint256 _length = positionKeys.length();
        require(offset <= _length, "Offset out of bounds");

        uint256 availableLength = _length - offset;
        uint256 resultLength = length > availableLength
            ? availableLength
            : length;
        Position[] memory _positions = new Position[](resultLength);

        for (uint256 i = 0; i < resultLength; i++) {
            _positions[i] = positions[positionKeys.at(i + offset)];
        }

        return _positions;
    }

    /// @notice Returns all positions of `user`
    function getUserPositions(
        address user
    ) external view returns (Position[] memory) {
        uint256 length = positionKeysForUser[user].length();
        Position[] memory _positions = new Position[](length);

        for (uint256 i = 0; i < length; i++) {
            _positions[i] = positions[positionKeysForUser[user].at(i)];
        }

        return _positions;
    }

    /// @dev Returns position key by hashing (user, asset, market)
    function _getPositionKey(
        address user,
        address asset,
        string memory market
    ) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(user, asset, market));
    }
}

File 5 of 10 : Roles.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./Governable.sol";
import "./RoleStore.sol";

/// @title Roles
/// @notice Role-based access control mechanism via onlyContract modifier
abstract contract Roles is Governable {
    bytes32 internal constant CONTRACT_ROLE = keccak256("CONTRACT");

    RoleStore public roleStore;

    /// @dev Reverts if caller address has not the contract role
    modifier onlyContract() {
        require(roleStore.hasRole(msg.sender, CONTRACT_ROLE), "!contract-role");
        _;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

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

/// @title Governable
/// @notice Basic access control mechanism, gov has access to certain functions
abstract contract Governable is Initializable {
    address public gov;

    event SetGov(address prevGov, address nextGov);

    /// @dev Reverts if called by any account other than gov
    modifier onlyGov() {
        require(msg.sender == gov, "!gov");
        _;
    }

    /// @notice Sets a new governance address
    /// @dev Only callable by governance
    function setGov(address _gov) external onlyGov {
        _setGov(_gov);
    }

    /// @notice Sets a new governance address
    /// @dev Internal function without access restriction
    function _setGov(address _gov) internal {
        require(_gov != address(0), "!zero-gov");
        address prevGov = gov;
        gov = _gov;
        emit SetGov(prevGov, _gov);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity 0.8.17;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 *  Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable.
 *  See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 *  In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(
        Set storage set,
        bytes32 value
    ) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(
        Set storage set,
        uint256 index
    ) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(
        Bytes32Set storage set,
        bytes32 value
    ) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(
        Bytes32Set storage set,
        bytes32 value
    ) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(
        Bytes32Set storage set,
        bytes32 value
    ) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(
        Bytes32Set storage set,
        uint256 index
    ) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(
        Bytes32Set storage set
    ) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(
        AddressSet storage set,
        address value
    ) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(
        AddressSet storage set,
        address value
    ) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(
        AddressSet storage set,
        address value
    ) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(
        AddressSet storage set,
        uint256 index
    ) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(
        AddressSet storage set
    ) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(
        UintSet storage set,
        uint256 value
    ) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(
        UintSet storage set,
        uint256 value
    ) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(
        UintSet storage set,
        uint256 index
    ) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(
        UintSet storage set
    ) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "./EnumerableSet.sol";
import "./Governable.sol";

/**
 * @title  RoleStore
 * @notice Role-based access control mechanism. Governance can grant and
 *         revoke roles dynamically via {grantRole} and {revokeRole}
 */
contract RoleStore is Governable {
    // Libraries
    using EnumerableSet for EnumerableSet.AddressSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;

    event RoleGranted(
        bytes32 indexed role,
        address indexed account,
        address indexed sender
    );
    event RoleRevoked(
        bytes32 indexed role,
        address indexed account,
        address indexed sender
    );

    // Set of roles
    EnumerableSet.Bytes32Set internal roles;

    // Role -> address
    mapping(bytes32 => EnumerableSet.AddressSet) internal roleMembers;

    function initialize() external initializer {
        _setGov(msg.sender);
    }

    /// @notice Grants `role` to `account`
    /// @dev Only callable by governance
    function grantRole(address account, bytes32 role) external onlyGov {
        // add role if not already present
        if (!roles.contains(role)) roles.add(role);

        require(roleMembers[role].add(account));
        emit RoleGranted(role, account, msg.sender);
    }

    /// @notice Revokes `role` from `account`
    /// @dev Only callable by governance
    function revokeRole(address account, bytes32 role) external onlyGov {
        require(roleMembers[role].remove(account));
        emit RoleRevoked(role, account, msg.sender);

        // Remove role if it has no longer any members
        if (roleMembers[role].length() == 0) {
            roles.remove(role);
        }
    }

    /// @notice Returns `true` if `account` has been granted `role`
    function hasRole(
        address account,
        bytes32 role
    ) external view returns (bool) {
        return roleMembers[role].contains(account);
    }

    /// @notice Returns number of roles
    function getRoleCount() external view returns (uint256) {
        return roles.length();
    }
}

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

pragma solidity ^0.8.2;

import "../../utils/Address.sol";

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

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

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

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

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

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

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

    /**
     * @dev Internal function that returns the initialized version. Returns `_initialized`
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Internal function that returns the initialized version. Returns `_initializing`
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

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

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

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

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

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

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

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

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

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

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

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

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

Settings
{
  "remappings": [
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "chainlink/=node_modules/@chainlink/",
    "pyth-sdk-solidity/=node_modules/@pythnetwork/pyth-sdk-solidity/",
    "@uniswap/v2-periphery/=node_modules/@uniswap/v2-periphery/",
    "@uniswap/v2-core/=node_modules/@uniswap/v2-core/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs"
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "london",
  "viaIR": true
}

Contract Security Audit

Contract ABI

API
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"prevGov","type":"address"},{"indexed":false,"internalType":"address","name":"nextGov","type":"address"}],"name":"SetGov","type":"event"},{"inputs":[],"name":"BPS_DIVIDER","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DS","outputs":[{"internalType":"contract DataStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"string","name":"market","type":"string"},{"internalType":"uint256","name":"size","type":"uint256"},{"internalType":"bool","name":"isLong","type":"bool"}],"name":"checkMaxDelta","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"string","name":"market","type":"string"},{"internalType":"uint256","name":"size","type":"uint256"}],"name":"checkMaxOI","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"string","name":"market","type":"string"},{"internalType":"uint256","name":"sizeToAdd","type":"uint256"},{"internalType":"uint256","name":"currentSize","type":"uint256"},{"internalType":"bool","name":"isLongOrder","type":"bool"},{"internalType":"bool","name":"isLongPosition","type":"bool"}],"name":"checkMaxPositionSize","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"int256","name":"pnl","type":"int256"}],"name":"checkPoolDrawdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"}],"name":"getADLThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"market","type":"string"},{"internalType":"address","name":"asset","type":"address"}],"name":"getMaxDelta","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"market","type":"string"},{"internalType":"address","name":"asset","type":"address"}],"name":"getMaxOI","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"market","type":"string"},{"internalType":"address","name":"asset","type":"address"}],"name":"getMaxPositionSize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"}],"name":"getPoolProfitLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"}],"name":"getPoolProfitTracker","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gov","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"rs","type":"address"},{"internalType":"address","name":"ds","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"poolHourlyDecay","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"roleStore","outputs":[{"internalType":"contract RoleStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"uint256","name":"bps","type":"uint256"}],"name":"setADLThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_gov","type":"address"}],"name":"setGov","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"market","type":"string"},{"internalType":"address","name":"asset","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"setMaxDelta","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"market","type":"string"},{"internalType":"address","name":"asset","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"setMaxOI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"factor","type":"uint256"}],"name":"setMaxPositionSizeFactor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"bps","type":"uint256"}],"name":"setPoolHourlyDecay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"uint256","name":"bps","type":"uint256"}],"name":"setPoolProfitLimit","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60808060405234610016576113f6908161001c8239f35b600080fdfe608060408181526004918236101561001657600080fd5b600092833560e01c91826312d43a5114610cb457508163228706a314610c7057816329aebed314610c385781632c547a8814610bdf5781632db7dc9914610bc05781633c2e0fa714610b675781634242bac014610b3e5781634519fcbc14610afa578163485cc955146109985781634a4a7b041461096f57816362b3866f146108145781636b1a7657146107e75781637c4283bc146107ca5781638d2860e81461078c578163965f21761461075b578163a396264e14610708578163b525a2df1461069c578163c9d2d0b214610664578163cc2b308614610317578163cfad57a2146102db578163e3af01bb146101ca57508063e8a2c221146101775763fe3d95e91461012257600080fd5b3461017357806003193601126101735761013a610d0e565b906024359160018060a01b039061015882865460101c163314610dae565b6101656127108510610eb9565b168352600a60205282205580f35b5080fd5b5034610173576127106101c2826020948561019136610d24565b92909182865193849283376002908201908152030190206001600160a01b0390911682528652205460095490610f74565b049051908152f35b9050346102d757816003193601126102d7576101e4610d0e565b600154835163ac4ab3fb60e01b815233848201527fa66b7a3e6b19d24ccb6f717fc232a1bb0278a7f83f8e2211835fc4ed0fe69f19602482015291939190602090829060449082906001600160a01b03165afa9081156102cd57859161028f575b501561025b578361025860243585610f87565b80f35b906020606492519162461bcd60e51b8352820152600e60248201526d21636f6e74726163742d726f6c6560901b6044820152fd5b90506020813d82116102c5575b816102a960209383610eeb565b810103126102c1575180151581036102c15738610245565b8480fd5b3d915061029c565b82513d87823e3d90fd5b8280fd5b8334610314576020366003190112610314576102586102f8610d0e565b61030f60018060a01b03845460101c163314610dae565b610de0565b80fd5b919050346102d75760803660031901126102d757610333610d0e565b60243567ffffffffffffffff81116102c1576103529036908501610cdb565b90916044359160643590878215158303610314576103939260018060a01b038060075416895163bf40fac160e01b908181528c818060209a8b938201611103565b0381865afa908115610637578b859493928f8f978d918c9a998e968d95610641575b506103d390519b8c96879586946301d25add60e21b8652850161112b565b0392165afa94851561063757918d918d8a9489986105fa575b5090610405949392915180958194829383528201611103565b03915afa9081156105bd578a83928a8f958f968b9998978d968c956105c7575b5061044390519a8b96879586946312e1541b60e31b8652850161112b565b0392165afa9384156105bd5787949392918b8d928896610583575b5091610497969785949287948b84519182378a818d810160088152030190209c169b8c8252895220549081610516575b505050506111b3565b958288519384928337810160028152030190209187525282852054908115159283610502575b5050506104c8578280f35b6104fe92505191829162461bcd60e51b83528201606090602081526007602082015266216d61782d6f6960c81b60408201520190565b0390fd5b61050d9293506111b3565b113880806104bd565b156105515761052d9261052891611161565b610f42565b8c811261054a575b6105419089111561117a565b8082388061048e565b508b610535565b6105639261055e91610f42565b611161565b8c811261057c575b6105779089111561117a565b610541565b508b61056b565b9396925050935081813d83116105b6575b61059e8183610eeb565b810103126102c15751869390928b908b61049761045e565b503d610594565b8b513d87823e3d90fd5b6104439195506105ec90883d8a116105f3575b6105e48183610eeb565b810190610f23565b9490610425565b503d6105da565b97505091509185813d8311610630575b6106148183610eeb565b8101031261062c5793519387918d918d6104056103ec565b8580fd5b503d61060a565b8c513d88823e3d90fd5b6103d391955061065d90883d8a116105f3576105e48183610eeb565b94906103b5565b5050346101735760203660031901126101735760209181906001600160a01b0361068c610d0e565b168152600a845220549051908152f35b8390346101735760c0366003190112610173576106b7610d0e565b906024359067ffffffffffffffff8211610704576106d791369101610cdb565b91906084359081151582036102c15760a43592831515840361062c576102589460643592604435926111cd565b8380fd5b505034610173578060031936011261017357610722610d0e565b906024359160018060a01b039061074082865460101c163314610dae565b61074d6127108510610eb9565b168352600560205282205580f35b8390346101735760203660031901126101735761078560018060a01b03835460101c163314610dae565b3560095580f35b83903461017357602036600319011261017357356107b760018060a01b03835460101c163314610dae565b6107c46127108210610eb9565b60035580f35b505034610173578160031936011261017357602090516127108152f35b5050346101735760203660031901126101735760209061080d610808610d0e565b6112a5565b9051908152f35b919050346102d75760603660031901126102d757610830610d0e565b60243567ffffffffffffffff81116102c15761084f9036908501610cdb565b600754845163bf40fac160e01b81529193926020926001600160a01b039284908290851681806108808d8201611103565b03915afa908115610948578287939286928c91610952575b5087868c6108b98d519c8d96879586946339589adb60e21b8652850161112b565b0392165afa958615610948578996610915575b50839082885193849283378101600281520301902092168652528184205480151591826108fe575b50506104c8578280f35b61090d919250604435906111b3565b1138806108f4565b9095508381813d8311610941575b61092d8183610eeb565b8101031261093d575194836108cc565b8880fd5b503d610923565b87513d8b823e3d90fd5b6109699150833d85116105f3576105e48183610eeb565b38610898565b50503461017357816003193601126101735760015490516001600160a01b039091168152602090f35b9050346102d757816003193601126102d7576109b2610d0e565b6001600160a01b03602435818116929083900361062c57855460ff8160081c161594858096610aed575b8015610ad6575b15610a7c575060ff198116600117875584610a6b575b506bffffffffffffffffffffffff60a01b9283600754161760075516906001541617600155610a2733610de0565b6101a0600355610a35575080f35b60207f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989161ff001984541684555160018152a180f35b61ffff1916610101178655386109f9565b608490602088519162461bcd60e51b8352820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152fd5b50303b1580156109e35750600160ff8316146109e3565b50600160ff8316106109dc565b505034610173578060209283610b0f36610d24565b92909182865193849283376008908201908152030190206001600160a01b039091168252845220549051908152f35b50503461017357816003193601126101735760075490516001600160a01b039091168152602090f35b50503461017357610b7736610d67565b93929091602060018060a01b0392610b9684895460101c163314610dae565b610ba1871515610e83565b8286519384928337810160088152030190209116845260205282205580f35b5050346101735781600319360112610173576020906003549051908152f35b50503461017357610bef36610d67565b93929091602060018060a01b0392610c0e84895460101c163314610dae565b610c19871515610e83565b8286519384928337810160028152030190209116845260205282205580f35b5050346101735760203660031901126101735760209181906001600160a01b03610c60610d0e565b1681526005845220549051908152f35b505034610173578060209283610c8536610d24565b92909182865193849283376002908201908152030190206001600160a01b039091168252845220549051908152f35b849034610173578160031936011261017357905460101c6001600160a01b03168152602090f35b9181601f84011215610d095782359167ffffffffffffffff8311610d095760208381860195010111610d0957565b600080fd5b600435906001600160a01b0382168203610d0957565b6040600319820112610d09576004359067ffffffffffffffff8211610d0957610d4f91600401610cdb565b90916024356001600160a01b0381168103610d095790565b6060600319820112610d09576004359067ffffffffffffffff8211610d0957610d9291600401610cdb565b90916024356001600160a01b0381168103610d09579060443590565b15610db557565b606460405162461bcd60e51b815260206004820152600460248201526310b3b7bb60e11b6044820152fd5b6001600160a01b03818116918215610e52576000805462010000600160b01b03198116601093841b62010000600160b01b031617909155604080519190921c909216825260208201929092527f53351836099c03ffc3b1727d8abd4b0222afa87d4ed76ae3102d51369ef7f7859190a1565b60405162461bcd60e51b815260206004820152600960248201526810bd32b93796b3b7bb60b91b6044820152606490fd5b15610e8a57565b60405162461bcd60e51b815260206004820152600760248201526608585b5bdd5b9d60ca1b6044820152606490fd5b15610ec057565b606460405162461bcd60e51b81526020600482015260046024820152632162707360e01b6044820152fd5b90601f8019910116810190811067ffffffffffffffff821117610f0d57604052565b634e487b7160e01b600052604160045260246000fd5b90816020910312610d0957516001600160a01b0381168103610d095790565b91909160008382019384129112908015821691151617610f5e57565b634e487b7160e01b600052601160045260246000fd5b81810292918115918404141715610f5e57565b9060018060a01b038060075416604092835194859263bf40fac160e01b845283606460209889938460048301526009602483015268506f6f6c53746f726560b81b60448301525afa9283156110d85786906000946110e3575b5060249394865194858092631e9abd8160e11b825280861698896004840152165afa9283156110d8576000936110a7575b509061052861101f926112a5565b9160005260058452826000205460048552828460002055600685524284600020558015801561109c575b611095576127109161105a91610f74565b041115611065575050565b60649250519062461bcd60e51b82526004820152600a60248201526921706f6f6c2d7269736b60b01b6044820152fd5b5050505050565b506000831315611049565b90928682813d83116110d1575b6110be8183610eeb565b8101031261031457505191610528611011565b503d6110b4565b85513d6000823e3d90fd5b602494506110fd90823d84116105f3576105e48183610eeb565b93610fe0565b60609060208152600d60208201526c506f736974696f6e53746f726560981b60408201520190565b9192606093819260018060a01b0316845260406020850152816040850152848401376000828201840152601f01601f1916010190565b81810392916000138015828513169184121617610f5e57565b1561118157565b60405162461bcd60e51b815260206004820152600a602482015269216d61782d64656c746160b01b6044820152606490fd5b91908201809211610f5e57565b91908203918211610f5e57565b9592949560095490811561129b5783602061121294612710966040519384928337810160028152030190209060018060a01b0316600052602052604060002054610f74565b04936000918361126257505050505b1161122857565b60405162461bcd60e51b8152602060048201526012602482015271216d61782d706f736974696f6e2d73697a6560701b6044820152606490fd5b15159015151460001461127f57509061127a916111b3565b611221565b5081811115611292579061127a916111c0565b61127a916111c0565b5050505050505050565b60009060018060a01b031681526004806020526040822054906006602052610e10806040852054049042048181116112e0575b505050905090565b906112ea916111c0565b906003549182156113ad576127109280840482106113115750505050505b803880806112d8565b85929193949594838282039212818312811690828413901516179105600160ff1b8114915b8587106113495750505050505050611308565b90919293949596816113875782810290848782121661139a578082058414901517156113875796600019811461138757600101959493929190611336565b634e487b7160e01b865260118552602486fd5b634e487b7160e01b875260118652602487fd5b634e487b7160e01b855260128252602485fdfea26469706673582212206806efae11f6535fe1fcfe4533e673605c58d502c64c2ac84bb7196e09b09e4964736f6c63430008110033

Deployed Bytecode

0x608060408181526004918236101561001657600080fd5b600092833560e01c91826312d43a5114610cb457508163228706a314610c7057816329aebed314610c385781632c547a8814610bdf5781632db7dc9914610bc05781633c2e0fa714610b675781634242bac014610b3e5781634519fcbc14610afa578163485cc955146109985781634a4a7b041461096f57816362b3866f146108145781636b1a7657146107e75781637c4283bc146107ca5781638d2860e81461078c578163965f21761461075b578163a396264e14610708578163b525a2df1461069c578163c9d2d0b214610664578163cc2b308614610317578163cfad57a2146102db578163e3af01bb146101ca57508063e8a2c221146101775763fe3d95e91461012257600080fd5b3461017357806003193601126101735761013a610d0e565b906024359160018060a01b039061015882865460101c163314610dae565b6101656127108510610eb9565b168352600a60205282205580f35b5080fd5b5034610173576127106101c2826020948561019136610d24565b92909182865193849283376002908201908152030190206001600160a01b0390911682528652205460095490610f74565b049051908152f35b9050346102d757816003193601126102d7576101e4610d0e565b600154835163ac4ab3fb60e01b815233848201527fa66b7a3e6b19d24ccb6f717fc232a1bb0278a7f83f8e2211835fc4ed0fe69f19602482015291939190602090829060449082906001600160a01b03165afa9081156102cd57859161028f575b501561025b578361025860243585610f87565b80f35b906020606492519162461bcd60e51b8352820152600e60248201526d21636f6e74726163742d726f6c6560901b6044820152fd5b90506020813d82116102c5575b816102a960209383610eeb565b810103126102c1575180151581036102c15738610245565b8480fd5b3d915061029c565b82513d87823e3d90fd5b8280fd5b8334610314576020366003190112610314576102586102f8610d0e565b61030f60018060a01b03845460101c163314610dae565b610de0565b80fd5b919050346102d75760803660031901126102d757610333610d0e565b60243567ffffffffffffffff81116102c1576103529036908501610cdb565b90916044359160643590878215158303610314576103939260018060a01b038060075416895163bf40fac160e01b908181528c818060209a8b938201611103565b0381865afa908115610637578b859493928f8f978d918c9a998e968d95610641575b506103d390519b8c96879586946301d25add60e21b8652850161112b565b0392165afa94851561063757918d918d8a9489986105fa575b5090610405949392915180958194829383528201611103565b03915afa9081156105bd578a83928a8f958f968b9998978d968c956105c7575b5061044390519a8b96879586946312e1541b60e31b8652850161112b565b0392165afa9384156105bd5787949392918b8d928896610583575b5091610497969785949287948b84519182378a818d810160088152030190209c169b8c8252895220549081610516575b505050506111b3565b958288519384928337810160028152030190209187525282852054908115159283610502575b5050506104c8578280f35b6104fe92505191829162461bcd60e51b83528201606090602081526007602082015266216d61782d6f6960c81b60408201520190565b0390fd5b61050d9293506111b3565b113880806104bd565b156105515761052d9261052891611161565b610f42565b8c811261054a575b6105419089111561117a565b8082388061048e565b508b610535565b6105639261055e91610f42565b611161565b8c811261057c575b6105779089111561117a565b610541565b508b61056b565b9396925050935081813d83116105b6575b61059e8183610eeb565b810103126102c15751869390928b908b61049761045e565b503d610594565b8b513d87823e3d90fd5b6104439195506105ec90883d8a116105f3575b6105e48183610eeb565b810190610f23565b9490610425565b503d6105da565b97505091509185813d8311610630575b6106148183610eeb565b8101031261062c5793519387918d918d6104056103ec565b8580fd5b503d61060a565b8c513d88823e3d90fd5b6103d391955061065d90883d8a116105f3576105e48183610eeb565b94906103b5565b5050346101735760203660031901126101735760209181906001600160a01b0361068c610d0e565b168152600a845220549051908152f35b8390346101735760c0366003190112610173576106b7610d0e565b906024359067ffffffffffffffff8211610704576106d791369101610cdb565b91906084359081151582036102c15760a43592831515840361062c576102589460643592604435926111cd565b8380fd5b505034610173578060031936011261017357610722610d0e565b906024359160018060a01b039061074082865460101c163314610dae565b61074d6127108510610eb9565b168352600560205282205580f35b8390346101735760203660031901126101735761078560018060a01b03835460101c163314610dae565b3560095580f35b83903461017357602036600319011261017357356107b760018060a01b03835460101c163314610dae565b6107c46127108210610eb9565b60035580f35b505034610173578160031936011261017357602090516127108152f35b5050346101735760203660031901126101735760209061080d610808610d0e565b6112a5565b9051908152f35b919050346102d75760603660031901126102d757610830610d0e565b60243567ffffffffffffffff81116102c15761084f9036908501610cdb565b600754845163bf40fac160e01b81529193926020926001600160a01b039284908290851681806108808d8201611103565b03915afa908115610948578287939286928c91610952575b5087868c6108b98d519c8d96879586946339589adb60e21b8652850161112b565b0392165afa958615610948578996610915575b50839082885193849283378101600281520301902092168652528184205480151591826108fe575b50506104c8578280f35b61090d919250604435906111b3565b1138806108f4565b9095508381813d8311610941575b61092d8183610eeb565b8101031261093d575194836108cc565b8880fd5b503d610923565b87513d8b823e3d90fd5b6109699150833d85116105f3576105e48183610eeb565b38610898565b50503461017357816003193601126101735760015490516001600160a01b039091168152602090f35b9050346102d757816003193601126102d7576109b2610d0e565b6001600160a01b03602435818116929083900361062c57855460ff8160081c161594858096610aed575b8015610ad6575b15610a7c575060ff198116600117875584610a6b575b506bffffffffffffffffffffffff60a01b9283600754161760075516906001541617600155610a2733610de0565b6101a0600355610a35575080f35b60207f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989161ff001984541684555160018152a180f35b61ffff1916610101178655386109f9565b608490602088519162461bcd60e51b8352820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152fd5b50303b1580156109e35750600160ff8316146109e3565b50600160ff8316106109dc565b505034610173578060209283610b0f36610d24565b92909182865193849283376008908201908152030190206001600160a01b039091168252845220549051908152f35b50503461017357816003193601126101735760075490516001600160a01b039091168152602090f35b50503461017357610b7736610d67565b93929091602060018060a01b0392610b9684895460101c163314610dae565b610ba1871515610e83565b8286519384928337810160088152030190209116845260205282205580f35b5050346101735781600319360112610173576020906003549051908152f35b50503461017357610bef36610d67565b93929091602060018060a01b0392610c0e84895460101c163314610dae565b610c19871515610e83565b8286519384928337810160028152030190209116845260205282205580f35b5050346101735760203660031901126101735760209181906001600160a01b03610c60610d0e565b1681526005845220549051908152f35b505034610173578060209283610c8536610d24565b92909182865193849283376002908201908152030190206001600160a01b039091168252845220549051908152f35b849034610173578160031936011261017357905460101c6001600160a01b03168152602090f35b9181601f84011215610d095782359167ffffffffffffffff8311610d095760208381860195010111610d0957565b600080fd5b600435906001600160a01b0382168203610d0957565b6040600319820112610d09576004359067ffffffffffffffff8211610d0957610d4f91600401610cdb565b90916024356001600160a01b0381168103610d095790565b6060600319820112610d09576004359067ffffffffffffffff8211610d0957610d9291600401610cdb565b90916024356001600160a01b0381168103610d09579060443590565b15610db557565b606460405162461bcd60e51b815260206004820152600460248201526310b3b7bb60e11b6044820152fd5b6001600160a01b03818116918215610e52576000805462010000600160b01b03198116601093841b62010000600160b01b031617909155604080519190921c909216825260208201929092527f53351836099c03ffc3b1727d8abd4b0222afa87d4ed76ae3102d51369ef7f7859190a1565b60405162461bcd60e51b815260206004820152600960248201526810bd32b93796b3b7bb60b91b6044820152606490fd5b15610e8a57565b60405162461bcd60e51b815260206004820152600760248201526608585b5bdd5b9d60ca1b6044820152606490fd5b15610ec057565b606460405162461bcd60e51b81526020600482015260046024820152632162707360e01b6044820152fd5b90601f8019910116810190811067ffffffffffffffff821117610f0d57604052565b634e487b7160e01b600052604160045260246000fd5b90816020910312610d0957516001600160a01b0381168103610d095790565b91909160008382019384129112908015821691151617610f5e57565b634e487b7160e01b600052601160045260246000fd5b81810292918115918404141715610f5e57565b9060018060a01b038060075416604092835194859263bf40fac160e01b845283606460209889938460048301526009602483015268506f6f6c53746f726560b81b60448301525afa9283156110d85786906000946110e3575b5060249394865194858092631e9abd8160e11b825280861698896004840152165afa9283156110d8576000936110a7575b509061052861101f926112a5565b9160005260058452826000205460048552828460002055600685524284600020558015801561109c575b611095576127109161105a91610f74565b041115611065575050565b60649250519062461bcd60e51b82526004820152600a60248201526921706f6f6c2d7269736b60b01b6044820152fd5b5050505050565b506000831315611049565b90928682813d83116110d1575b6110be8183610eeb565b8101031261031457505191610528611011565b503d6110b4565b85513d6000823e3d90fd5b602494506110fd90823d84116105f3576105e48183610eeb565b93610fe0565b60609060208152600d60208201526c506f736974696f6e53746f726560981b60408201520190565b9192606093819260018060a01b0316845260406020850152816040850152848401376000828201840152601f01601f1916010190565b81810392916000138015828513169184121617610f5e57565b1561118157565b60405162461bcd60e51b815260206004820152600a602482015269216d61782d64656c746160b01b6044820152606490fd5b91908201809211610f5e57565b91908203918211610f5e57565b9592949560095490811561129b5783602061121294612710966040519384928337810160028152030190209060018060a01b0316600052602052604060002054610f74565b04936000918361126257505050505b1161122857565b60405162461bcd60e51b8152602060048201526012602482015271216d61782d706f736974696f6e2d73697a6560701b6044820152606490fd5b15159015151460001461127f57509061127a916111b3565b611221565b5081811115611292579061127a916111c0565b61127a916111c0565b5050505050505050565b60009060018060a01b031681526004806020526040822054906006602052610e10806040852054049042048181116112e0575b505050905090565b906112ea916111c0565b906003549182156113ad576127109280840482106113115750505050505b803880806112d8565b85929193949594838282039212818312811690828413901516179105600160ff1b8114915b8587106113495750505050505050611308565b90919293949596816113875782810290848782121661139a578082058414901517156113875796600019811461138757600101959493929190611336565b634e487b7160e01b865260118552602486fd5b634e487b7160e01b875260118652602487fd5b634e487b7160e01b855260128252602485fdfea26469706673582212206806efae11f6535fe1fcfe4533e673605c58d502c64c2ac84bb7196e09b09e4964736f6c63430008110033

Block Transaction Gas Used Reward
view all blocks produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.