Перейти к содержимому
Проверенный контрактЧастичноеBUSL-1.1

PhysicalLiquidityPool

Адрес0x6b6e675c9917b2e4e5cd4f5eb8e488687bed55d6
Баланс

0 ETH

 

Транзакций

1

 

Компилятор

solc 0.8.24

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.24+commit.e11b9ed9
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
cancun
Через IR
да
Лицензия
BUSL-1.1
Совпадение
Частичноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 428 814
Транзакция создания
0x164c4af28b…7bc1657ff0

32 файла

contracts/physical/PhysicalLiquidityPool.sol

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

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

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

import {AccessControl} from "../libraries/AccessControl.sol";

import {ILSDAdapter} from "./adapters/ILSDAdapter.sol";
import {IPhysicalAccounting} from "./interfaces/IPhysicalAccounting.sol";
import {IPhysicalLiquidityPool} from "./interfaces/IPhysicalLiquidityPool.sol";
import {IPhysicalOptionRegistry} from "./interfaces/IPhysicalOptionRegistry.sol";
import {IAuthority} from "../interfaces/IAuthority.sol";
import {Types} from "../libraries/Types.sol";

import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

/**
 *  @title Physically-settled Rysk Liquidity Pool
 *  @notice Dual-token liquidity pool for physically-settled option vaults. The pool holds a
 *          primary and a secondary deposit token; both are user-depositable. Shares are minted
 *          and redeemed at pricer-submitted per-epoch prices (one deposit price and one
 *          withdrawal price per asset), which the pricer computes off chain using a formula.
 *          Every share always carries both legs: a withdrawal covers both legs through one
 *          receipt and is paid in full on both legs at one processed epoch's two withdrawal
 *          prices. No on-chain swap.
 */
contract PhysicalLiquidityPool is IPhysicalLiquidityPool, ERC20Upgradeable, UUPSUpgradeable, AccessControl, ReentrancyGuardUpgradeable, PausableUpgradeable {
	using SafeERC20 for IERC20;

	Protocol public protocol;
	address public strikeAsset;
	address public underlyingAsset;
	address public primaryAsset;
	address public secondaryAsset;

	uint256 public collateralAllocated;
	uint256 public partitionedFunds;
	uint256 public accumulatedProtocolFees;
	uint256 public accumulatedCuratorFees;

	uint256 public secondaryCollateralAllocated;
	uint256 public partitionedFundsSecondary;
	uint256 public accumulatedProtocolFeesSecondary;
	uint256 public accumulatedCuratorFeesSecondary;

	uint256 public epoch;
	/// @notice Per-share primary-asset deposit price for epoch `e` (primary decimals).
	mapping(uint256 => uint256) public epochDepositPricePrimary;
	/// @notice Per-share secondary-asset deposit price for epoch `e` (secondary decimals).
	mapping(uint256 => uint256) public epochDepositPriceSecondary;
	/// @notice Per-share primary-asset withdrawal price for epoch `e` (primary decimals).
	mapping(uint256 => uint256) public epochWithdrawalPricePrimary;
	/// @notice Per-share secondary-asset withdrawal price for epoch `e` (secondary decimals).
	mapping(uint256 => uint256) public epochWithdrawalPriceSecondary;
	/// @notice Whether epoch `e` processed the withdrawal queue: both legs funded, both
	///         payouts partitioned and the queued shares burned.
	mapping(uint256 => bool) public epochWithdrawalsProcessed;
	mapping(uint256 => EpochData) internal _epochData;

	mapping(address => IPhysicalAccounting.DepositReceipt) public depositReceipts;
	/// @notice One in-flight withdrawal receipt per user. It covers both legs of its shares.
	mapping(address => VaultWithdrawalReceipt) public withdrawalReceipts;

	uint256 public pendingDeposits;
	/// @notice Aggregate secondary pending for the current epoch (deposit-isolated).
	uint256 public pendingDepositsSecondary;
	/// @notice Shares queued for withdrawal and not yet processed. When
	///         `executeEpochCalculation` finds enough available balance on BOTH legs to pay
	///         every queued share at the epoch's two withdrawal prices, both payouts are
	///         partitioned, the queued shares are burned, the epoch is marked processed and
	///         the counter is cleared. Otherwise the whole queue rolls forward to the next epoch.
	uint256 public pendingWithdrawals;

	/// @notice Smallest secondary deposit. `initialize` sets 100 whole secondary tokens (100 USDC
	///         for a USDC secondary), which also covers the decimal-pair floor, so an accepted
	///         deposit mints at least one share at unit pricing. The governor can change it with
	///         `setMinDeposit`.
	uint256 public minSecondaryDeposit;
	/// @notice Smallest withdrawal, in shares, whose secondary leg pays ≥1 wei at unit pricing.
	uint256 public minSecondaryWithdraw;
	mapping(address => bool) public handler;
	bool public isEpochLocked;
	mapping(address => bool) public keeper;
	uint256 public disputePeriod;
	mapping(uint256 => uint256) public epochPriceSetTimestamp;

	uint256 public optionSaleFee;
	uint256 public curatorFeeShare;

	bool public isWhitelistEnabled;
	mapping(address => bool) public whitelistedAddresses;

	/// @notice Governor-curated allowlist of LSD adapters. Each adapter converts a
	///         non-pool token (e.g. the underlying received from an ITM put settlement)
	///         into the pool's primary or secondary asset via an external staking
	///         contract. See `setLSDAdapter` and `convertViaAdapter`.
	mapping(address => bool) public lsdAdapterAllowed;

	/// @notice Which deposit legs are open. Defaults to `Both`. See `setDepositMode`.
	DepositMode public depositMode;

	/// @notice Primary-leg deposit cap in primary-asset units, 0 means no cap. A primary
	///         deposit reverts when `getAvailableBalance() + collateralAllocated +
	///         pendingDeposits + amount` would exceed it. See `setDepositCap`.
	uint256 public depositCapPrimary;
	/// @notice Secondary-leg deposit cap in secondary-asset units, 0 means no cap. A secondary
	///         deposit reverts when `getAvailableSecondary() + secondaryCollateralAllocated +
	///         pendingDepositsSecondary + amount` would exceed it. See `setDepositCap`.
	uint256 public depositCapSecondary;

	/// @notice Smallest primary deposit in primary-asset units. 0 at deploy, so any nonzero
	///         amount is accepted. The governor sets it with `setMinDeposit`.
	uint256 public minPrimaryDeposit;

	uint256 private constant MAX_BPS = 10_000;

	/// @notice Opyn `amount × strike` product is fixed-point with 16 decimals (8 + 8). Used to
	///         normalize put-collateral math from Opyn-space to the collateral asset's decimals.
	uint256 private constant OPYN_AMOUNT_STRIKE_PRODUCT_DECIMALS = 1e16;

	error LP_InvalidAmount();
	error LP_InvalidShareAmount();
	error LP_NotHandler();
	error LP_NotKeeperOrGovernor();
	error LP_EpochLocked();
	error LP_InvalidAddress();
	error LP_AssetsMustDiffer();
	error LP_DepositBelowDust();
	error LP_WithdrawBelowDust();
	error LP_AddressNotWhitelisted();
	error LP_WithdrawPending();
	error LP_NoExistingWithdrawal();
	error LP_WithdrawalNotProcessed();
	error LP_CollateralAssetInvalid();
	error LP_UnderlyingAssetInvalid();
	error LP_StrikeAssetInvalid();
	error LP_IssuanceFailed();
	error LP_InsufficientSecondary();
	error LP_InsufficientAvailable();
	error LP_InsufficientFundsForPremium();
	error LP_InsufficientSecondaryForPremium();
	error LP_SenderNotWhitelisted();
	error LP_RecipientNotWhitelisted();
	error LP_CannotUnlockPriced();
	error LP_InvalidPrice();
	error LP_PriceAlreadySet();
	error LP_EpochMustBeLocked();
	error LP_PricesNotSetYet();
	error LP_DisputePeriodExpired();
	error LP_DisputePeriodNotExpired();
	error LP_EpochNotLocked();
	error LP_EpochPricesNotSet();
	error LP_ZeroManager();
	error LP_AdapterNotAllowed();
	error LP_DepositLegClosed();
	error LP_FeeExceedsMax();
	error LP_NoPendingDeposit();
	error LP_DepositCapExceeded();

	event Withdraw(
		address indexed recipient,
		uint256 primaryAmount,
		uint256 secondaryAmount,
		uint256 shares,
		uint256 processedEpoch
	);
	event DepositPrimary(address indexed recipient, uint256 amount, uint256 epoch);
	event DepositSecondary(address indexed recipient, uint256 amount, uint256 epoch);
	event Redeem(address indexed recipient, uint256 amount, uint256 epoch);
	event InitiateWithdraw(address indexed recipient, uint256 shares, uint256 epoch);
	event WriteOption(address indexed series, uint256 amount, uint256 premium, uint256 escrow, address indexed buyer);
	event EpochLocked();
	event EpochUnlocked();
	event OptionFeeCollected(address indexed series, uint256 totalFee, uint256 curatorShare, uint256 protocolShare);
	event BuybackOption(
		address indexed series,
		uint256 amount,
		uint256 premium,
		uint256 collateralReturned,
		address indexed seller
	);
	event EpochExecuted(uint256 epoch);
	event EpochPriceSet(
		uint256 indexed epoch,
		uint256 depositPricePrimary,
		uint256 depositPriceSecondary,
		uint256 withdrawalPricePrimary,
		uint256 withdrawalPriceSecondary
	);
	event EpochPriceDisputed(
		uint256 indexed epoch,
		uint256 depositPricePrimary,
		uint256 depositPriceSecondary,
		uint256 withdrawalPricePrimary,
		uint256 withdrawalPriceSecondary
	);
	event DisputePeriodUpdated(uint256 newDisputePeriod);
	event OptionSaleFeeUpdated(uint256 newFee);
	event CuratorFeeShareUpdated(uint256 newShare);
	event HandlerUpdated(address indexed handler, bool authorized);
	event KeeperUpdated(address indexed keeper, bool authorized);
	event WhitelistEnabled(bool enabled);
	event AddressWhitelisted(address indexed account, bool whitelisted);
	event ProtocolFeesWithdrawn(address indexed recipient, uint256 amount, address indexed token);
	event CuratorFeesWithdrawn(address indexed recipient, uint256 amount, address indexed token);
	event SettleVault(
		address indexed series,
		address indexed tokenReturned,
		uint256 collateralReturned,
		uint256 collateralLost,
		address closer,
		uint256 vaultId
	);
	event LSDAdapterUpdated(address indexed adapter, bool allowed);
	event DepositModeUpdated(DepositMode mode);
	event DepositCapUpdated(uint256 cap, bool isPrimary);
	event MinDepositUpdated(uint256 min, bool isPrimary);
	event DepositCancelled(address indexed depositor, uint256 amountPrimary, uint256 amountSecondary, uint256 epoch);

	modifier onlyHandler() {
		if (!handler[msg.sender]) revert LP_NotHandler();
		_;
	}

	modifier epochNotLocked() {
		if (isEpochLocked) revert LP_EpochLocked();
		_;
	}

	modifier isKeeperOrGovernor() {
		if (!keeper[msg.sender] && msg.sender != authority.governor()) revert LP_NotKeeperOrGovernor();
		_;
	}

	/// @custom:oz-upgrades-unsafe-allow constructor
	constructor() {
		_disableInitializers();
	}

	function initialize(
		address _protocol,
		address _strikeAsset,
		address _underlyingAsset,
		address _primaryAsset,
		address _secondaryAsset,
		string memory _name,
		string memory _symbol,
		address _authority,
		bool _whitelistEnabled
	) external initializer {
		__ERC20_init(_name, _symbol);
		__UUPSUpgradeable_init();
		__ReentrancyGuard_init();
		__Pausable_init();
		__AccessControl_init(IAuthority(_authority));

		if (
			_protocol == address(0) ||
			_strikeAsset == address(0) ||
			_underlyingAsset == address(0) ||
			_primaryAsset == address(0) ||
			_secondaryAsset == address(0)
		) {
			revert LP_InvalidAddress();
		}
		if (_primaryAsset == _secondaryAsset) {
			revert LP_AssetsMustDiffer();
		}
		strikeAsset = _strikeAsset;
		underlyingAsset = _underlyingAsset;
		primaryAsset = _primaryAsset;
		secondaryAsset = _secondaryAsset;
		protocol = Protocol(_protocol);
		uint256 primaryScale = 10 ** ERC20(_primaryAsset).decimals();
		uint256 secondaryScale = 10 ** ERC20(_secondaryAsset).decimals();
		// Epoch 0 sentinel: non-zero prices (10**decimals) for both assets so epoch-0 lookups never divide by zero.
		epochDepositPricePrimary[0] = primaryScale;
		epochDepositPriceSecondary[0] = secondaryScale;
		epochWithdrawalPricePrimary[0] = primaryScale;
		epochWithdrawalPriceSecondary[0] = secondaryScale;
		epoch++;
		// Secondary deposit minimum: 100 whole secondary tokens, which is at least the decimal-pair
		// floor 10**(s - p) for every pair. `setMinDeposit` can change it later, and the primary
		// minimum stays 0. Withdraw floor: the decimal-asymmetry guard below.
		minSecondaryDeposit  = 100 * secondaryScale;
		minSecondaryWithdraw = primaryScale > secondaryScale ? primaryScale / secondaryScale : 1;
		isWhitelistEnabled = _whitelistEnabled;
	}

	function decimals() public view override returns (uint8) {
		return ERC20(primaryAsset).decimals();
	}

	/// @notice Guardian-only protocol pause.
	function pause() external onlyGuardian {
		_pause();
	}

	/// @notice Guardian-only unpause.
	function unpause() external onlyGuardian {
		_unpause();
	}

	/// @notice Guardian toggle for `isEpochLocked`. Refuses to unlock once the current epoch has been priced.
	function lockUnlockEpoch(bool _lock) external onlyGuardian {
		// Refuse to unlock once the current epoch has been priced. The lock stops new
		// deposits, initiateWithdraw, option writes and buybacks (all gated by
		// epochNotLocked). cancelDeposit still runs while locked: on each leg it lowers
		// the pool balance and that leg's pending deposit counter by the same amount, so
		// the available balances and the withdrawal gate do not move, and execute mints
		// shares only for the deposits still pending at that time.
		if (!_lock && epochPriceSetTimestamp[epoch] != 0) {
			revert LP_CannotUnlockPriced();
		}
		isEpochLocked = _lock;
		if (_lock) {
			emit EpochLocked();
		} else {
			emit EpochUnlocked();
		}
	}

	/// @notice Set premium fee bps. Reverts `LP_FeeExceedsMax` above `MAX_BPS`.
	function setOptionSaleFee(uint256 _optionSaleFee) external onlyGovernor {
		if (_optionSaleFee > MAX_BPS) revert LP_FeeExceedsMax();
		optionSaleFee = _optionSaleFee;
		emit OptionSaleFeeUpdated(_optionSaleFee);
	}

	/// @notice Set curator's slice of total fees in bps. Reverts `LP_FeeExceedsMax` above `MAX_BPS`.
	function setCuratorFeeShare(uint256 _curatorFeeShare) external onlyGovernor {
		if (_curatorFeeShare > MAX_BPS) revert LP_FeeExceedsMax();
		curatorFeeShare = _curatorFeeShare;
		emit CuratorFeeShareUpdated(_curatorFeeShare);
	}

	/// @notice Set dispute window seconds.
	function setDisputePeriod(uint256 _disputePeriod) external onlyGovernor {
		// Dispute period is mutable even after pricing 
		// a mid-window change can extend the window when there is a real reason to dispute.
		disputePeriod = _disputePeriod;
		emit DisputePeriodUpdated(_disputePeriod);
	}

	/// @notice Toggle handler authorization.
	function changeHandler(address _handler, bool auth) external onlyGovernor {
		if (_handler == address(0)) revert LP_InvalidAddress();
		handler[_handler] = auth;
		emit HandlerUpdated(_handler, auth);
	}

	/// @notice Toggle keeper authorization.
	function setKeeper(address _keeper, bool _auth) external onlyGovernor {
		if (_keeper == address(0)) revert LP_InvalidAddress();
		keeper[_keeper] = _auth;
		emit KeeperUpdated(_keeper, _auth);
	}

	/// @notice Allowlist or revoke an `ILSDAdapter`. Governor is the trust boundary —
	///         the adapter contract is reviewed off-chain before allowlisting.
	/// @dev    This function does NOT enforce on-chain that
	///         `adapter.inputToken() != primaryAsset && adapter.inputToken() != secondaryAsset`
	///         (drain vector if violated) nor that
	///         `adapter.outputToken() == primaryAsset || adapter.outputToken() == secondaryAsset`
	///         (silent-loss vector if violated). The `ILSDAdapter` interface documents both
	///         constraints as the governor's responsibility. Governance MUST verify both
	///         tokens against the pool's primary/secondary assets before allowlisting.
	function setLSDAdapter(address adapter, bool allowed) external onlyGovernor {
		if (adapter == address(0)) revert LP_InvalidAddress();
		lsdAdapterAllowed[adapter] = allowed;
		emit LSDAdapterUpdated(adapter, allowed);
	}

	/// @notice Governor-only conversion of a non-pool token (e.g. wHYPE received from an
	///         ITM put settlement) into this pool's primary or secondary asset via an
	///         allowlisted LSD adapter. Adapter is the trust boundary; the adapter pulls
	///         `amountIn` of its `inputToken` from the pool and deposits the resulting
	///         LSD shares back to the pool.
	function convertViaAdapter(address adapter, uint256 amountIn)
		external
		onlyGovernor
		nonReentrant
		returns (uint256 amountOut)
	{
		if (!lsdAdapterAllowed[adapter]) revert LP_AdapterNotAllowed();
		if (amountIn == 0) revert LP_InvalidAmount();

		ILSDAdapter a = ILSDAdapter(adapter);
		IERC20 inToken = IERC20(a.inputToken());
		inToken.forceApprove(adapter, amountIn);
		amountOut = a.deposit(amountIn, address(this));
		inToken.forceApprove(adapter, 0);
	}

	/// @notice Keeper or governor opens deposits on both legs, the primary leg only, or the
	///         secondary leg only, or closes both legs with `None`. Only `depositPrimary` /
	///         `depositSecondary` are gated. Receipts from earlier deposits on a now-closed
	///         leg still execute, redeem and auto-redeem as usual, and withdrawals are
	///         unaffected.
	function setDepositMode(DepositMode _mode) external isKeeperOrGovernor {
		depositMode = _mode;
		emit DepositModeUpdated(_mode);
	}

	/// @notice Keeper or governor sets the deposit cap of one leg: `depositCapPrimary` when
	///         `_isPrimary` is true, `depositCapSecondary` otherwise. 0 removes the cap. It can
	///         change at any time and only gates new deposits: lowering it below the current
	///         total never touches pending deposits, receipts, shares or withdrawals.
	function setDepositCap(uint256 _cap, bool _isPrimary) external isKeeperOrGovernor {
		if (_isPrimary) depositCapPrimary = _cap;
		else depositCapSecondary = _cap;
		emit DepositCapUpdated(_cap, _isPrimary);
	}

	/// @notice Governor sets the minimum deposit of one leg, in that leg's asset units:
	///         `minPrimaryDeposit` when `_isPrimary` is true, `minSecondaryDeposit` otherwise.
	///         0 accepts any nonzero amount. It only gates new deposits, never pending deposits,
	///         receipts, shares or withdrawals.
	/// @dev   No lower bound. A deposit worth less than one share at its epoch's deposit price
	///        mints zero shares. On the secondary leg at unit pricing that is any amount below
	///        the decimal-pair floor `10**(secondaryDecimals - primaryDecimals)`. The depositor
	///        loses that dust to the pool, and other holders lose nothing.
	function setMinDeposit(uint256 _min, bool _isPrimary) external onlyGovernor {
		if (_isPrimary) minPrimaryDeposit = _min;
		else minSecondaryDeposit = _min;
		emit MinDepositUpdated(_min, _isPrimary);
	}

	/// @notice Enable or disable the deposit whitelist.
	function setWhitelistEnabled(bool _enabled) external onlyGovernor {
		isWhitelistEnabled = _enabled;
		emit WhitelistEnabled(_enabled);
	}

	/// @notice Set whitelist status for one or many addresses.
	function setWhitelistedAddress(address _address, bool _whitelisted) external onlyGovernor {
		whitelistedAddresses[_address] = _whitelisted;
		emit AddressWhitelisted(_address, _whitelisted);
	}

	/// @notice Set whitelist status for one or many addresses.
	function setWhitelistedAddresses(address[] calldata _addresses, bool _whitelisted) external onlyGovernor {
		for (uint256 i = 0; i < _addresses.length; i++) {
			whitelistedAddresses[_addresses[i]] = _whitelisted;
			emit AddressWhitelisted(_addresses[i], _whitelisted);
		}
	}

	/// @notice Pricer-only setter for the four per-epoch prices. Reverts if either deposit price
	///         is zero, the epoch is not locked, or prices are already set for this epoch.
	///         A withdrawal price may be zero: that leg then pays nothing and needs no funding.
	/// @dev    The four prices are computed off chain by the pricer using a formula; this
	///         function only validates and stores them.
	///
	///         ENCODING CONVENTION: all four prices follow the "native-token per 1 whole share"
	///         convention, where 1 whole share equals `10**primaryDecimals` raw share units
	///         (by ERC20 convention).
	///           - `_depositPricePrimary` / `_withdrawalPricePrimary`: primary-native units
	///             per 1 whole share. Sentinel: `epochDeposit/WithdrawalPricePrimary[0] =
	///             10**primaryDecimals` (set at initialize).
	///           - `_depositPriceSecondary` / `_withdrawalPriceSecondary`: secondary-native
	///             units per 1 whole share. Sentinel: `epochDeposit/WithdrawalPriceSecondary[0]
	///             = 10**secondaryDecimals` (set at initialize).
	///         See `PhysicalAccounting.amountForShares` NatSpec for how the share math
	///         consumes these values.
	function setEpochPrices(
		uint256 _depositPricePrimary,
		uint256 _depositPriceSecondary,
		uint256 _withdrawalPricePrimary,
		uint256 _withdrawalPriceSecondary
	) external onlyPricer {
		if (_depositPricePrimary == 0 || _depositPriceSecondary == 0) revert LP_InvalidPrice();
		if (!isEpochLocked) revert LP_EpochMustBeLocked();
		uint256 e = epoch;
		if (epochPriceSetTimestamp[e] != 0) revert LP_PriceAlreadySet();
		_priceEpoch(e, _depositPricePrimary, _depositPriceSecondary, _withdrawalPricePrimary, _withdrawalPriceSecondary);
		emit EpochPriceSet(e, _depositPricePrimary, _depositPriceSecondary, _withdrawalPricePrimary, _withdrawalPriceSecondary);
	}

	/// @notice Pricer overrides the four prices during the dispute window. Reverts
	///         after `disputePeriod` elapses. Same zero rules as `setEpochPrices`.
	function disputeEpochPrices(
		uint256 _depositPricePrimary,
		uint256 _depositPriceSecondary,
		uint256 _withdrawalPricePrimary,
		uint256 _withdrawalPriceSecondary
	) external onlyPricer {
		if (_depositPricePrimary == 0 || _depositPriceSecondary == 0) revert LP_InvalidPrice();
		uint256 e = epoch;
		uint256 setAt = epochPriceSetTimestamp[e];
		if (setAt == 0) revert LP_PricesNotSetYet();
		if (block.timestamp - setAt >= disputePeriod) revert LP_DisputePeriodExpired();
		_priceEpoch(e, _depositPricePrimary, _depositPriceSecondary, _withdrawalPricePrimary, _withdrawalPriceSecondary);
		emit EpochPriceDisputed(e, _depositPricePrimary, _depositPriceSecondary, _withdrawalPricePrimary, _withdrawalPriceSecondary);
	}

	function _priceEpoch(
		uint256 e,
		uint256 depositPricePrimary,
		uint256 depositPriceSecondary,
		uint256 withdrawalPricePrimary,
		uint256 withdrawalPriceSecondary
	) internal {
		epochDepositPricePrimary[e] = depositPricePrimary;
		epochDepositPriceSecondary[e] = depositPriceSecondary;
		epochWithdrawalPricePrimary[e] = withdrawalPricePrimary;
		epochWithdrawalPriceSecondary[e] = withdrawalPriceSecondary;
		epochPriceSetTimestamp[e] = block.timestamp;
	}

	/// @notice Execute the next epoch using the prices set via `setEpochPrices`.
	/// @dev Whole-queue rule: the withdrawal queue is processed only when BOTH legs can pay
	///      every queued share at this epoch's two withdrawal prices. Then both payouts are
	///      partitioned, the queued shares are burned and the epoch is flagged in
	///      `epochWithdrawalsProcessed`. If either leg is short, nothing is partitioned or
	///      burned on either leg and the whole queue rolls forward in `pendingWithdrawals`,
	///      to be paid at the FIRST subsequent epoch whose prices both legs can fund in full.
	///      One leg is never paid ahead of the other.
	function executeEpochCalculation() external whenNotPaused isKeeperOrGovernor nonReentrant {
		if (!isEpochLocked) revert LP_EpochNotLocked();
		uint256 currentEpoch = epoch;
		uint256 setAt = epochPriceSetTimestamp[currentEpoch];
		if (setAt == 0) revert LP_EpochPricesNotSet();
		uint256 dp = disputePeriod;
		if (dp > 0 && block.timestamp - setAt < dp) revert LP_DisputePeriodNotExpired();

		uint256 dpP = epochDepositPricePrimary[currentEpoch];
		uint256 dpS = epochDepositPriceSecondary[currentEpoch];
		uint256 wpP = epochWithdrawalPricePrimary[currentEpoch];
		uint256 wpS = epochWithdrawalPriceSecondary[currentEpoch];

		(
			uint256 sharesToMint,
			uint256 totalPrimaryWithdraw,
			uint256 totalSecondaryWithdraw,
			uint256 primaryAmountNeeded,
			uint256 secondaryAmountNeeded
		) = _getAccounting().executeEpochCalculation(dpP, dpS, wpP, wpS);

		// Both legs or neither: a shortfall on either leg leaves the whole queue pending so
		// it is paid in full, on both legs, at the first epoch that can fund all of it.
		uint256 pending = pendingWithdrawals;
		if (pending > 0 && primaryAmountNeeded == 0 && secondaryAmountNeeded == 0) {
			partitionedFunds += totalPrimaryWithdraw;
			partitionedFundsSecondary += totalSecondaryWithdraw;
			epochWithdrawalsProcessed[currentEpoch] = true;
			pendingWithdrawals = 0;
			_burn(address(this), pending);
		}

		delete pendingDeposits;
		delete pendingDepositsSecondary;
		_mint(address(this), sharesToMint);

		// Snapshot the executed prices and advance epoch.
		_epochData[currentEpoch] = EpochData({
			epochNumber: currentEpoch,
			depositPricePrimary: dpP,
			depositPriceSecondary: dpS,
			withdrawalPricePrimary: wpP,
			withdrawalPriceSecondary: wpS,
			timestamp: block.timestamp
		});
		epoch = currentEpoch + 1;
		isEpochLocked = false;
		emit EpochUnlocked();
		emit EpochExecuted(currentEpoch);
	}

	/// @notice Settle an expired series via the option registry and decrement the
	///         matching collateral allocation counter. Caches `seriesInfo` before
	///         `settle()` because the registry deletes it.
	/// @dev Reverts `LP_CollateralAssetInvalid` if the cached collateral is neither
	///      `secondaryAsset` nor `primaryAsset`. The check runs after `settle()`, so the
	///      registry's own reverts for a missing or unsettleable series surface unchanged.
	function settleVault(address seriesAddress) external isKeeperOrGovernor nonReentrant returns (uint256) {
		IPhysicalOptionRegistry optionRegistry = _getOptionRegistry();
		address secondary = secondaryAsset;

		// MUST cache seriesInfo before settle the registry deletes seriesInfo[seriesAddress]
		// inside settle(), so reading it afterwards returns a zero struct whose collateral
		// field is address(0), which classifies every settlement as primary-collateral
		// (the wrong branch for any secondary-collateral series).
		Types.OptionSeries memory seriesInfo = optionRegistry.getSeriesInfo(seriesAddress);
		bool wasSecondaryCollateral = (seriesInfo.collateral == secondary);

		(
			,
			address tokenReturned,
			uint256 amountReturned,
			uint256 amountLost,
			,
			uint256 vaultId,
			uint256 originalCollateral
		) = optionRegistry.settle(seriesAddress);

		// The leangamma vault is fully destroyed at settlement, so the entire `originalCollateral`
		// allocated for this series leaves the global counter regardless of which path returned
		// the funds. Using `originalCollateral` directly closes the partial-ITM ghost-allocation
		// drift where both opposite-token payout and residual collateral are returned together.
		if (!wasSecondaryCollateral) {
			if (seriesInfo.collateral != primaryAsset) revert LP_CollateralAssetInvalid();
			uint256 alloc = collateralAllocated;
			uint256 delta = originalCollateral >= alloc ? alloc : originalCollateral;
			collateralAllocated = alloc - delta;
		} else {
			uint256 alloc = secondaryCollateralAllocated;
			uint256 delta = originalCollateral >= alloc ? alloc : originalCollateral;
			secondaryCollateralAllocated = alloc - delta;
		}

		emit SettleVault(seriesAddress, tokenReturned, amountReturned, amountLost, msg.sender, vaultId);
		return amountReturned;
	}

	/// @notice Pay accumulated primary + secondary protocol fees to the governor; zeroes both buckets.
	/// @dev onlyGovernor guarantees msg.sender == authority.governor(), so fees go to msg.sender.
	function withdrawProtocolFees() external onlyGovernor nonReentrant {
		(uint256 primaryAmount, uint256 secondaryAmount) = _payFees(msg.sender, false);
		emit ProtocolFeesWithdrawn(msg.sender, primaryAmount, primaryAsset);
		emit ProtocolFeesWithdrawn(msg.sender, secondaryAmount, secondaryAsset);
	}

	/// @notice Curator pulls own primary + secondary fee buckets.
	function withdrawCuratorFees() external onlyManager nonReentrant {
		_flushCurator(authority.manager());
	}

	/// @notice Governor flushes accumulated curator fees to the manager.
	function flushCuratorFees() external onlyGovernor nonReentrant {
		_flushCurator(authority.manager());
	}

	function _flushCurator(address manager) internal { 
		if (manager == address(0)) revert LP_ZeroManager();
		(uint256 primaryAmount, uint256 secondaryAmount) = _payFees(manager, true);
		emit CuratorFeesWithdrawn(manager, primaryAmount, primaryAsset); 
		emit CuratorFeesWithdrawn(manager, secondaryAmount, secondaryAsset);
	}

	/// @dev Pays out ALL accumulated fees (primary + secondary) to `to`. `isCurator=false` →
	///      protocol fees; `isCurator=true` → curator fees. Amount computed internally from fee
	///      buckets — no caller-supplied amount prevents generic-drain primitives.
	function _payFees(address to, bool isCurator) internal returns (uint256 primaryAmount, uint256 secondaryAmount) {
		if (isCurator) {
			primaryAmount = accumulatedCuratorFees;
			secondaryAmount = accumulatedCuratorFeesSecondary;
			accumulatedCuratorFees = 0;
			accumulatedCuratorFeesSecondary = 0;
		} else {
			primaryAmount = accumulatedProtocolFees;
			secondaryAmount = accumulatedProtocolFeesSecondary;
			accumulatedProtocolFees = 0;
			accumulatedProtocolFeesSecondary = 0;
		}

		if (primaryAmount > 0) {
			IERC20(primaryAsset).safeTransfer(to, primaryAmount);
		}
		if (secondaryAmount > 0) {
			IERC20(secondaryAsset).safeTransfer(to, secondaryAmount);
		}
	}

	/// @notice Snapshot of the four executed prices and timestamp for an executed epoch.
	function getEpochData(uint256 _epoch) external view override returns (EpochData memory) {
		return _epochData[_epoch];
	}

	/// @notice Deposit `_amount` of primary asset toward the current epoch. Reverts with
	///         `LP_DepositLegClosed` when `depositMode` is `SecondaryOnly` or `None`, with
	///         `LP_DepositBelowDust` when `_amount < minPrimaryDeposit` (0 at deploy, set by the
	///         governor), and with `LP_DepositCapExceeded` when `depositCapPrimary` is set and
	///         `getAvailableBalance() + collateralAllocated + pendingDeposits + _amount` exceeds it.
	/// @dev   Share inflation: with a tiny share supply a donation can make one share worth more than a
	///        later deposit, which is then minted zero shares. A public vault should not run an epoch
	///        with small deposits or a single depositor.
	function depositPrimary(uint256 _amount) external override whenNotPaused nonReentrant epochNotLocked returns (bool) {
		return _deposit(_amount, true);
	}

	/// @notice Deposit `_amount` of secondary asset toward the current epoch. Reverts when
	///         `_amount < minSecondaryDeposit` (100 whole secondary tokens at deploy, the
	///         governor can change it) with
	///         `LP_DepositBelowDust`, and with `LP_DepositLegClosed` when `depositMode` is
	///         `PrimaryOnly` or `None`, and with `LP_DepositCapExceeded` when
	///         `depositCapSecondary` is set and `getAvailableSecondary() +
	///         secondaryCollateralAllocated + pendingDepositsSecondary + _amount` exceeds it.
	/// @dev   Same share-inflation caveat as `depositPrimary`.
	function depositSecondary(uint256 _amount) external override whenNotPaused nonReentrant epochNotLocked returns (bool) {
		return _deposit(_amount, false);
	}

	function _deposit(uint256 _amount, bool isPrimary) internal returns (bool) {
		if (_amount == 0) revert LP_InvalidAmount();
		// DepositMode values double as a closed-leg bitmask: bit 0 closes secondary
		// (PrimaryOnly, None), bit 1 closes primary (SecondaryOnly, None).
		if (uint8(depositMode) & (isPrimary ? 2 : 1) != 0) revert LP_DepositLegClosed();
		if (_amount < (isPrimary ? minPrimaryDeposit : minSecondaryDeposit)) revert LP_DepositBelowDust();
		// Leg cap: free + allocated + pending + this deposit must stay within it (0 = no cap).
		uint256 cap = isPrimary ? depositCapPrimary : depositCapSecondary;
		if (
			cap != 0 &&
			(isPrimary
				? getAvailableBalance() + collateralAllocated + pendingDeposits
				: getAvailableSecondary() + secondaryCollateralAllocated + pendingDepositsSecondary) + _amount > cap
		) revert LP_DepositCapExceeded();

		if (isWhitelistEnabled && !whitelistedAddresses[msg.sender]) revert LP_AddressNotWhitelisted();

		// Auto-redeem any stale prior receipt (covers both legs together).
		IPhysicalAccounting.DepositReceipt memory existingReceipt = depositReceipts[msg.sender];
		if (
			existingReceipt.epoch != 0 &&
			existingReceipt.epoch < epoch &&
			(existingReceipt.amountPrimary > 0 || existingReceipt.amountSecondary > 0)
		) {
			_redeem();
		}

		uint256 currentEpoch = epoch;
		IPhysicalAccounting accounting = _getAccounting();

		if (isPrimary) {
			uint256 newAmountPrimary = accounting.depositPrimary(msg.sender, _amount);
			IPhysicalAccounting.DepositReceipt memory r = depositReceipts[msg.sender];
			uint256 keepSecondary = (r.epoch == currentEpoch ? r.amountSecondary : 0);
			depositReceipts[msg.sender] = IPhysicalAccounting.DepositReceipt({
				epoch: uint128(currentEpoch),
				amountPrimary: newAmountPrimary,
				amountSecondary: keepSecondary
			});
			pendingDeposits += _amount;
			emit DepositPrimary(msg.sender, _amount, currentEpoch);
			IERC20(primaryAsset).safeTransferFrom(msg.sender, address(this), _amount);
		} else {
			uint256 newAmountSecondary = accounting.depositSecondary(msg.sender, _amount);
			IPhysicalAccounting.DepositReceipt memory r = depositReceipts[msg.sender];
			uint256 keepPrimary = (r.epoch == currentEpoch ? r.amountPrimary : 0);
			depositReceipts[msg.sender] = IPhysicalAccounting.DepositReceipt({
				epoch: uint128(currentEpoch),
				amountPrimary: keepPrimary,
				amountSecondary: newAmountSecondary
			});
			pendingDepositsSecondary += _amount;
			emit DepositSecondary(msg.sender, _amount, currentEpoch);
			IERC20(secondaryAsset).safeTransferFrom(msg.sender, address(this), _amount);
		}
		return true;
	}

	/// @notice Mint shares from a prior-epoch deposit receipt (sums both legs at receipt-epoch prices). Idempotent.
	function redeem() external override whenNotPaused nonReentrant returns (uint256) {
		return _redeem();
	}

	/// @notice Keeper or governor cancels `_depositor`'s pending deposit: both legs of the
	///         receipt, in full. Both pending counters drop by the receipt amounts, the receipt
	///         is deleted and the tokens go back to `_depositor` in this call.
	/// @dev    A pending deposit always carries the current epoch: execute converts every
	///         pending deposit into shares and advances the epoch. A receipt with an older epoch
	///         is already shares waiting for `redeem`, so it is refused with
	///         `LP_NoPendingDeposit`, as are an absent receipt and an already cancelled one.
	///         Works while the epoch is locked, after prices are set and while the pool is
	///         paused: execute mints shares from the pending counters at execution, so a
	///         cancelled deposit never receives shares.
	///         USDC blacklist: when a USDC refund is due it is pushed to `_depositor`. If USDC
	///         has blacklisted that address, has blacklisted the pool, or is paused, the
	///         transfer reverts, the whole call reverts and the deposit stays pending and
	///         executes into shares as usual. A receipt with no USDC skips the USDC transfer.
	///         Token assumption: both legs must be plain ERC20s that move exactly the amount
	///         asked (WHYPE, USDC). With a fee-on-transfer or rebasing token, the pool balance
	///         can drift from the pending counters, so a cancel could pay one depositor out of
	///         funds owed to others. A token with transfer callbacks lets the recipient refuse
	///         its refund and observe the pool mid-call; `nonReentrant` blocks re-entry into the
	///         guarded pool functions, while views and role-gated setters stay callable. Such
	///         assets need a separate review.
	function cancelDeposit(address _depositor) external isKeeperOrGovernor nonReentrant {
		IPhysicalAccounting.DepositReceipt memory r = depositReceipts[_depositor];
		uint256 currentEpoch = epoch;
		if (r.epoch != currentEpoch) revert LP_NoPendingDeposit();
		delete depositReceipts[_depositor];
		pendingDeposits -= r.amountPrimary;
		pendingDepositsSecondary -= r.amountSecondary;
		emit DepositCancelled(_depositor, r.amountPrimary, r.amountSecondary, currentEpoch);
		if (r.amountPrimary > 0) IERC20(primaryAsset).safeTransfer(_depositor, r.amountPrimary);
		if (r.amountSecondary > 0) IERC20(secondaryAsset).safeTransfer(_depositor, r.amountSecondary);
	}

	/// @notice Initiate a withdrawal of `_shares`, covering both legs. The shares move into
	///         the pool's escrow and join the withdrawal queue; they are burned when an epoch
	///         processes the queue, and `completeWithdraw` then pays both legs.
	/// @dev Off-chain "can initiate" / "max initiable shares" computation:
	///        canInitiate = !paused()
	///                   && !isEpochLocked()
	///                   && withdrawalReceipts[user].shares == 0
	///        maxShares  = IERC20(pool).balanceOf(user)              // pulled from wallet via _transfer
	///      Floor: `_shares >= minSecondaryWithdraw` (dust guard for the decimal-asymmetry pair).
	///      Reverts: LP_InvalidShareAmount (zero), LP_WithdrawBelowDust (< minSecondaryWithdraw),
	///      LP_EpochLocked (epoch locked), LP_WithdrawPending (existing receipt).
	function initiateWithdraw(uint256 _shares) external override whenNotPaused nonReentrant epochNotLocked {
		if (_shares == 0) revert LP_InvalidShareAmount();
		if (_shares < minSecondaryWithdraw) revert LP_WithdrawBelowDust();
		if (withdrawalReceipts[msg.sender].shares > 0) revert LP_WithdrawPending();
		IPhysicalAccounting.DepositReceipt memory existingDeposit = depositReceipts[msg.sender];
		if (
			existingDeposit.epoch != 0 &&
			existingDeposit.epoch < epoch &&
			(existingDeposit.amountPrimary > 0 || existingDeposit.amountSecondary > 0)
		) {
			_redeem();
		}
		uint256 currentEpoch = epoch;
		withdrawalReceipts[msg.sender] = VaultWithdrawalReceipt({
			epoch: uint128(currentEpoch),
			shares: _shares
		});
		pendingWithdrawals += _shares;
		emit InitiateWithdraw(msg.sender, _shares, currentEpoch);
		_transfer(msg.sender, address(this), _shares);
	}

	/// @notice Pay both legs of the user's processed withdrawal receipt at the processing
	///         epoch's two withdrawal prices and clear the receipt. The receipt's shares were
	///         already burned when the epoch processed the queue. Reverts if no receipt or not
	///         processed yet.
	function completeWithdraw()
		external
		override
		whenNotPaused
		nonReentrant
		returns (uint256 primaryAmount, uint256 secondaryAmount)
	{
		VaultWithdrawalReceipt memory receipt = withdrawalReceipts[msg.sender];
		if (receipt.shares == 0) revert LP_NoExistingWithdrawal();
		uint256 processedEpoch = _findProcessedEpoch(receipt.epoch);
		IPhysicalAccounting accounting = _getAccounting();
		primaryAmount = accounting.amountForShares(receipt.shares, epochWithdrawalPricePrimary[processedEpoch]);
		secondaryAmount = accounting.amountForShares(receipt.shares, epochWithdrawalPriceSecondary[processedEpoch]);

		delete withdrawalReceipts[msg.sender];
		partitionedFunds -= primaryAmount;
		partitionedFundsSecondary -= secondaryAmount;
		emit Withdraw(msg.sender, primaryAmount, secondaryAmount, receipt.shares, processedEpoch);
		if (primaryAmount > 0) IERC20(primaryAsset).safeTransfer(msg.sender, primaryAmount);
		if (secondaryAmount > 0) IERC20(secondaryAsset).safeTransfer(msg.sender, secondaryAmount);
	}

	/// @notice Available primary balance for writing primary-collateral series. Excludes
	///         pendingDeposits (deposit isolation from option writing) and reserved buckets.
	function getAvailableBalance() public view returns (uint256) {
		uint256 balance = ERC20(primaryAsset).balanceOf(address(this));
		uint256 reserved = partitionedFunds + pendingDeposits + accumulatedProtocolFees + accumulatedCuratorFees;
		return balance > reserved ? balance - reserved : 0;
	}

	/// @notice Available secondary balance for writing secondary-collateral series.
	function getAvailableSecondary() public view returns (uint256) {
		uint256 balance = IERC20(secondaryAsset).balanceOf(address(this));
		uint256 reserved = partitionedFundsSecondary
			+ pendingDepositsSecondary
			+ accumulatedProtocolFeesSecondary
			+ accumulatedCuratorFeesSecondary;
		return balance > reserved ? balance - reserved : 0;
	}

	function handlerIssue(Types.OptionSeries memory optionSeries) external override whenNotPaused nonReentrant onlyHandler returns (address) {
		return _issue(optionSeries, _getOptionRegistry());
	}

	function handlerWriteOption(
		Types.OptionSeries memory optionSeries,
		address seriesAddress,
		uint256 amount,
		uint256 premium,
		address premiumToken,
		address recipient
	) external override whenNotPaused nonReentrant onlyHandler epochNotLocked returns (uint256) {
		return _writeOption(optionSeries, seriesAddress, amount, premium, premiumToken, recipient);
	}

	function handlerBuybackOption(
		Types.OptionSeries memory optionSeries,
		uint256 amount,
		address seriesAddress,
		uint256 premium,
		address premiumToken,
		address seller
	) external override whenNotPaused nonReentrant onlyHandler epochNotLocked returns (uint256) {
		return _buybackOption(optionSeries, amount, seriesAddress, premium, premiumToken, seller);
	}

	function _issue(Types.OptionSeries memory optionSeries, IPhysicalOptionRegistry optionRegistry)
		internal
		returns (address series)
	{
		if (optionSeries.collateral != primaryAsset && optionSeries.collateral != secondaryAsset) revert LP_CollateralAssetInvalid();
		if (optionSeries.underlying != underlyingAsset) revert LP_UnderlyingAssetInvalid();
		if (optionSeries.strikeAsset != strikeAsset) revert LP_StrikeAssetInvalid();
		series = optionRegistry.issue(optionSeries);
		if (series == address(0)) revert LP_IssuanceFailed();
	}

	function _writeOption(
		Types.OptionSeries memory optionSeries,
		address seriesAddress,
		uint256 amount,
		uint256 premium,
		address premiumToken,
		address recipient
	) internal returns (uint256) {
		address _primary = primaryAsset;
		address _secondary = secondaryAsset;
		
		address collateralAsset = optionSeries.collateral;
		bool isSecondaryCollateral = (collateralAsset == _secondary);

		uint256 collateral;
		{
			uint8 collateralDec = ERC20(collateralAsset).decimals();
			if (optionSeries.isPut) {
				uint256 numerator = amount * uint256(optionSeries.strike) * (10 ** collateralDec);
				collateral = (numerator == 0) ? 0 : (numerator + OPYN_AMOUNT_STRIKE_PRODUCT_DECIMALS - 1) / OPYN_AMOUNT_STRIKE_PRODUCT_DECIMALS; 
			} else {
				if (collateralDec >= 8) {
					collateral = amount * (10 ** (collateralDec - 8));
				} else {
					uint256 divisor = 10 ** (8 - collateralDec);
					collateral = (amount + divisor - 1) / divisor;
				}
			}
		}

		bool isPrimaryPremium = (premiumToken == _primary);
		uint256 saleFee = (optionSaleFee > 0 && premium > 0) ? (premium * optionSaleFee) / MAX_BPS : 0;
		if (saleFee > 0) {
			uint256 curatorShare = (saleFee * curatorFeeShare) / MAX_BPS;
			uint256 protocolShare = saleFee - curatorShare;
			if (isPrimaryPremium) {
				accumulatedCuratorFees += curatorShare;
				accumulatedProtocolFees += protocolShare;
			} else {
				accumulatedCuratorFeesSecondary += curatorShare;
				accumulatedProtocolFeesSecondary += protocolShare;
			}
			emit OptionFeeCollected(seriesAddress, saleFee, curatorShare, protocolShare);
		}

		// Collateral check — getAvailableBalance excludes pendingDeposits (deposit isolation)
		if (isSecondaryCollateral) {
			if (collateral > getAvailableSecondary()) revert LP_InsufficientSecondary();
		} else {
			if (collateral > getAvailableBalance()) revert LP_InsufficientAvailable();
		}

		IPhysicalOptionRegistry optionRegistry = _getOptionRegistry();
		IERC20(collateralAsset).forceApprove(address(optionRegistry), collateral);
		uint256 otokenBalanceBefore = IERC20(seriesAddress).balanceOf(address(this));
		(, uint256 collateralUsed) = optionRegistry.open(seriesAddress, amount, collateral);
		uint256 otokensReceived = IERC20(seriesAddress).balanceOf(address(this)) - otokenBalanceBefore;

		if (isSecondaryCollateral) {
			secondaryCollateralAllocated += collateralUsed;
		} else {
			collateralAllocated += collateralUsed;
		}
		emit WriteOption(seriesAddress, amount, premium, collateralUsed, recipient);

		IERC20(seriesAddress).safeTransfer(recipient, otokensReceived);
		return amount;
	}

	function _buybackOption(
		Types.OptionSeries memory optionSeries,
		uint256 amount,
		address seriesAddress,
		uint256 premium,
		address premiumToken,
		address seller
	) internal returns (uint256) {
		address _primary = primaryAsset;
		address _secondary = secondaryAsset;
		
		IPhysicalOptionRegistry optionRegistry = _getOptionRegistry();
		(, uint256 collateralReturned) = optionRegistry.close(seriesAddress, amount, seller);

		bool isSecondaryCollateral = (optionSeries.collateral == _secondary);

		if (premiumToken == _primary) {
			if (getAvailableBalance() < premium) revert LP_InsufficientFundsForPremium();
		} else {
			if (getAvailableSecondary() < premium) revert LP_InsufficientSecondaryForPremium();
		}

		// NOTE: collateralReturned may differ from original allocation by ≤1 wei due to Opyn
		// rounding on partial closes. Drift bounded by 1 wei per partial buyback; resets on full settlement.
		if (isSecondaryCollateral) {
			if (collateralReturned <= secondaryCollateralAllocated) {
				secondaryCollateralAllocated -= collateralReturned;
			} else {
				secondaryCollateralAllocated = 0;
			}
		} else {
			if (collateralReturned <= collateralAllocated) {
				collateralAllocated -= collateralReturned;
			} else {
				collateralAllocated = 0;
			}
		}

		if (premium > 0) {
			IERC20(premiumToken).safeTransfer(seller, premium);
		}

		emit BuybackOption(seriesAddress, amount, premium, collateralReturned, seller);
		return amount;
	}

	function _redeem() internal returns (uint256) {
		(uint256 toRedeem, IPhysicalAccounting.DepositReceipt memory depositReceipt) = _getAccounting().redeem(
			msg.sender
		);
		if (toRedeem == 0) {
			depositReceipts[msg.sender] = depositReceipt;
			return 0;
		}
		delete depositReceipts[msg.sender];
		emit Redeem(msg.sender, toRedeem, depositReceipt.epoch); 
		_transfer(address(this), msg.sender, toRedeem);
		return toRedeem;
	}

	/// @dev Forward-scan from `withdrawalEpoch` to the first epoch that processed the
	///      withdrawal queue. Reverts when none. Both legs of a receipt are paid at that one
	///      epoch's prices.
	function _findProcessedEpoch(uint128 withdrawalEpoch) internal view returns (uint256) {
		uint256 currentEpoch = epoch;
		for (uint256 i = withdrawalEpoch; i < currentEpoch; i++) {
			if (epochWithdrawalsProcessed[i]) return i;
		}
		revert LP_WithdrawalNotProcessed();
	}

	function _getAccounting() internal view returns (IPhysicalAccounting) {
		return IPhysicalAccounting(protocol.accounting());
	}

	function _getOptionRegistry() internal view returns (IPhysicalOptionRegistry) {
		return IPhysicalOptionRegistry(protocol.optionRegistry());
	}

	/// @dev Asymmetric whitelist enforcement is INTENTIONAL: once a user has shares,
	///      they can always exit. The `from != address(this) && to != address(this)` condition
	///      is load-bearing: it exempts every share-flow that goes THROUGH the pool (withdrawal
	///      escrow, redeem, mint/burn during epoch execution). Touching that condition can
	///      either gate a previously-whitelisted user out of their own withdrawal — breaking
	///      exit liveness — or bypass whitelist on a true address-to-address transfer.
	function _update(address from, address to, uint256 value) internal virtual override {
		if (from != address(0) && to != address(0) && from != address(this) && to != address(this)) {
			if (isWhitelistEnabled) {
				if (!whitelistedAddresses[from]) revert LP_SenderNotWhitelisted();
				if (!whitelistedAddresses[to]) revert LP_RecipientNotWhitelisted();
			}
		}
		super._update(from, to, value);
	}

	function _authorizeUpgrade(address newImplementation) internal view override onlyUpgrader {
		newImplementation;
	}
}

contracts/Protocol.sol

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

import {AccessControl} from "./libraries/AccessControl.sol";
import {IAuthority} from "./interfaces/IAuthority.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

/**
 *  @title Contract used for storage of important contracts for the liquidity pool
 */
contract Protocol is UUPSUpgradeable, AccessControl {

	address public optionRegistry;

	address public accounting;

	/// @custom:oz-upgrades-unsafe-allow constructor
	constructor() {
		_disableInitializers();
	}

	/**
	 * @notice Initialize the Protocol contract
	 * @param _optionRegistry address of the OptionRegistry contract
	 * @param _authority address of the Authority contract
	 */
	function initialize(
		address _optionRegistry,
		address _authority
	) external initializer {
		__UUPSUpgradeable_init();
		__AccessControl_init(IAuthority(_authority));
		
		if (_optionRegistry == address(0) || _authority == address(0)) {
			revert("Protocol: Invalid address");
		}
		
		optionRegistry = _optionRegistry;
	}

	/**
	 * @notice Set the Accounting contract address
	 * @param _accounting address of the Accounting contract
	 * @dev only governor can call this function
	 */
	function changeAccounting(address _accounting) external onlyGovernor {
		if (_accounting == address(0)) {
			revert("Protocol: Invalid address");
		}
		accounting = _accounting;
	}

	function _authorizeUpgrade(address newImplementation) internal view override onlyUpgrader {
		newImplementation; 
	}
}

contracts/interfaces/IAuthority.sol

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

interface IAuthority {
	/* ========== EVENTS ========== */

	event GovernorPushed(address indexed from, address indexed to);
	event GuardianPushed(address indexed to);
	event ManagerPushed(address indexed from, address indexed to);
	event OptionHandlerPushed(address indexed to);
	event PricerPushed(address indexed to);

	event GovernorPulled(address indexed from, address indexed to);
	event GuardianRevoked(address indexed to);
	event ManagerPulled(address indexed from, address indexed to);
	event OptionHandlerRevoked(address indexed to);
	event PricerRevoked(address indexed to);

	/* ========== VIEW ========== */

	function governor() external view returns (address);

	function guardian(address _target) external view returns (bool);

	function manager() external view returns (address);

	function upgrader(address _target) external view returns (bool);

	function optionHandler(address _target) external view returns (bool);

	function pricer(address _target) external view returns (bool);
}

contracts/libraries/AccessControl.sol

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

import {IAuthority} from "../interfaces/IAuthority.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

/**
 *  @title Contract used for access control functionality, based off of OlympusDao Access Control
 */
abstract contract AccessControl is Initializable {

	event AuthorityUpdated(IAuthority authority);

	IAuthority public authority;

	/**
	 * @dev Initializes the authority
	 * @param _authority The authority contract address
	 */
	function __AccessControl_init(IAuthority _authority) internal onlyInitializing {
		__AccessControl_init_unchained(_authority);
	}

	function __AccessControl_init_unchained(IAuthority _authority) internal onlyInitializing {
		authority = _authority;
		emit AuthorityUpdated(_authority);
	}

	function setAuthority(IAuthority _newAuthority) external onlyGovernor {
		if (address(_newAuthority) == address(0)) {
			revert("AccessControl: Zero authority");
		}
		authority = _newAuthority;
		emit AuthorityUpdated(_newAuthority);
	}

	modifier onlyGovernor() {
		if (msg.sender != authority.governor()) revert("AccessControl: UNAUTHORIZED");
		_;
	}

	modifier onlyGuardian() {
		if (!authority.guardian(msg.sender) && msg.sender != authority.governor()) revert("AccessControl: UNAUTHORIZED");
		_;
	}

	modifier onlyManager() {
		if (msg.sender != authority.manager() && msg.sender != authority.governor())
			revert("AccessControl: UNAUTHORIZED");
		_;
	}

	modifier onlyUpgrader() {
		if (!authority.upgrader(msg.sender)) revert("AccessControl: UNAUTHORIZED");
		_;
	}

	modifier onlyOptionHandler() {
		if (!authority.optionHandler(msg.sender) && msg.sender != authority.governor()) revert("AccessControl: UNAUTHORIZED");
		_;
	}

	modifier onlyPricer() {
		if (!authority.pricer(msg.sender)) revert("AccessControl: UNAUTHORIZED");
		_;
	}

	/**
	 * @dev This empty reserved space is put in place to allow future versions to add new
	 * variables without shifting down storage in the inheritance chain.
	 */
	uint256[49] private __gap;
}

contracts/libraries/Types.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.0;

library Types {
	struct OptionSeries {
		uint64 expiration;
		uint128 strike;
		bool isPut;
		address underlying;
		address strikeAsset;
		address collateral;
	}
	struct Order {
		OptionSeries optionSeries;
		uint256 amount;
		uint256 price;
		uint256 orderExpiry;
		address counterparty; // buyer for writes, seller for buybacks
		address seriesAddress;
		bool isBuyback; // true = buyback order, false = write order
	}
	struct PhysicalOrder {
		OptionSeries optionSeries;
		uint256 amount;
		uint256 price;
		uint256 orderExpiry;
		address counterparty; // buyer for writes, seller for buybacks
		address seriesAddress;
		bool isBuyback; // true = buyback order, false = write order
		address premiumToken; // must be primaryAsset or secondaryAsset
	}
	// Rysk RFQ quote — signed by the maker (the trader requesting the trade).
	// In this protocol's convention the MAKER initiates the trade (sells when
	// isTakerBuy=true, buys when false); the TAKER is the LP-side responder
	// who signs the confirmation acknowledging the quote. The physical handler
	// accepts the premium token as an unsigned payload field (not covered by
	// either signature) so signatures interop with the broader Rysk RFQ tooling.
	struct RFQQuote {
		address assetAddress;
		uint256 chainId;
		bool isPut;
		uint256 strike;
		uint64 expiry;
		address maker;
		uint64 nonce;
		uint256 price;       // price per option in e18
		uint256 quantity;    // quantity in e18
		bool isTakerBuy;
		uint64 validUntil;
		address usd;
		address collateralAsset;
	}
	// Rysk RFQ confirmation — `taker` is the liquidity pool; signed on its behalf
	// by a handler-whitelisted RFQ signer (passed as the `rfqSigner` argument to
	// `executeRFQOrder`, alongside its signature over the confirmation digest).
	struct RFQConfirmation {
		address maker;
		address assetAddress;
		uint256 chainId;
		uint64 expiry;
		bool isPut;
		uint64 nonce;
		uint256 price;       // price per option in e18
		uint256 quantity;    // quantity in e18
		uint64 quoteNonce;
		bytes quoteSignature;
		uint256 strike;
		address taker;
		bool isTakerBuy;
		address usd;
		address collateralAsset;
		uint256 collateralAmount;
		uint256 gasFee;
		// Unsigned transport field: carried in the struct to mirror the backend's
		// confirmation object but NOT part of RFQ_CONFIRMATION_TYPEHASH — the digest
		// builder skips it, so existing confirmation signatures stay valid. Validated
		// on-chain against the pool's primary/secondary assets.
		address premiumAsset;
	}
}

contracts/physical/adapters/ILSDAdapter.sol

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

/// @title  ILSDAdapter
/// @notice Generic input-token → LSD-token converter used by the physical liquidity pool
///         to mint its primary (or secondary) LSD asset from an underlying received via
///         physical option settlement. Implementations encapsulate per-LSD deposit
///         mechanics (rate calc, native-gas unwrapping, fee handling) and must transfer
///         the minted LSD tokens to `receiver` before returning.
interface ILSDAdapter {
	/// @notice ERC20 the adapter pulls from `msg.sender`. Must differ from both
	///         primaryAsset and secondaryAsset of any pool that allowlists the adapter.
	function inputToken() external view returns (address);

	/// @notice ERC20 the adapter delivers to `receiver`. Must equal either primaryAsset
	///         or secondaryAsset of any pool that allowlists the adapter.
	function outputToken() external view returns (address);

	/// @notice Indicative quote at the current rate.
	function previewDeposit(uint256 amountIn) external view returns (uint256 amountOut);

	/// @notice Pull `amountIn` of inputToken from caller, deposit into the LSD, transfer
	///         outputToken to `receiver`. The pool trusts `amountOut` as the authoritative
	///         result — adapters are reviewed off-chain by the governor before allowlisting,
	///         so implementations MUST return the true amount delivered to `receiver` (no
	///         inflation, no claimed-but-undelivered values).
	/// @return amountOut actual outputToken minted and forwarded to `receiver`
	function deposit(uint256 amountIn, address receiver)
		external
		returns (uint256 amountOut);

	event Deposited(address indexed receiver, uint256 amountIn, uint256 amountOut);
}

contracts/physical/interfaces/IPhysicalAccounting.sol

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

/// @title Accounting interface for physically-settled vaults with dual-token pricing
/// @notice Off-chain pricer submits per-asset deposit + withdrawal prices each epoch,
///         computed off chain using a formula.
///         This contract converts between (primary deposit amount) ↔ (shares), and from
///         (shares) → (primary payout, secondary payout) at withdrawal.
interface IPhysicalAccounting {
	struct DepositReceipt {
		uint128 epoch;
		uint256 amountPrimary;   // primary token decimals
		uint256 amountSecondary; // secondary token decimals
	}

	struct WithdrawalReceipt {
		uint128 epoch;
		uint256 shares; // LP token decimals (matches primary token decimals)
	}

	/// @notice Aggregates same-epoch primary deposits into the receipt total. Returns
	///         existing-receipt amount + new amount when the depositor's receipt epoch
	///         equals the current pool epoch, else just the new amount. View only; the
	///         pool performs the state mutation. No cap is enforced here or by the pool.
	function depositPrimary(address depositor, uint256 _amount)
		external
		view
		returns (uint256 depositAmount);

	/// @notice Aggregates same-epoch secondary deposits into the receipt total. Returns
	///         existing-receipt amount + new amount when the depositor's receipt epoch
	///         equals the current pool epoch, else just the new amount. View only; the
	///         pool performs the state mutation. No cap is enforced here or by the pool.
	function depositSecondary(address depositor, uint256 _amount)
		external
		view
		returns (uint256 depositAmount);

	/**
	 * @notice Logic for allowing a user to redeem their shares from a previous epoch
	 * @param  redeemer the address making the redemption
	 * @return toRedeem the amount to actually redeem
	 * @return depositReceipt the updated deposit receipt
	 */
	function redeem(address redeemer)
		external
		view
		returns (uint256 toRedeem, DepositReceipt memory depositReceipt);

	/**
	 * @notice Get the number of redeemable shares from unredeemed deposits
	 * @param user the address to check
	 * @return redeemableShares the amount of shares available to redeem
	 */
	function getRedeemableShares(address user) external view returns (uint256 redeemableShares);

	/// @notice Both leg amounts the user could claim now. Reads `withdrawalReceipts` and prices
	///         both legs at the first epoch >= the receipt's epoch that processed the queue.
	///         Returns (0, 0) when there is no receipt or it has not been processed yet.
	function canCompleteWithdraw(address withdrawer)
		external
		view
		returns (uint256 primaryAmount, uint256 secondaryAmount);

	/// @notice Compute the next epoch's transition values from per-asset deposit + withdrawal
	///         prices. Share-mint sums both deposit legs at their own price; both withdrawal
	///         totals price the pool's single `pendingWithdrawals` queue. The pool processes the
	///         queue only when both `*AmountNeeded` are zero.
	function executeEpochCalculation(
		uint256 depositPricePrimary,
		uint256 depositPriceSecondary,
		uint256 withdrawalPricePrimary,
		uint256 withdrawalPriceSecondary
	)
		external
		view
		returns (
			uint256 sharesToMint,
			uint256 totalPrimaryWithdraw,
			uint256 totalSecondaryWithdraw,
			uint256 primaryAmountNeeded,
			uint256 secondaryAmountNeeded
		);

	/**
	 * @notice Convert an amount of either leg's asset to shares using that leg's per-share price
	 * @dev One function serves both legs; shares scale is `10**primaryDecimals` for both.
	 * @param _amount amount in the leg's native decimals (primary or secondary)
	 * @param assetPerShare the leg's tokens per whole share, in the leg's native decimals
	 */
	function sharesForAmount(uint256 _amount, uint256 assetPerShare)
		external
		view
		returns (uint256 shares);

	/**
	 * @notice Convert shares to an amount of either leg's asset using that leg's per-share price
	 * @dev One function serves both legs; shares scale is `10**primaryDecimals` for both.
	 * @param _shares shares to convert (LP token decimals = primary decimals)
	 * @param _assetPerShare the leg's tokens per whole share, in the leg's native decimals
	 */
	function amountForShares(uint256 _shares, uint256 _assetPerShare)
		external
		view
		returns (uint256 amount);
}

contracts/physical/interfaces/IPhysicalLiquidityPool.sol

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

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

/// @title Interface for the physically-settled Rysk Liquidity Pool
/// @notice Single-pool monolith holding both a primary and a secondary ERC20. Which side
///         locks as collateral is set per option series via `optionSeries.collateral`, not
///         per option kind; exercise proceeds flow naturally to the counter-asset side.
///         Shares are minted and redeemed at pricer-submitted per-epoch prices (one
///         deposit price and one withdrawal price per asset), computed off chain by the
///         pricer using a formula.
interface IPhysicalLiquidityPool is IERC20 {

	struct EpochData {
		uint256 epochNumber;
		uint256 depositPricePrimary;
		uint256 depositPriceSecondary;
		uint256 withdrawalPricePrimary;
		uint256 withdrawalPriceSecondary;
		uint256 timestamp;
	}

	struct VaultWithdrawalReceipt {
		uint128 epoch;
		uint256 shares;
	}

	/// @notice Which deposit legs are open. `Both` is the zero value, so a fresh pool
	///         accepts both legs until the governor changes it. `None` closes both legs.
	///         The pool reads the values as a closed-leg bitmask (bit 0 secondary, bit 1
	///         primary), so the order must not change.
	enum DepositMode {
		Both,
		PrimaryOnly,
		SecondaryOnly,
		None
	}

	/// @notice Get the primary asset address (deposit token; locks as collateral for
	///         option series whose `optionSeries.collateral == primaryAsset`)
	function primaryAsset() external view returns (address);

	/// @notice Get the underlying asset address
	function underlyingAsset() external view returns (address);

	/// @notice Get the strike asset address
	function strikeAsset() external view returns (address);

	/// @notice Get the total primary-asset collateral allocated to active options
	///         whose collateral side is primary
	function collateralAllocated() external view returns (uint256);

	/// @notice Get the total primary funds partitioned for processed withdrawals
	function partitionedFunds() external view returns (uint256);

	/// @notice Get the secondary asset address (locks as collateral for series whose
	///         `optionSeries.collateral == secondaryAsset`; is a valid premium
	///         denomination for either direction via the per-order `premiumToken`
	///         parameter; may receive ITM exercise proceeds when the series'
	///         exercise-payment token equals `secondaryAsset` for that deployment).
	function secondaryAsset() external view returns (address);

	/// @notice Get the total secondary-asset collateral allocated to active options
	///         whose collateral side is secondary
	function secondaryCollateralAllocated() external view returns (uint256);

	/// @notice Get the total secondary funds partitioned for processed withdrawals
	function partitionedFundsSecondary() external view returns (uint256);

	/// @notice Get the current epoch number
	function epoch() external view returns (uint256);

	/// @notice Get the per-share primary-asset deposit price for a specific epoch
	function epochDepositPricePrimary(uint256 epoch) external view returns (uint256);

	/// @notice Get the per-share secondary-asset deposit price for a specific epoch
	function epochDepositPriceSecondary(uint256 epoch) external view returns (uint256);

	/// @notice Get the per-share primary-asset withdrawal price for a specific epoch
	function epochWithdrawalPricePrimary(uint256 epoch) external view returns (uint256);

	/// @notice Get the per-share secondary-asset withdrawal price for a specific epoch
	function epochWithdrawalPriceSecondary(uint256 epoch) external view returns (uint256);

	/// @notice Whether `epoch` processed the withdrawal queue (both legs funded and
	///         partitioned, queued shares burned).
	function epochWithdrawalsProcessed(uint256 epoch) external view returns (bool);

	/// @notice Get complete epoch data including all four prices
	function getEpochData(uint256 _epoch) external view returns (EpochData memory);

	/// @notice Get a user's deposit receipt (extended for dual-asset deposits).
	function depositReceipts(address) external view returns (uint128 epoch, uint256 amountPrimary, uint256 amountSecondary);

	/// @notice Get a user's withdrawal receipt. One receipt covers both legs of its shares.
	function withdrawalReceipts(address) external view returns (uint128 epoch, uint256 shares);

	/// @notice Aggregate primary pending deposits for the current epoch.
	function pendingDeposits() external view returns (uint256);

	/// @notice Aggregate secondary pending deposits for the current epoch.
	function pendingDepositsSecondary() external view returns (uint256);

	/// @notice Aggregate shares pending withdrawal across all not-yet-processed epochs.
	///         Cleared only when an epoch can fund the whole queue on both legs.
	function pendingWithdrawals() external view returns (uint256);

	/// @notice Smallest secondary deposit: 100 whole secondary tokens at initialize, which also
	///         covers the decimal-pair floor, so an accepted deposit mints ≥1 share at unit pricing.
	///         The governor can change it with `setMinDeposit`.
	function minSecondaryDeposit() external view returns (uint256);

	/// @notice Smallest primary deposit, in primary-asset units. 0 at initialize (any nonzero
	///         amount); the governor can set it with `setMinDeposit`.
	function minPrimaryDeposit() external view returns (uint256);

	/// @notice Smallest withdrawal, in shares, whose secondary leg pays ≥1 wei at unit pricing
	///         (decimal-pair guard).
	function minSecondaryWithdraw() external view returns (uint256);

	/// @notice Get the dispute period in seconds
	function disputePeriod() external view returns (uint256);

	/// @notice Get the timestamp when epoch prices were set
	function epochPriceSetTimestamp(uint256 epoch) external view returns (uint256);

	/// @notice Which deposit legs are open (set by a keeper or the governor). Gates only `depositPrimary` and
	///         `depositSecondary`; redeem, withdrawals and epoch execution are unaffected.
	function depositMode() external view returns (DepositMode);

	/// @notice Primary-leg deposit cap (set by a keeper or the governor), 0 means no cap.
	///         `depositPrimary` reverts when `getAvailableBalance() + collateralAllocated +
	///         pendingDeposits + amount` would exceed it.
	function depositCapPrimary() external view returns (uint256);

	/// @notice Secondary-leg deposit cap (set by a keeper or the governor), 0 means no cap.
	///         `depositSecondary` reverts when `getAvailableSecondary() +
	///         secondaryCollateralAllocated + pendingDepositsSecondary + amount` would exceed it.
	function depositCapSecondary() external view returns (uint256);

	/// @notice Redeem shares from previous epochs (sums both deposit legs).
	function redeem() external returns (uint256);

	/// @notice Deposit primary asset toward the current epoch.
	///         Reverts if `_amount < minPrimaryDeposit` (0 at initialize).
	///         Reverts if `depositMode` is `SecondaryOnly` or `None`, or if the amount would
	///         push the primary leg past `depositCapPrimary`.
	function depositPrimary(uint256 _amount) external returns (bool);

	/// @notice Deposit secondary asset toward the current epoch.
	///         Reverts if `_amount < minSecondaryDeposit` (100 whole secondary tokens at initialize).
	///         Price-dependent residual dust above the floor remains accepted loss.
	///         Reverts if `depositMode` is `PrimaryOnly` or `None`, or if the amount would
	///         push the secondary leg past `depositCapSecondary`.
	function depositSecondary(uint256 _amount) external returns (bool);

	/// @notice Initiate a withdrawal of `_shares` covering both legs. Reverts if
	///         `_shares < minSecondaryWithdraw`, the epoch is priced, or a receipt is in flight.
	function initiateWithdraw(uint256 _shares) external;

	/// @notice Pay both legs of the user's receipt at the processing epoch's two withdrawal
	///         prices and clear the receipt. Reverts if no receipt or not processed.
	function completeWithdraw() external returns (uint256 primaryAmount, uint256 secondaryAmount);

	/// @notice Issue an option series
	function handlerIssue(Types.OptionSeries memory optionSeries) external returns (address);

	/// @notice Write options (amount in e8) — collateral pulled from the pool side
	///         indicated by `optionSeries.collateral` (primary or secondary)
	function handlerWriteOption(
		Types.OptionSeries memory optionSeries,
		address seriesAddress,
		uint256 amount,
		uint256 premium,
		address premiumToken,
		address recipient
	) external returns (uint256);

	/// @notice Buy back options from a seller, burning oTokens and returning collateral
	function handlerBuybackOption(
		Types.OptionSeries memory optionSeries,
		uint256 amount,
		address seriesAddress,
		uint256 premium,
		address premiumToken,
		address seller
	) external returns (uint256);

	/// @notice Get the available primary balance (excluding partitioned, pendingDeposits, fees)
	/// @dev Enforces deposit isolation — pendingDeposits are not usable until epoch execution
	function getAvailableBalance() external view returns (uint256);

	/// @notice Get the available secondary balance (excludes partitionedSecondary, pendingDepositsSecondary, feesSecondary).
	function getAvailableSecondary() external view returns (uint256);

	/// @notice Get the accumulated secondary protocol fees
	function accumulatedProtocolFeesSecondary() external view returns (uint256);

	/// @notice Get the accumulated secondary curator fees
	function accumulatedCuratorFeesSecondary() external view returns (uint256);

	/// @notice Check if whitelist is enabled for deposits
	function isWhitelistEnabled() external view returns (bool);

	/// @notice Check if an address is whitelisted
	function whitelistedAddresses(address account) external view returns (bool);

}

contracts/physical/interfaces/IPhysicalOptionRegistry.sol

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

import { Types } from "../../libraries/Types.sol";

/// @title Option registry interface for physically-settled options
/// @notice Extends the standard option lifecycle with physical settlement awareness.
///         settle() can return either the primary or secondary token depending on exercise.
/// @dev Currently mirrors cash-settled Opyn calls internally. Will be updated when the new
///      physically-settled Opyn is integrated.
interface IPhysicalOptionRegistry {
	/**
	 * @notice Either retrieves the option token if it already exists, or deploy it
	 * @param  optionSeries option series to issue
	 * @return the address of the option
	 */
	function issue(Types.OptionSeries memory optionSeries) external returns (address);

	/**
	 * @notice Open an options contract using collateral from the liquidity pool
	 * @param  _series the address of the option token to be created
	 * @param  amount the amount of options to deploy
	 * @param  collateralAmount the collateral required for the option
	 * @dev only callable by the liquidityPool
	 * @return if the transaction succeeded
	 * @return the amount of collateral taken from the liquidityPool
	 */
	function open(
		address _series,
		uint256 amount,
		uint256 collateralAmount
	) external returns (bool, uint256);

	/**
	 * @notice Close/reduce an options position by burning oTokens and withdrawing collateral
	 * @param  _series the address of the option token to burn
	 * @param  amount the amount of oTokens to burn in e8 (oToken standard)
	 * @param  from the address holding the oTokens (must have approved OptionRegistry)
	 * @dev only callable by the liquidityPool
	 * @return if the transaction succeeded
	 * @return the amount of collateral returned to the liquidityPool
	 */
	function close(
		address _series,
		uint256 amount,
		address from
	) external returns (bool, uint256);

	/**
	 * @notice Settle an options vault after expiry (physical settlement).
	 * @param  _series option series address.
	 * @return success transaction outcome.
	 * @return tokenReturned series.collateral on OTM expiry; the exercise-payment token
	 *         (series.strikeAsset for calls, series.underlying for puts) on ITM physical exercise.
	 * @return amountReturned amount of `tokenReturned` forwarded to the liquidity pool.
	 * @return amountLost collateral consumed by ITM physical exercise (originalCollateral - collatReceived),
	 *         in the series' collateral-asset native decimals.
	 * @return amountShort oToken amount the vault was short at settlement.
	 * @return vaultId the Opyn vault ID.
	 * @return originalCollateral the collateral the vault held immediately before settlement,
	 *         used by the pool to drive its `collateralAllocated` / `secondaryCollateralAllocated`
	 *         decrement.
	 * @dev callable only by the liquidity pool. The registry `safeTransfer`s `tokenReturned`
	 *      (and any residual collateral on ITM) directly to the pool; the pool then decrements
	 *      `collateralAllocated` or `secondaryCollateralAllocated` by `originalCollateral`
	 *      based on which side the series was collateralized on (`series.collateral`).
	 */
	function settle(address _series)
		external
		returns (
			bool success,
			address tokenReturned,
			uint256 amountReturned,
			uint256 amountLost,
			uint256 amountShort,
			uint256 vaultId,
			uint256 originalCollateral
		);

	/**
	 * @notice Redeem oTokens for payout (for ITM options after expiry)
	 * @param  _series the address of the option token to redeem
	 * @param  _amount the amount to redeem
	 * @return collateralRedeemed the amount of collateral received
	 */
	function redeem(address _series, uint256 _amount) external returns (uint256 collateralRedeemed);

	/**
	 * @notice Retrieves the option token if it exists
	 * @param  underlying is the address of the underlying asset of the option
	 * @param  strikeAsset is the address of the collateral asset of the option
	 * @param  expiration is the expiry timestamp of the option
	 * @param  isPut the type of option
	 * @param  strike is the strike price of the option - e8 format
	 * @param  collateral is the address of the asset to collateralize the option with
	 * @return the address of the option
	 */
	function getOtoken(
		address underlying,
		address strikeAsset,
		uint256 expiration,
		bool isPut,
		uint256 strike,
		address collateral
	) external view returns (address);

	/// @notice Registry record for a series (zero struct after settlement).
	function getSeriesInfo(address series) external view returns (Types.OptionSeries memory);
	/// @notice Leangamma vault id assigned to a series, or 0 if none.
	function vaultIds(address series) external view returns (uint256);
	/// @notice Configured leangamma Controller address.
	function gammaController() external view returns (address);
	/// @notice Configured leangamma oTokenFactory address.
	function oTokenFactory() external view returns (address);
	/// @notice Configured leangamma MarginPool address.
	function marginPool() external view returns (address);
	/// @notice Rotate the authorized liquidity pool. Governor-only.
	function setLiquidityPool(address _newLiquidityPool) external;
	/// @notice Rotate the leangamma AddressBook used for cache refreshes. Governor-only.
	function setAddressBook(address _newAddressBook) external;
	/// @notice Refresh cached leangamma module pointers from the current AddressBook. Governor-only.
	function refreshGammaAddressesFromAddressBook()
		external
		returns (address newOtokenFactory, address newGammaController, address newMarginPool);
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

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

pragma solidity ^0.8.20;

/**
 * @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]
 * ```solidity
 * 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 Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._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 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._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() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @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 {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

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

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

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.20;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
    /// @custom:storage-location erc7201:openzeppelin.storage.ERC20
    struct ERC20Storage {
        mapping(address account => uint256) _balances;

        mapping(address account => mapping(address spender => uint256)) _allowances;

        uint256 _totalSupply;

        string _name;
        string _symbol;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;

    function _getERC20Storage() private pure returns (ERC20Storage storage $) {
        assembly {
            $.slot := ERC20StorageLocation
        }
    }

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        ERC20Storage storage $ = _getERC20Storage();
        $._name = name_;
        $._symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            $._totalSupply += value;
        } else {
            uint256 fromBalance = $._balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                $._balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                $._totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                $._balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        $._allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol

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

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

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

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

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

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

lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

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

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

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

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

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
    }

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

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

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

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

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

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

lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol

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

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

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

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

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

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

    function _nonReentrantBefore() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol

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

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.21;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity ^0.8.20;

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

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

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

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

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

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

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

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

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

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

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

lib/openzeppelin-contracts/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

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

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

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

lib/openzeppelin-contracts/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Настройки компилятораПоказать
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "contracts/physical/leangamma/:forge-std/=contracts/physical/leangamma/lib/forge-std/src/",
    "prb-math/=lib/prb-math/",
    "@rage/core/=lib/core/",
    "@chainlink/=lib/chainlink/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@uniswap/v3-core-0.8-support/=lib/v3-core/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v3-periphery/=lib/v3-periphery/",
    "core/=lib/core/contracts/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.