Blockchain / Global / Address

Contract

0xC10feaC8c113Fb71549bC8be778d6723Be93cB44

Balance
0 SOMI
Transactions sent
1
Type
Contract · 5,986 bytes of code

MangroveChainlinkOracleV2 Verified

Compiler
solc 0.8.28+commit.7893614a
Language
Solidity
Optimization
Yes, 200 runs
EVM version
prague
License
—
Verified
2026-10-12

src/oracles/chainlink/v2/MangroveChainlinkOracleV2.sol

and 28 more files

Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {IOracle} from "../../IOracle.sol";
import {OLKey} from "@mgv/src/core/MgvLib.sol";
import {Tick} from "@mgv/lib/core/TickLib.sol";
import {ChainlinkConsumer} from "../../../vendor/chainlink/ChainlinkConsumer.sol";
import {AggregatorV3Interface} from "../../../vendor/chainlink/AggregatorV3Interface.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {MangroveVaultErrors} from "../../../lib/MangroveVaultErrors.sol";
import {ERC4626Consumer} from "../../../vendor/ERC4626/ERC4626Consumer.sol";

/**
 * @title ChainlinkFeed
 * @notice Struct to hold Chainlink feed information
 * @param feed Address of the Chainlink price feed
 * @param baseDecimals Number of decimals for the base token
 * @param quoteDecimals Number of decimals for the quote token
 */
struct ChainlinkFeed {
  address feed;
  uint256 baseDecimals;
  uint256 quoteDecimals;
}

/**
 * @title ERC4626Feed
 * @notice Struct to hold ERC4626 vault information
 * @param vault Address of the ERC4626 vault
 * @param conversionSample Sample amount used for price conversion calculations in the vault
 */
struct ERC4626Feed {
  address vault;
  uint256 conversionSample;
}

/**
 * @title MangroveChainlinkOracle
 * @notice An oracle adapter for Mangrove that supports up to 4 Chainlink price feeds and 2 ERC4626 vault feeds
 * @dev This contract combines up to 4 Chainlink price feeds and 2 ERC4626 vault feeds to create a single price oracle for Mangrove.
 *      For Chainlink feeds, it supports up to 2 feeds to combine for the base price, plus two inverse feeds for the quote price.
 *      For example, if we have A/B, B/C, D/C, and E/D feeds, we can combine them into A/E.
 *      For ERC4626 vaults, it supports one vault feed for the base and one for the quote.
 *      For example, if we have a vault vA containing A tokens (vA/A feed) and a vault vE containing E tokens (vE/E feed),
 *      we can compose them into a vA/vE feed with the above composition.
 *
 * @dev The price is represented as quote/base, while on Mangrove it's inbound/outbound.
 *      Inbound tokens are received by the maker, outbound tokens are sent by the maker.
 *      The oracle outputs a tick corresponding to the price on the inbound=base/outbound=quote market.
 */
contract MangroveChainlinkOracleV2 is IOracle {
  using ChainlinkConsumer for AggregatorV3Interface;
  using Math for uint256;
  using ERC4626Consumer for IERC4626;

  /// @notice The ERC4626 vault for the base token
  IERC4626 public immutable baseVault;
  /// @notice The ERC4626 vault for the quote token
  IERC4626 public immutable quoteVault;

  /// @notice Sample amount used for price conversion calculations in the base vault
  uint256 public immutable baseVaultConversionSample;
  /// @notice Sample amount used for price conversion calculations in the quote vault
  uint256 public immutable quoteVaultConversionSample;

  /// @notice The first Chainlink price feed for the base token
  AggregatorV3Interface public immutable baseFeed1;
  /// @notice The second Chainlink price feed for the base token
  AggregatorV3Interface public immutable baseFeed2;
  /// @notice The first Chainlink price feed for the quote token
  AggregatorV3Interface public immutable quoteFeed1;
  /// @notice The second Chainlink price feed for the quote token
  AggregatorV3Interface public immutable quoteFeed2;

  /// @notice The number of decimals in the price returned by baseFeed1
  uint256 public immutable baseFeed1Decimals;
  /// @notice The number of decimals in the price returned by baseFeed2
  uint256 public immutable baseFeed2Decimals;
  /// @notice The number of decimals in the price returned by quoteFeed1
  uint256 public immutable quoteFeed1Decimals;
  /// @notice The number of decimals in the price returned by quoteFeed2
  uint256 public immutable quoteFeed2Decimals;

  /// @notice The number of decimals for the base token in baseFeed1
  uint256 public immutable baseFeed1BaseDecimals;
  /// @notice The number of decimals for the quote token in baseFeed1
  uint256 public immutable baseFeed1QuoteDecimals;

  /// @notice The number of decimals for the base token in baseFeed2
  uint256 public immutable baseFeed2BaseDecimals;
  /// @notice The number of decimals for the quote token in baseFeed2
  uint256 public immutable baseFeed2QuoteDecimals;

  /// @notice The number of decimals for the base token in quoteFeed1
  uint256 public immutable quoteFeed1BaseDecimals;
  /// @notice The number of decimals for the quote token in quoteFeed1
  uint256 public immutable quoteFeed1QuoteDecimals;

  /// @notice The number of decimals for the base token in quoteFeed2
  uint256 public immutable quoteFeed2BaseDecimals;
  /// @notice The number of decimals for the quote token in quoteFeed2
  uint256 public immutable quoteFeed2QuoteDecimals;

  /**
   * @notice Constructs a new MangroveChainlinkOracle
   * @param _baseFeed1 ChainlinkFeed struct for the first base feed
   * @param _baseFeed2 ChainlinkFeed struct for the second base feed
   * @param _quoteFeed1 ChainlinkFeed struct for the first quote feed
   * @param _quoteFeed2 ChainlinkFeed struct for the second quote feed
   * @param _baseVault ERC4626Feed struct for the base vault
   * @param _quoteVault ERC4626Feed struct for the quote vault
   */
  constructor(
    ChainlinkFeed memory _baseFeed1,
    ChainlinkFeed memory _baseFeed2,
    ChainlinkFeed memory _quoteFeed1,
    ChainlinkFeed memory _quoteFeed2,
    ERC4626Feed memory _baseVault,
    ERC4626Feed memory _quoteVault
  ) {
    baseFeed1 = AggregatorV3Interface(_baseFeed1.feed);
    baseFeed2 = AggregatorV3Interface(_baseFeed2.feed);
    quoteFeed1 = AggregatorV3Interface(_quoteFeed1.feed);
    quoteFeed2 = AggregatorV3Interface(_quoteFeed2.feed);

    baseVault = IERC4626(_baseVault.vault);
    quoteVault = IERC4626(_quoteVault.vault);

    baseVaultConversionSample = _baseVault.conversionSample;
    quoteVaultConversionSample = _quoteVault.conversionSample;

    baseFeed1Decimals = baseFeed1.getDecimals();
    baseFeed2Decimals = baseFeed2.getDecimals();
    quoteFeed1Decimals = quoteFeed1.getDecimals();
    quoteFeed2Decimals = quoteFeed2.getDecimals();

    baseFeed1BaseDecimals = _baseFeed1.baseDecimals;
    baseFeed1QuoteDecimals = _baseFeed1.quoteDecimals;
    baseFeed2BaseDecimals = _baseFeed2.baseDecimals;
    baseFeed2QuoteDecimals = _baseFeed2.quoteDecimals;
    quoteFeed1BaseDecimals = _quoteFeed1.baseDecimals;
    quoteFeed1QuoteDecimals = _quoteFeed1.quoteDecimals;
    quoteFeed2BaseDecimals = _quoteFeed2.baseDecimals;
    quoteFeed2QuoteDecimals = _quoteFeed2.quoteDecimals;
  }

  /**
   * @notice Calculates the current price tick based on the Chainlink price feeds
   * @dev This function combines up to four price feeds to determine the final tick:
   *      - Two base feeds (baseFeed1 and baseFeed2) are added together
   *      - Two quote feeds (quoteFeed1 and quoteFeed2) are subtracted
   *      This allows for complex price calculations, such as A/E derived from A/B, B/C, D/C, and E/D feeds
   * @return Tick The calculated price tick for use in Mangrove's order book
   */
  function tick() public view returns (Tick) {
    return Tick.wrap(
      baseFeed1.getTick(baseFeed1Decimals, baseFeed1BaseDecimals, baseFeed1QuoteDecimals)
        + baseFeed2.getTick(baseFeed2Decimals, baseFeed2BaseDecimals, baseFeed2QuoteDecimals)
        + baseVault.getTick(baseVaultConversionSample)
        - quoteFeed1.getTick(quoteFeed1Decimals, quoteFeed1BaseDecimals, quoteFeed1QuoteDecimals)
        - quoteFeed2.getTick(quoteFeed2Decimals, quoteFeed2BaseDecimals, quoteFeed2QuoteDecimals)
        - quoteVault.getTick(quoteVaultConversionSample)
    );
  }
}

Other files

  • lib/forge-std/src/console.sol
    // SPDX-License-Identifier: MIT
    pragma solidity >=0.4.22 <0.9.0;
    
    library console {
        address constant CONSOLE_ADDRESS =
            0x000000000000000000636F6e736F6c652e6c6f67;
    
        function _sendLogPayloadImplementation(bytes memory payload) internal view {
            address consoleAddress = CONSOLE_ADDRESS;
            /// @solidity memory-safe-assembly
            assembly {
                pop(
                    staticcall(
                        gas(),
                        consoleAddress,
                        add(payload, 32),
                        mload(payload),
                        0,
                        0
                    )
                )
            }
        }
    
        function _castToPure(
          function(bytes memory) internal view fnIn
        ) internal pure returns (function(bytes memory) pure fnOut) {
            assembly {
                fnOut := fnIn
            }
        }
    
        function _sendLogPayload(bytes memory payload) internal pure {
            _castToPure(_sendLogPayloadImplementation)(payload);
        }
    
        function log() internal pure {
            _sendLogPayload(abi.encodeWithSignature("log()"));
        }
    
        function logInt(int256 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
        }
    
        function logUint(uint256 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
        }
    
        function logString(string memory p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string)", p0));
        }
    
        function logBool(bool p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
        }
    
        function logAddress(address p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address)", p0));
        }
    
        function logBytes(bytes memory p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
        }
    
        function logBytes1(bytes1 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
        }
    
        function logBytes2(bytes2 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
        }
    
        function logBytes3(bytes3 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
        }
    
        function logBytes4(bytes4 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
        }
    
        function logBytes5(bytes5 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
        }
    
        function logBytes6(bytes6 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
        }
    
        function logBytes7(bytes7 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
        }
    
        function logBytes8(bytes8 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
        }
    
        function logBytes9(bytes9 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
        }
    
        function logBytes10(bytes10 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
        }
    
        function logBytes11(bytes11 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
        }
    
        function logBytes12(bytes12 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
        }
    
        function logBytes13(bytes13 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
        }
    
        function logBytes14(bytes14 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
        }
    
        function logBytes15(bytes15 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
        }
    
        function logBytes16(bytes16 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
        }
    
        function logBytes17(bytes17 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
        }
    
        function logBytes18(bytes18 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
        }
    
        function logBytes19(bytes19 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
        }
    
        function logBytes20(bytes20 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
        }
    
        function logBytes21(bytes21 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
        }
    
        function logBytes22(bytes22 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
        }
    
        function logBytes23(bytes23 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
        }
    
        function logBytes24(bytes24 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
        }
    
        function logBytes25(bytes25 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
        }
    
        function logBytes26(bytes26 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
        }
    
        function logBytes27(bytes27 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
        }
    
        function logBytes28(bytes28 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
        }
    
        function logBytes29(bytes29 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
        }
    
        function logBytes30(bytes30 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
        }
    
        function logBytes31(bytes31 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
        }
    
        function logBytes32(bytes32 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
        }
    
        function log(uint256 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
        }
    
        function log(int256 p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
        }
    
        function log(string memory p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string)", p0));
        }
    
        function log(bool p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
        }
    
        function log(address p0) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address)", p0));
        }
    
        function log(uint256 p0, uint256 p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256)", p0, p1));
        }
    
        function log(uint256 p0, string memory p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string)", p0, p1));
        }
    
        function log(uint256 p0, bool p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool)", p0, p1));
        }
    
        function log(uint256 p0, address p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address)", p0, p1));
        }
    
        function log(string memory p0, uint256 p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1));
        }
    
        function log(string memory p0, int256 p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,int256)", p0, p1));
        }
    
        function log(string memory p0, string memory p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
        }
    
        function log(string memory p0, bool p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
        }
    
        function log(string memory p0, address p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
        }
    
        function log(bool p0, uint256 p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256)", p0, p1));
        }
    
        function log(bool p0, string memory p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
        }
    
        function log(bool p0, bool p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
        }
    
        function log(bool p0, address p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
        }
    
        function log(address p0, uint256 p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256)", p0, p1));
        }
    
        function log(address p0, string memory p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
        }
    
        function log(address p0, bool p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
        }
    
        function log(address p0, address p1) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
        }
    
        function log(uint256 p0, uint256 p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256)", p0, p1, p2));
        }
    
        function log(uint256 p0, uint256 p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string)", p0, p1, p2));
        }
    
        function log(uint256 p0, uint256 p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool)", p0, p1, p2));
        }
    
        function log(uint256 p0, uint256 p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address)", p0, p1, p2));
        }
    
        function log(uint256 p0, string memory p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256)", p0, p1, p2));
        }
    
        function log(uint256 p0, string memory p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string)", p0, p1, p2));
        }
    
        function log(uint256 p0, string memory p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool)", p0, p1, p2));
        }
    
        function log(uint256 p0, string memory p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address)", p0, p1, p2));
        }
    
        function log(uint256 p0, bool p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256)", p0, p1, p2));
        }
    
        function log(uint256 p0, bool p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string)", p0, p1, p2));
        }
    
        function log(uint256 p0, bool p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool)", p0, p1, p2));
        }
    
        function log(uint256 p0, bool p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address)", p0, p1, p2));
        }
    
        function log(uint256 p0, address p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256)", p0, p1, p2));
        }
    
        function log(uint256 p0, address p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string)", p0, p1, p2));
        }
    
        function log(uint256 p0, address p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool)", p0, p1, p2));
        }
    
        function log(uint256 p0, address p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address)", p0, p1, p2));
        }
    
        function log(string memory p0, uint256 p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256)", p0, p1, p2));
        }
    
        function log(string memory p0, uint256 p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string)", p0, p1, p2));
        }
    
        function log(string memory p0, uint256 p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool)", p0, p1, p2));
        }
    
        function log(string memory p0, uint256 p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address)", p0, p1, p2));
        }
    
        function log(string memory p0, string memory p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256)", p0, p1, p2));
        }
    
        function log(string memory p0, string memory p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
        }
    
        function log(string memory p0, string memory p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
        }
    
        function log(string memory p0, string memory p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
        }
    
        function log(string memory p0, bool p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256)", p0, p1, p2));
        }
    
        function log(string memory p0, bool p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
        }
    
        function log(string memory p0, bool p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
        }
    
        function log(string memory p0, bool p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
        }
    
        function log(string memory p0, address p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256)", p0, p1, p2));
        }
    
        function log(string memory p0, address p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
        }
    
        function log(string memory p0, address p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
        }
    
        function log(string memory p0, address p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
        }
    
        function log(bool p0, uint256 p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256)", p0, p1, p2));
        }
    
        function log(bool p0, uint256 p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string)", p0, p1, p2));
        }
    
        function log(bool p0, uint256 p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool)", p0, p1, p2));
        }
    
        function log(bool p0, uint256 p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address)", p0, p1, p2));
        }
    
        function log(bool p0, string memory p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256)", p0, p1, p2));
        }
    
        function log(bool p0, string memory p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
        }
    
        function log(bool p0, string memory p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
        }
    
        function log(bool p0, string memory p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
        }
    
        function log(bool p0, bool p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256)", p0, p1, p2));
        }
    
        function log(bool p0, bool p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
        }
    
        function log(bool p0, bool p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
        }
    
        function log(bool p0, bool p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
        }
    
        function log(bool p0, address p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256)", p0, p1, p2));
        }
    
        function log(bool p0, address p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
        }
    
        function log(bool p0, address p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
        }
    
        function log(bool p0, address p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
        }
    
        function log(address p0, uint256 p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256)", p0, p1, p2));
        }
    
        function log(address p0, uint256 p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string)", p0, p1, p2));
        }
    
        function log(address p0, uint256 p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool)", p0, p1, p2));
        }
    
        function log(address p0, uint256 p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address)", p0, p1, p2));
        }
    
        function log(address p0, string memory p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256)", p0, p1, p2));
        }
    
        function log(address p0, string memory p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
        }
    
        function log(address p0, string memory p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
        }
    
        function log(address p0, string memory p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
        }
    
        function log(address p0, bool p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256)", p0, p1, p2));
        }
    
        function log(address p0, bool p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
        }
    
        function log(address p0, bool p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
        }
    
        function log(address p0, bool p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
        }
    
        function log(address p0, address p1, uint256 p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256)", p0, p1, p2));
        }
    
        function log(address p0, address p1, string memory p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
        }
    
        function log(address p0, address p1, bool p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
        }
    
        function log(address p0, address p1, address p2) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
        }
    
        function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, uint256 p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, string memory p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, bool p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,address)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,string)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,bool)", p0, p1, p2, p3));
        }
    
        function log(uint256 p0, address p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, uint256 p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, string memory p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, bool p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
        }
    
        function log(string memory p0, address p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, uint256 p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, string memory p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, bool p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
        }
    
        function log(bool p0, address p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, uint256 p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, string memory p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, bool p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, uint256 p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, uint256 p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, uint256 p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, uint256 p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, string memory p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, string memory p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, string memory p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, string memory p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, bool p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, bool p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, bool p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, bool p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, address p2, uint256 p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint256)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, address p2, string memory p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, address p2, bool p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
        }
    
        function log(address p0, address p1, address p2, address p3) internal pure {
            _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
        }
    }
    
  • lib/forge-std/src/console2.sol
    // SPDX-License-Identifier: MIT
    pragma solidity >=0.4.22 <0.9.0;
    
    import {console as console2} from "./console.sol";
    
  • lib/mangrove-core/lib/IERC20.sol
    // SPDX-License-Identifier: MIT
    pragma solidity >=0.6.2;
    
    interface IERC20 {
      function totalSupply() external view returns (uint);
    
      function balanceOf(address account) external view returns (uint);
    
      function transfer(address recipient, uint amount) external returns (bool);
    
      function allowance(address owner, address spender) external view returns (uint);
    
      function approve(address spender, uint amount) external returns (bool);
    
      function transferFrom(address sender, address recipient, uint amount) external returns (bool);
    
      function symbol() external view returns (string memory);
    
      event Transfer(address indexed from, address indexed to, uint value);
      event Approval(address indexed owner, address indexed spender, uint value);
    
      function decimals() external view returns (uint8);
    
      function name() external view returns (string memory);
    }
    
  • lib/mangrove-core/lib/core/BitLib.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.17;
    
    library BitLib {
      // - if x is a nonzero uint64: 
      //   return number of zeroes in x that do not have a 1 to their right
      // - otherwise:
      //    return 64
      function ctz64(uint x) internal pure returns (uint256 c) {
        unchecked {
          assembly ("memory-safe") {
            // clean
            x:= and(x,0xffffffffffffffff)
    
            // 7th bit
            c:= shl(6,iszero(x))
    
            // isolate lsb
            x := and(x, add(not(x), 1))
    
            // 6th bit
            c := or(c,shl(5, lt(0xffffffff, x)))
    
            // debruijn lookup
            c := or(c, byte(shr(251, mul(shr(c, x), shl(224, 0x077cb531))), 
                0x00011c021d0e18031e16140f191104081f1b0d17151310071a0c12060b050a09))
          }
        }
      }
    
      // Function fls is MIT License. Copyright (c) 2022 Solady.
    /// @dev find last set.
        /// Returns the index of the most significant bit of `x`,
        /// counting from the least significant bit position.
        /// If `x` is zero, returns 256.
        /// Equivalent to `log2(x)`, but without reverting for the zero case.
        function fls(uint256 x) internal pure returns (uint256 r) {
            assembly ("memory-safe") {
                r := shl(8, iszero(x))
    
                r := or(r, shl(7, lt(0xffffffffffffffffffffffffffffffff, x)))
                r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
    
                // For the remaining 32 bits, use a De Bruijn lookup.
                x := shr(r, x)
                x := or(x, shr(1, x))
                x := or(x, shr(2, x))
                x := or(x, shr(4, x))
                x := or(x, shr(8, x))
                x := or(x, shr(16, x))
    
                // forgefmt: disable-next-item
                r := or(r, byte(shr(251, mul(x, shl(224, 0x07c4acdd))),
                    0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f))
            }
        }
    }
    
  • lib/mangrove-core/lib/core/Constants.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.17;
    
    /* The constants below are written as literals to optimize gas. For all the relevant constants here, the non-literal expression that computes them is checked in `Constants.t.sol`. */
    
    uint constant ONE = 1;
    uint constant ONES = type(uint).max;
    uint constant TOPBIT = 0x8000000000000000000000000000000000000000000000000000000000000000;
    uint constant NOT_TOPBIT = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
    
    /* **sizes must match field sizes in `structs.ts` where relevant** */
    
    /* Number of bits used to represent a tick */
    uint constant TICK_BITS = 21;
    /* Number of bits used to represent an offer id */
    uint constant OFFER_BITS = 32;
    /* Maximum possible size of a field -- protects against wrong code changes. Constraint given by `BitLib.ctz64`. */
    uint constant MAX_FIELD_SIZE = 64;
    
    /* `X_SIZE_BITS` is 1+log2 of the size of `X`, where size is the number of elements it holds.In a field, an element is a bit; in a leaf, an element is a pair of offer ids. For `LEVEL`s and `ROOT`, the value must be exact, so only power-of-2 sizes are allowed. */
    uint constant LEAF_SIZE_BITS = 2; 
    uint constant LEVEL_SIZE_BITS = 6;
    uint constant ROOT_SIZE_BITS = 1;
    
    /* `X_SIZE` is `2**X_SIZE_BITS` */
    int constant LEAF_SIZE = 4;
    int constant LEVEL_SIZE = 64;
    int constant ROOT_SIZE = 2;
    
    /* `X_SIZE_MASK` is `0...01...1` where the number of 1s is `X_SIZE_BITS` */
    uint constant LEAF_SIZE_MASK = 0x3;
    uint constant LEVEL_SIZE_MASK = 0x3f;
    uint constant ROOT_SIZE_MASK = 0x1;
    /* `0...01...1` with `OFFER_BITS` 1s at the end */
    uint constant OFFER_MASK = 0xffffffff;
    
    /* Same as `ROOT_SIZE` */
    int constant NUM_LEVEL1 = 2;
    /* Same as `NUM_LEVEL1 * LEVEL_SIZE` */
    int constant NUM_LEVEL2 = 128;
    /* Same as `NUM_LEVEL2 * LEVEL_SIZE` */
    int constant NUM_LEVEL3 = 8192;
    /* Same as `NUM_LEVEL3 * LEVEL_SIZE` */
    int constant NUM_LEAFS = 524288;
    /* Same as `NUM_LEAFS * LEAF` */
    int constant NUM_BINS = 2097152;
    /* min and max bins are defined like min and max int. */
    int constant MIN_BIN = -1048576;
    int constant MAX_BIN = 1048575;
    
    /* The tick range is the largest such that the mantissa of `1.0001^MAX_TICK` fits on 128 bits (and thus can be multiplied by volumes). */
    int constant MIN_TICK = -887272;
    int constant MAX_TICK = 887272;
    /* These are reference values for what the function `tickFromRatio` function will return, not the most possible accurate values for the min and max tick. */
    uint constant MIN_RATIO_MANTISSA = 170153974464283981435225617938057077692;
    int constant MIN_RATIO_EXP = 255;
    uint constant MAX_RATIO_MANTISSA = 340256786836388094050805785052946541084;
    int constant MAX_RATIO_EXP = 0;
    /* `MANTISSA_BITS` is the number of bits used in the mantissa of normalized floats that represent ratios. 128 means we can multiply all allowed volumes by the mantissa and not overflow. */
    uint constant MANTISSA_BITS = 128;
    uint constant MANTISSA_BITS_MINUS_ONE = 127;
    /* 
    With `|tick|<=887272` and normalized mantissas on 128 bits, the maximum possible mantissa is `340282295208261841796968287475569060645`, so the maximum safe volume before overflow is `NO_OVERFLOW_AMOUNT = 340282438633630198193436196978374475856` (slightly above `2**128`).
    
    For ease of use, we could pick a simpler, slightly smaller max safe volume: `(1<<128)-1`.
    
    However the `*ByVolume` functions get a price by (abstractly) performing `outboundAmount/inboundAmount`. If we limit all volumes to `NO_OVERFLOW_AMOUNT` but aren't more restrictive than that, since `type(uint128).max > 1.0001**MAX_TICK`, we will get ratios that are outside the price boundaries.
    
    We thus pick a uniform, easy to remember constraint on volumes that works everywhere: `(1<<127)-1`
    */
    uint constant MAX_SAFE_VOLUME = 170141183460469231731687303715884105727;
    
    /* When a market order consumes offers, the implementation uses recursion consumes additional EVM stack space at each new offer. To avoid reverting due to stack overflow, Mangrove keeps a counter and stops the market order when it reaches a maximum recursion depth. `INITIAL_MAX_RECURSION_DEPTH` is the maximum recursion depth given at deployment time.
    
    See `maxRecursionDepth` in `structs.ts`
    
    Without optimizer enabled it fails above 79. With optimizer and 200 runs it fails above 80. Set default a bit lower to be safe. */
    uint constant INITIAL_MAX_RECURSION_DEPTH = 75;
    
    /* When a market order consumes offers, it may use gas on offers that fail to deliver. To avoid reverts after a string of failing offers that consumes more gas than is available in a block, Mangrove stops a market order after it has gone through failing offers such that their cumulative `gasreq` is greater than the global `maxGasreqForFailingOffers` parameter. At deployment, `maxGasreqForFailingOffers` is set to:
    ```
    INITIAL_MAX_GASREQ_FOR_FAILING_OFFERS_MULTIPLIER * gasmax
    ``` */
    uint constant INITIAL_MAX_GASREQ_FOR_FAILING_OFFERS_MULTIPLIER = 3;
    
    /* Those two constants are used in `TickLib.ratioFromTick` to convert a log base 1.0001 to a log base 2. */
    uint constant LOG_BP_SHIFT = 235;
    uint constant LOG_BP_2X235 = 382733217082594961806491056566382061424140926068392360945012727618364717537;
  • lib/mangrove-core/lib/core/DensityLib.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.17;
    
    import {Field} from "@mgv/lib/core/TickTreeLib.sol";
    import {ONES} from "@mgv/lib/core/Constants.sol";
    import {BitLib} from "@mgv/lib/core/BitLib.sol";
    
    /*
    
    The density of a semibook is the number of outbound tokens per gas required. An offer must a respect a semibook's density.
    
    Density can be < 1.
    
    The density of a semibook is stored as a 9 bits float. For convenience, governance functions read density as a 96.32 fixed point number. The functions below give conversion utilities between the two formats
    
    As a guideline, fixed-point densities should be uints and should use hungarian notation (for instance `uint density96X32`). Floating-point densities should use the Density user-defined type.
    
    The float <-> fixed conversion is format agnostic but the expectation is that fixed points are 96x32, and floats are 2-bit mantissa, 7bit exponent with bias 32. 
    
    The encoding is nonstandard so the code can be simpler.
    
    There are no subnormal floats in this encoding, `[exp][mantissa]` means:
    
    ```
    if exp is 0 or 1:   0bmantissa   * 2^-32
    otherwise:          0b1.mantissa * 2^(exp-32)
    ```
    
    so the small values have some holes:
    
    ```
      coeff   exponent  available    |   coeff   exponent  available
      --------------------------------------------------------------
      0b0.00                         |  0b1.10     -31
      0b1.00     -32                 |  0b1.11     -31        no
      0b1.01     -32        no       |  0b1.00     -30
      0b1.10     -32        no       |  0b1.01     -30
      0b1.11     -32        no       |  0b1.10     -30
      0b1.00     -31                 |  0b1.11     -30
      0b1.01     -31        no       |  0b1.00     -29
    ```
    */
    
    type Density is uint;
    using DensityLib for Density global;
    
    library DensityLib {
      /* Numbers in this file assume that density is 9 bits in structs.ts */
      uint constant BITS = 9; // must match structs.ts
      uint constant MANTISSA_BITS = 2;
      uint constant SUBNORMAL_LIMIT = ~(ONES << (MANTISSA_BITS+1));
      uint constant MANTISSA_MASK = ~(ONES << MANTISSA_BITS);
      uint constant MASK = ~(ONES << BITS);
      uint constant MANTISSA_INTEGER = 1 << MANTISSA_BITS;
      uint constant EXPONENT_BITS = BITS - MANTISSA_BITS;
    
      function eq(Density a, Density b) internal pure returns (bool) { unchecked {
        return Density.unwrap(a) == Density.unwrap(b);
      }}
    
      /* Check the size of a fixed-point formatted density */
      function checkDensity96X32(uint density96X32) internal pure returns (bool) { unchecked {
        return density96X32 < (1<<(96+32));
      }}
    
      /* fixed-point -> float conversion */
      /* Warning: no bit cleaning (expected to be done by Local's code), no checking that the input is on 128 bits. */
      /* floats with `[exp=1]` are not in the image of fromFixed. They are considered noncanonical. */
      function from96X32(uint density96X32) internal pure returns (Density) { unchecked {
        if (density96X32 <= MANTISSA_MASK) {
          return Density.wrap(density96X32);
        }
        // invariant: `exp >= 2` (so not 0)
        uint exp = BitLib.fls(density96X32);
        return make(density96X32 >> (exp-MANTISSA_BITS),exp);
      }}
    
      /* float -> fixed-point conversion */
      function to96X32(Density density) internal pure returns (uint) { unchecked {
        /* also accepts floats not generated by fixedToFloat, i.e. with exp=1 */
        if (Density.unwrap(density) <= SUBNORMAL_LIMIT) {
          return Density.unwrap(density) & MANTISSA_MASK;
        }
        /* assumes exp is on the right number of bits */
        // invariant: `exp >= 2`
        uint shift = (Density.unwrap(density) >> MANTISSA_BITS) - MANTISSA_BITS;
        return ((Density.unwrap(density) & MANTISSA_MASK) | MANTISSA_INTEGER) << shift;
      }}
    
      function mantissa(Density density) internal pure returns (uint) { unchecked {
        return Density.unwrap(density) & MANTISSA_MASK;
      }}
    
      function exponent(Density density) internal pure returns (uint) { unchecked {
        return Density.unwrap(density) >> MANTISSA_BITS;
      }}
    
      /* Make a float from a mantissa and an exponent. May make a noncanonical float. */
      /* Warning: no checks */
      function make(uint _mantissa, uint _exponent) internal pure returns (Density) { unchecked {
        return Density.wrap((_exponent << MANTISSA_BITS) | (_mantissa & MANTISSA_MASK));
      }}
    
      /* None of the functions below will overflow if m is 96bit wide.
         Density being a 96.32 number is useful because:
         - Most of its range is representable with the 9-bits float format chosen
         - It does not overflow when multiplied with a 96bit number, which is the size chosen to represent token amounts in Mangrove.
         - Densities below `2^-32` need `> 4e9` gasreq to force gives > 0, which is not realistic
      */
      /* Multiply the density with m, rounded towards zero. */
      /* May overflow if `|m|>9` */
      function multiply(Density density, uint m) internal pure returns (uint) { unchecked {
        return (m * density.to96X32())>>32;
      }}
      /* Multiply the density with m, rounded towards +infinity. */
      /* May overflow if `|m|>96` */
      function multiplyUp(Density density, uint m) internal pure returns (uint) { unchecked {
        uint part = m * density.to96X32();
        return (part >> 32) + (part%(2<<32) == 0 ? 0 : 1);
      }}
    
      /* Convenience function: get a fixed-point density from the given parameters. Computes the price of gas in outbound tokens (base units), then multiplies by cover_factor. */
      /* Warning: you must multiply input usd prices by 100 */
      /* not supposed to be gas optimized */
      function paramsTo96X32(
        uint outbound_decimals, 
        uint gasprice_in_Mwei, 
        uint eth_in_centiusd, 
        uint outbound_display_in_centiusd, 
        uint cover_factor
      ) internal pure returns (uint) {
        // Do not use unchecked here
        require(uint8(outbound_decimals) == outbound_decimals,"DensityLib/fixedFromParams1/decimals/wrong");
        uint num = cover_factor * gasprice_in_Mwei * (10**outbound_decimals) * eth_in_centiusd;
        // use * instead of << to trigger overflow check
        return (num * (1 << 32)) / (outbound_display_in_centiusd * 1e12);
      }
    
      /* Version with token in Mwei instead of usd */
      function paramsTo96X32(
        uint outbound_decimals, 
        uint gasprice_in_Mwei, 
        uint outbound_display_in_Mwei, 
        uint cover_factor
      ) internal pure returns (uint) {
        /* **Do not** use unchecked here. */
        require(uint8(outbound_decimals) == outbound_decimals,"DensityLib/fixedFromParams2/decimals/wrong");
        uint num = cover_factor * gasprice_in_Mwei * (10**outbound_decimals);
        /* use `*` instead of `<<` to trigger overflow check */
        return (num * (1 << 32)) / outbound_display_in_Mwei;
      }
    }
  • lib/mangrove-core/lib/core/LocalExtra.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.17;
    
    import {Bin,TickTreeLib,Field} from "@mgv/lib/core/TickTreeLib.sol";
    import {Density, DensityLib} from "@mgv/lib/core/DensityLib.sol";
    import {Local,LocalUnpacked,LocalLib} from "@mgv/src/preprocessed/Local.post.sol";
    
    
    
    // cleanup-mask: 0s at location of fields to hide from maker, 1s elsewhere
    uint constant HIDE_FIELDS_FROM_MAKER_MASK = ~(LocalLib.binPosInLeaf_mask_inv | LocalLib.level3_mask_inv | LocalLib.level2_mask_inv | LocalLib.level1_mask_inv | LocalLib.root_mask_inv | LocalLib.last_mask_inv);
    
    /* Extra functions for local */
    library LocalExtra {
    
      /* Sets the density in fixed-point 96X32 format (it is stored in floating-point, see `DensityLib` for more information). */
      function densityFrom96X32(Local local, uint density96X32) internal pure returns (Local) { unchecked {
        return local.density(DensityLib.from96X32(density96X32));
      }}
    
      /* Returns the gasbase in gas (it is stored in kilogas) */
      function offer_gasbase(Local local) internal pure returns (uint) { unchecked {
        return local.kilo_offer_gasbase() * 1e3;
      }}
    
      /* Sets the gasbase in gas (it is stored in kilogas) */
      function offer_gasbase(Local local,uint val) internal pure returns (Local) { unchecked {
        return local.kilo_offer_gasbase(val/1e3);
      }}
    
      /* Returns the bin that contains the best offer in \`local\`'s offer list */
      function bestBin(Local local) internal pure returns (Bin) { unchecked {
        return TickTreeLib.bestBinFromLocal(local);
      }}
    
      /* Erases field that give information about the current structure of the offer list. */
      function clearFieldsForMaker(Local local) internal pure returns (Local) { unchecked {
        return Local.wrap(
          Local.unwrap(local)
          & HIDE_FIELDS_FROM_MAKER_MASK);
      }}
    }
    
    /* Extra functions for the struct version of local */
    library LocalUnpackedExtra {
      /* Sets the density in fixed-point 96X32 format (it is stored in floating-point, see `DensityLib` for more information). */
      function densityFrom96X32(LocalUnpacked memory local, uint density96X32) internal pure { unchecked {
        local.density = DensityLib.from96X32(density96X32);
      }}
    
      /* Returns the gasbase in gas (it is stored in kilogas) */
      function offer_gasbase(LocalUnpacked memory local) internal pure returns (uint) { unchecked {
        return local.kilo_offer_gasbase * 1e3;
      }}
    
      /* Sets the gasbase in gas (it is stored in kilogas) */
      function offer_gasbase(LocalUnpacked memory local,uint val) internal pure { unchecked {
        local.kilo_offer_gasbase = val/1e3;
      }}
    
      /* Returns the bin that contains the best offer in \`local\`'s offer list */
      function bestBin(LocalUnpacked memory local) internal pure returns (Bin) { unchecked {
        return TickTreeLib.bestBinFromBranch(local.binPosInLeaf,local.level3,local.level2,local.level1,local.root);
      }}
    }
  • lib/mangrove-core/lib/core/OfferDetailExtra.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.17;
    
    import {OfferDetail,OfferDetailUnpacked} from "@mgv/src/preprocessed/OfferDetail.post.sol";
    
    
    /* Extra functions for the offer details */
    library OfferDetailExtra {
      function offer_gasbase(OfferDetail offerDetail) internal pure returns (uint) { unchecked {
        return offerDetail.kilo_offer_gasbase() * 1e3;
      }}
      function offer_gasbase(OfferDetail offerDetail,uint val) internal pure returns (OfferDetail) { unchecked {
        return offerDetail.kilo_offer_gasbase(val/1e3);
      }}
    }
    
    /* Extra functions for the struct version of the offer details */
    library OfferDetailUnpackedExtra {
      function offer_gasbase(OfferDetailUnpacked memory offerDetail) internal pure returns (uint) { unchecked {
        return offerDetail.kilo_offer_gasbase * 1e3;
      }}
      function offer_gasbase(OfferDetailUnpacked memory offerDetail,uint val) internal pure { unchecked {
        offerDetail.kilo_offer_gasbase = val/1e3;
      }}
    }
  • lib/mangrove-core/lib/core/OfferExtra.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.17;
    
    import "@mgv/lib/core/TickTreeLib.sol";
    import "@mgv/lib/core/TickLib.sol";
    import {Offer,OfferUnpacked,OfferLib} from "@mgv/src/preprocessed/Offer.post.sol";
    
    
    /* cleanup-mask: 0s at location of fields to hide from maker, 1s elsewhere */
    uint constant HIDE_FIELDS_FROM_MAKER_MASK = ~(OfferLib.prev_mask_inv | OfferLib.next_mask_inv);
    
    /* Extra functions for the offer */
    library OfferExtra {
      /* Compute wants from tick and gives */
      function wants(Offer offer) internal pure returns (uint) {
        return offer.tick().inboundFromOutboundUp(offer.gives());
      }
    
      /* Sugar to test offer liveness */
      function isLive(Offer offer) internal pure returns (bool resp) {
        uint gives = offer.gives();
        assembly ("memory-safe") {
          resp := iszero(iszero(gives))
        }
      }
    
      /* Get the bin where the offer is stored given an offer list that has `tickSpacing` */
      function bin(Offer offer, uint tickSpacing) internal pure returns (Bin) {
        return offer.tick().nearestBin(tickSpacing);
      }
    
      /* Removes prev/next pointers from an offer before sending it to the maker.  Ensures that the maker has no information about the state of the book when it gets called. */
      function clearFieldsForMaker(Offer offer) internal pure returns (Offer) {
        unchecked {
          return Offer.wrap(
            Offer.unwrap(offer)
            & HIDE_FIELDS_FROM_MAKER_MASK);
        }
      }
    }
    
    /* Extra functions for the struct version of the offer */
    library OfferUnpackedExtra {
      /* Compute wants from tick and gives */
      function wants(OfferUnpacked memory offer) internal pure returns (uint) {
        return offer.tick.inboundFromOutboundUp(offer.gives);
      }
    
      /* Sugar to test offer liveness */
      function isLive(OfferUnpacked memory offer) internal pure returns (bool resp) {
        uint gives = offer.gives;
        assembly ("memory-safe") {
          resp := iszero(iszero(gives))
        }
      }
    
      /* Removes prev/next pointers from an offer before sending it to the maker; Ensures that the maker has no information about the state of the book when it gets called. */
      function bin(OfferUnpacked memory offer, uint tickSpacing) internal pure returns (Bin) {
        return offer.tick.nearestBin(tickSpacing);
      }
    
    }
  • lib/mangrove-core/lib/core/TickLib.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.17;
    
    import {Bin} from "@mgv/lib/core/TickTreeLib.sol";
    import "@mgv/lib/core/BitLib.sol";
    import "@mgv/lib/core/Constants.sol";
    
    /* This file is inspired by Uniswap's approach to ticks, with the following notable changes:
    - directly compute ticks base 1.0001 (not base `sqrt(1.0001)`)
    - directly compute ratios (not `sqrt(ratio)`) (simpler code elsewhere when dealing with actual ratios and logs of ratios)
    - ratios are floating-point numbers, not fixed-point numbers (increases precision when computing amounts)
    */
    
    
    /* # TickLib
    
    The `TickLib` file contains tick math-related code and utilities for manipulating ticks. It also holds functions related to ratios, which are represented as (mantissa,exponent) pairs. */
    
    /* Globally enable `tick.method(...)` */
    type Tick is int;
    using TickLib for Tick global;
    
    library TickLib {
    
      function inRange(Tick tick) internal pure returns (bool) {
        return Tick.unwrap(tick) >= MIN_TICK && Tick.unwrap(tick) <= MAX_TICK;
      }
    
      function eq(Tick tick1, Tick tick2) internal pure returns (bool) {
        unchecked {
          return Tick.unwrap(tick1) == Tick.unwrap(tick2);
        }
      }
    
      /* Returns the nearest, higher bin to the given `tick` at the given `tickSpacing`
        
        We do not force ticks to fit the tickSpacing (aka `tick%tickSpacing==0`). Ratios are rounded up that the maker is always paid at least what they asked for
      */
      function nearestBin(Tick tick, uint tickSpacing) internal pure returns (Bin bin) {
        unchecked {
          // By default division rounds towards 0. Since `smod` is signed we get the sign of `tick` and `tick%tickSpacing` in a single instruction.
          assembly("memory-safe") {
            bin := sdiv(tick,tickSpacing)
            bin := add(bin,sgt(smod(tick,tickSpacing),0))
          }
        }
      }
    
      /* ## Conversion functions */
    
      /* ### (inbound,tick) → outbound 
      `inboundFromOutbound[Up]` converts an outbound amount (i.e. an `offer.gives` or a `takerWants`), to an inbound amount, following the price induced by `tick`. There's a rounding-up and a rounding-down variant.
    
      `outboundAmt` should not exceed 127 bits.
      */
      function inboundFromOutbound(Tick tick, uint outboundAmt) internal pure returns (uint) {
        (uint sig, uint exp) = ratioFromTick(tick);
        return (sig * outboundAmt) >> exp;
      }
    
      function inboundFromOutboundUp(Tick tick, uint outboundAmt) internal pure returns (uint) {
        unchecked {
          (uint sig, uint exp) = ratioFromTick(tick);
          return divExpUp(sig*outboundAmt,exp);
        }
      }
    
      /* ### (outbound,tick) → inbound */
      /* `outboundFromInbound[Up]` converts an inbound amount (i.e. an `offer.wants` or a `takerGives`), to an outbound amount, following the price induced by `tick`. There's a rounding-up and a rounding-down variant.
    
      `inboundAmt` should not exceed 127 bits.
      */
      function outboundFromInbound(Tick tick, uint inboundAmt) internal pure returns (uint) {
        (uint sig, uint exp) = ratioFromTick(Tick.wrap(-Tick.unwrap(tick)));
        return (sig * inboundAmt) >> exp;
      }
    
      function outboundFromInboundUp(Tick tick, uint inboundAmt) internal pure returns (uint) {
        unchecked {
          (uint sig, uint exp) = ratioFromTick(Tick.wrap(-Tick.unwrap(tick)));
          return divExpUp(sig*inboundAmt,exp);
        }
      }
    
      /* ## Ratio representation
    
      Ratios are represented as a (mantissa,exponent) pair which represents the number `mantissa * 2**-exponent`.
    
      The exponent is negated so that, for ratios in the accepted range, the exponent is `>= 0`. This simplifies the code.
    
      Floats are normalized so that the mantissa uses exactly 128 bits. It enables easy comparison between floats and ensures they can be multiplied by amounts without overflow.
    
      The accepted ratio range is between `ratioFromTick(MIN_TICK)` and `ratioFromTick(MAX_TICK)` (inclusive).
      */
      
    
      /* ### (inbound,outbound) → ratio */
    
      /* `ratioFromVolumes` converts a pair of (inbound,outbound) volumes to a floating-point, normalized ratio. It rounds down.
      * `outboundAmt = 0` has a special meaning and the highest possible price will be returned.
      * `inboundAmt = 0` has a special meaning if `outboundAmt != 0` and the lowest possible price will be returned.
      */
      function ratioFromVolumes(uint inboundAmt, uint outboundAmt) internal pure returns (uint mantissa, uint exp) {
        unchecked {
          require(inboundAmt <= MAX_SAFE_VOLUME, "mgv/ratioFromVol/inbound/tooBig");
          require(outboundAmt <= MAX_SAFE_VOLUME, "mgv/ratioFromVol/outbound/tooBig");
          if (outboundAmt == 0) {
            return (MAX_RATIO_MANTISSA,uint(MAX_RATIO_EXP));
          } else if (inboundAmt == 0) {
            return (MIN_RATIO_MANTISSA,uint(MIN_RATIO_EXP));
          }
          uint ratio = (inboundAmt << MANTISSA_BITS) / outboundAmt; 
          uint log2 = BitLib.fls(ratio);
          require(ratio != 0,"mgv/ratioFromVolumes/zeroRatio");
          if (log2 > MANTISSA_BITS_MINUS_ONE) {
            uint diff = log2 - MANTISSA_BITS_MINUS_ONE;
            return (ratio >> diff, MANTISSA_BITS - diff);
          } else {
            uint diff = MANTISSA_BITS_MINUS_ONE - log2;
            return (ratio << diff, MANTISSA_BITS + diff);
          }
        }
      }
    
      /* ### (inbound,outbound) → tick */
      function tickFromVolumes(uint inboundAmt, uint outboundAmt) internal pure returns (Tick tick) {
        (uint man, uint exp) = ratioFromVolumes(inboundAmt, outboundAmt);
        return tickFromNormalizedRatio(man,exp);
      }
    
      /* ### ratio → tick */
      /* Does not require a normalized ratio. */
      function tickFromRatio(uint mantissa, int exp) internal pure returns (Tick) {
        uint normalized_exp;
        (mantissa, normalized_exp) = normalizeRatio(mantissa, exp);
        return tickFromNormalizedRatio(mantissa,normalized_exp);
      }
    
      /* ### low-level ratio → tick */
      /* Given `ratio`, return greatest tick `t` such that `ratioFromTick(t) <= ratio`. 
      * Input ratio must be within the maximum and minimum ratios returned by the available ticks. 
      * Does _not_ expected a normalized float.
      
      The function works as follows:
      * Approximate log2(ratio) to the 13th fractional digit.
      * Following <a href="https://hackmd.io/@mangrovedao/HJvl21zla">https://hackmd.io/@mangrovedao/HJvl21zla</a>, obtain `tickLow` and `tickHigh` such that $\log_{1.0001}(ratio)$ is between them
      * Return the highest one that yields a ratio below the input ratio.
      */
      function tickFromNormalizedRatio(uint mantissa, uint exp) internal pure returns (Tick tick) {
        if (floatLt(mantissa, exp, MIN_RATIO_MANTISSA, uint(MIN_RATIO_EXP))) {
          revert("mgv/tickFromRatio/tooLow");
        }
        if (floatLt(MAX_RATIO_MANTISSA, uint(MAX_RATIO_EXP), mantissa, exp)) {
          revert("mgv/tickFromRatio/tooHigh");
        }
        int log2ratio = int(MANTISSA_BITS_MINUS_ONE) - int(exp) << 64;
        uint mpow = mantissa >> MANTISSA_BITS_MINUS_ONE - 127; // give 129 bits of room left
    
        /* How the fractional digits of the log are computed: 
        * for a given `n` compute $n^2$. 
        * If $\lfloor\log_2(n^2)\rfloor = 2\lfloor\log_2(n)\rfloor$ then the fractional part of $\log_2(n^2)$ was $< 0.5$ (first digit is 0). 
        * If $\lfloor\log_2(n^2)\rfloor = 1 + 2\lfloor\log_2(n)\rfloor$ then the fractional part of $\log_2(n^2)$ was $\geq 0.5$ (first digit is 1).
        * Apply starting with `n=mpow` repeatedly by keeping `n` on 127 bits through right-shifts (has no impact on high fractional bits).
        */
    
        assembly ("memory-safe") {
          // 13 bits of precision
          mpow := shr(127, mul(mpow, mpow))
          let highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(63, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(62, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(61, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(60, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(59, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(58, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(57, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(56, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(55, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(54, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(53, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(52, highbit))
          mpow := shr(highbit, mpow)
    
          mpow := shr(127, mul(mpow, mpow))
          highbit := shr(128, mpow)
          log2ratio := or(log2ratio, shl(51, highbit))
        }
    
        // Convert log base 2 to log base 1.0001 (multiply by `log2(1.0001)^-1 << 64`), since log2ratio is x64 this yields a x128 number.
        int log_bp_ratio = log2ratio * 127869479499801913173571;
    
        // tickLow is approx - maximum error
        int tickLow = int((log_bp_ratio - 1701496478404567508395759362389778998) >> 128);
        // tickHigh is approx + minimum error
        int tickHigh = int((log_bp_ratio + 289637967442836606107396900709005211253) >> 128);
    
        (uint mantissaHigh, uint expHigh) = ratioFromTick(Tick.wrap(tickHigh));
    
        bool ratioHighGt = floatLt(mantissa, exp, mantissaHigh, expHigh);
        if (tickLow == tickHigh || ratioHighGt) {
          tick = Tick.wrap(tickLow);
        } else { 
          tick = Tick.wrap(tickHigh);
        }
      }
    
      /* ### tick → ratio conversion function */
      /* Returns a normalized (man,exp) ratio floating-point number. The mantissa is on 128 bits to avoid overflow when mulitplying with token amounts. The exponent has no bias. for easy comparison. */
      function ratioFromTick(Tick tick) internal pure returns (uint man, uint exp) {
        unchecked {
          (man, exp) = nonNormalizedRatioFromTick(tick);
          int shiftedTick = Tick.unwrap(tick) << LOG_BP_SHIFT;
          int log2ratio;
          // floor log2 of ratio towards negative infinity
          assembly ("memory-safe") {
            log2ratio := sdiv(shiftedTick,LOG_BP_2X235)
            log2ratio := sub(log2ratio,slt(smod(shiftedTick,LOG_BP_2X235),0))
          }
          int diff = log2ratio+int(exp)-int(MANTISSA_BITS_MINUS_ONE);
          if (diff > 0) {
            // For |tick| <= 887272, this drops at most 5 bits of precision
            man = man >> uint(diff);
          } else {
            man = man << uint(-diff);
          }
          // For |tick| << 887272, log2ratio <= 127
          exp = uint(int(MANTISSA_BITS_MINUS_ONE)-log2ratio);
        }
      }
    
      /* ### low-level tick → ratio conversion */
      /* Compute 1.0001^tick and returns it as a (mantissa,exponent) pair. Works by checking each set bit of `|tick|` multiplying by `1.0001^(-2**i)<<128` if the ith bit of tick is set. Since we inspect the absolute value of `tick`, `-1048576` is not a valid tick. If the tick is positive this computes `1.0001^-tick`, and we take the inverse at the end. For maximum precision some powers of 1.0001 are shifted until they occupy 128 bits. The `extra_shift` is recorded and added to the exponent.
    
      Since the resulting mantissa is left-shifted by 128 bits, if tick was positive, we divide `2**256` by the mantissa to get the 128-bit left-shifted inverse of the mantissa.
    
      The error (relative to 1.0001^tick) may be negative or positive.
      */
      function nonNormalizedRatioFromTick(Tick tick) internal pure returns (uint man, uint exp) {
        uint absTick = Tick.unwrap(tick) < 0 ? uint(-Tick.unwrap(tick)) : uint(Tick.unwrap(tick));
        require(absTick <= uint(MAX_TICK), "mgv/absTick/outOfBounds");
    
        int extra_shift;
        if (absTick & 0x1 != 0) {
          man = 0xfff97272373d413259a46990580e2139;
        } else {
          man = 0x100000000000000000000000000000000;
        }
        if (absTick & 0x2 != 0) {
          man = (man * 0xfff2e50f5f656932ef12357cf3c7fdcb) >> 128;
        }
        if (absTick & 0x4 != 0) {
          man = (man * 0xffe5caca7e10e4e61c3624eaa0941ccf) >> 128;
        }
        if (absTick & 0x8 != 0) {
          man = (man * 0xffcb9843d60f6159c9db58835c926643) >> 128;
        }
        if (absTick & 0x10 != 0) {
          man = (man * 0xff973b41fa98c081472e6896dfb254bf) >> 128;
        }
        if (absTick & 0x20 != 0) {
          man = (man * 0xff2ea16466c96a3843ec78b326b52860) >> 128;
        }
        if (absTick & 0x40 != 0) {
          man = (man * 0xfe5dee046a99a2a811c461f1969c3052) >> 128;
        }
        if (absTick & 0x80 != 0) {
          man = (man * 0xfcbe86c7900a88aedcffc83b479aa3a3) >> 128;
        }
        if (absTick & 0x100 != 0) {
          man = (man * 0xf987a7253ac413176f2b074cf7815e53) >> 128;
        }
        if (absTick & 0x200 != 0) {
          man = (man * 0xf3392b0822b70005940c7a398e4b70f2) >> 128;
        }
        if (absTick & 0x400 != 0) {
          man = (man * 0xe7159475a2c29b7443b29c7fa6e889d8) >> 128;
        }
        if (absTick & 0x800 != 0) {
          man = (man * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
        }
        if (absTick & 0x1000 != 0) {
          man = (man * 0xa9f746462d870fdf8a65dc1f90e061e4) >> 128;
        }
        if (absTick & 0x2000 != 0) {
          man = (man * 0xe1b0d342ada5437121767bec575e65ed) >> 128;
          extra_shift += 1;
        }
        if (absTick & 0x4000 != 0) {
          man = (man * 0xc6f84d7e5f423f66048c541550bf3e96) >> 128;
          extra_shift += 2;
        }
        if (absTick & 0x8000 != 0) {
          man = (man * 0x9aa508b5b7a84e1c677de54f3e99bc8f) >> 128;
          extra_shift += 4;
        }
        if (absTick & 0x10000 != 0) {
          man = (man * 0xbad5f1bdb70232cd33865244bdcc089c) >> 128;
          extra_shift += 9;
        }
        if (absTick & 0x20000 != 0) {
          man = (man * 0x885b9613d7e87aa498106fb7fa5edd37) >> 128;
          extra_shift += 18;
        }
        if (absTick & 0x40000 != 0) {
          man = (man * 0x9142e0723efb884889d1f447715afacd) >> 128;
          extra_shift += 37;
        }
        if (absTick & 0x80000 != 0) {
          man = (man * 0xa4d9a773d61316918f140bd96e8e6814) >> 128;
          extra_shift += 75;
        }
        if (Tick.unwrap(tick) > 0) {
          /* We use [Remco Bloemen's trick](https://xn--2-umb.com/17/512-bit-division/#divide-2-256-by-a-given-number) to divide `2**256` by `man`: */
          assembly("memory-safe") {
            man := add(div(sub(0, man), man), 1)
          }
          extra_shift = -extra_shift;
        }
        exp = uint(128 + extra_shift);
    
      }
    
      /* Shift mantissa so it occupies exactly `MANTISSA_BITS` and adjust `exp` in consequence.
      
      A float is normalized when its mantissa occupies exactly 128 bits. All in-range normalized floats have `exp >= 0`, so we can use a `uint` for exponents everywhere we expect a normalized float.
    
      When a non-normalized float is expected/used, `exp` can be negative since there is no constraint on the size of the mantissa.
      
       */
      function normalizeRatio(uint mantissa, int exp) internal pure returns (uint, uint) {
        require(mantissa != 0,"mgv/normalizeRatio/mantissaIs0");
        uint log2ratio = BitLib.fls(mantissa);
        int shift = int(MANTISSA_BITS_MINUS_ONE) - int(log2ratio);
        if (shift < 0) {
          mantissa = mantissa >> uint(-shift);
        } else {
          mantissa = mantissa << uint(shift);
        }
        exp = exp + shift;
        if (exp < 0) {
          revert("mgv/normalizeRatio/lowExp");
        }
        return (mantissa,uint(exp));
      }
    
      /* Return `a/(2**e)` rounded up */
      function divExpUp(uint a, uint e) internal pure returns (uint) {
        unchecked {
          uint rem;
          /* 
          Let mask be `(1<<e)-1`, `rem` is 1 if `a & mask > 0`, and 0 otherwise.
          Explanation:
          * if a is 0 then `rem` must be 0. `0 & mask` is 0.
          * else if `e > 255` then `0 < a < 2^e`, so `rem` must be 1. `(1<<e)-1` is `type(uint).max`, so `a & mask is a > 0`.
          * else `a & mask` is `a % 2**e`
          */
          assembly("memory-safe") {
            rem := gt(and(a,sub(shl(e,1),1)),0)
          }
          return (a>>e) + rem;
        }
      }
    
      /* Floats are normalized to 128 bits to ensure no overflow when multiplying with amounts, and for easier comparisons. Normalized in-range floats have `exp>=0`. */
      function floatLt(uint mantissa_a, uint exp_a, uint mantissa_b, uint exp_b) internal pure returns (bool) {
        /* Exponents are negated (so that exponents of ratios within the accepted range as >= 0, which simplifies the code), which explains the direction of the `exp_a > exp_b` comparison. */ 
        return (exp_a > exp_b || (exp_a == exp_b && mantissa_a < mantissa_b));
      }
    
    }
  • lib/mangrove-core/lib/core/TickTreeLib.sol
    // SPDX-License-Identifier: BUSL-1.1
    pragma solidity ^0.8.17;
    
    import "@mgv/lib/core/Constants.sol";
    import {Tick} from "@mgv/lib/core/TickLib.sol";
    import {BitLib} from "@mgv/lib/core/BitLib.sol";
    import {console2 as csf} from "@mgv/forge-std/console2.sol";
    import {Local} from "@mgv/src/preprocessed/Local.post.sol";
    
    
    /* # Libraries for tick tree manipulation 
    
    Offers in Mangrove are structured in a tree so that offer insertion, removal, and update can happen in constant time.
    
    The tree has the following structure: nodes at height 0, 1, 2 and 3 are bit fields (type `Field`) and nodes at height 4 (leaves) are arrays of pairs of offers (type `Leaf`).
    
    - The root node is a 2-bit `Field` and has 2 child nodes.
    - The nodes below are called `level1` nodes and are 64-bit `Field`s, with 64 child nodes each.
    - The nodes below are called `level2` nodes and are 64-bit `Field`s with 64 child nodes each.
    - The nodes below are called `level3` nodes and are 64-bit `Field`s with 64 child nodes each.
    - The nodes below are called `leaf` nodes and are arrays of pairs of offers. Each pair of offers represents the first and last offer of a bin.
    - Bins are linked lists of offers.
    
    For each field, the i-th bit (starting from least significant) is set if there is at least one bin holding offers below the i-th child of the field. */
    
    
    /* Globally enable `leaf.method(...)` */
    type Leaf is uint;
    using LeafLib for Leaf global;
    
    /* Each `Leaf` holds information about 4 bins as follows: `[firstId,lastId] [firstId,lastId] [firstId,lastId] [firstId,lastId]`. For each bin `firstId` is used by `marketOrder` to start consuming offers in the bin (each offer contains a pointer to the next offer in the bin, until `lastId` is reacher). `lastId` is used when inserting offers in the bin: the newly inserted offer replaces the last offer.
    
    Each `leaf` has an `index`: it is the number of leaves before it.
    */
    library LeafLib {
      Leaf constant EMPTY = Leaf.wrap(uint(0));
    
      /* Checks if a leaf is dirty or not (see below for more on dirty leaves). */
      function dirty(Leaf leaf) internal pure returns (DirtyLeaf) {
        unchecked {
          assembly ("memory-safe") {
            leaf := or(iszero(leaf),leaf)
          }
          return DirtyLeaf.wrap(Leaf.unwrap(leaf));
        }
      }
    
      function eq(Leaf leaf1, Leaf leaf2) internal pure returns (bool) {
        unchecked {
          return Leaf.unwrap(leaf1) == Leaf.unwrap(leaf2);
        }
      }
    
      function isEmpty(Leaf leaf) internal pure returns (bool) {
        unchecked {
          return Leaf.unwrap(leaf) == Leaf.unwrap(EMPTY);
        }
      }
    
      /* `bool -> int` cast */
      function uint_of_bool(bool b) internal pure returns (uint u) {
        unchecked {
          assembly ("memory-safe") {
            u := b
          }
        }
      }
    
      /* Set either tick's first (at pos*size) or last (at pos*size + 1) */
      function setPosFirstOrLast(Leaf leaf, uint pos, uint id, bool last) internal pure returns (Leaf) {
        unchecked {
          uint before = OFFER_BITS * ((pos * 2) + uint_of_bool(last));
    
          uint cleanupMask = ~(OFFER_MASK << (256 - OFFER_BITS - before));
    
          uint shiftedId = id << (256 - OFFER_BITS - before);
          uint newLeaf = Leaf.unwrap(leaf) & cleanupMask | shiftedId;
          return Leaf.wrap(newLeaf);
        }
      }
    
      /* Assume `leaf` is the leaf of `bin`. Set the first offer of `bin` in leaf to `id`. */
      function setBinFirst(Leaf leaf, Bin bin, uint id) internal pure returns (Leaf) {
        unchecked {
          uint posInLeaf = bin.posInLeaf();
          return setPosFirstOrLast(leaf, posInLeaf, id, false);
        }
      }
    
      /* Assume `leaf` is the leaf of `bin`. Set the last offer of `bin` in leaf to `id`. */
      function setBinLast(Leaf leaf, Bin bin, uint id) internal pure returns (Leaf) {
        unchecked {
          uint posInLeaf = bin.posInLeaf();
          return setPosFirstOrLast(leaf, posInLeaf, id, true);
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._ 
      /* Assumes `leaf` is the leaf of `bin`. Erase contents of bins in `leaf` to (not including) `bin`. */
      function eraseBelow(Leaf leaf, Bin bin) internal pure returns (Leaf) {
        unchecked {
          uint mask = ONES >> ((bin.posInLeaf() + 1) * OFFER_BITS * 2);
          return Leaf.wrap(Leaf.unwrap(leaf) & mask);
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._ 
      /* Assumes `leaf` is the leaf of `bin`. Erase contents of bins in `leaf` from (not including) `bin`. */
      function eraseAbove(Leaf leaf, Bin bin) internal pure returns (Leaf) {
        unchecked {
          uint mask = ~(ONES >> (bin.posInLeaf() * OFFER_BITS * 2));
          return Leaf.wrap(Leaf.unwrap(leaf) & mask);
        }
      }
    
    
      // _This function is not used by Mangrove but is part of the library._
      /* Return the id of the first offer in `bin`, assuming `bin`'s leaf is `leaf`. */
      function firstOfBin(Leaf leaf, Bin bin) internal pure returns (uint) {
        unchecked {
          return firstOfPos(leaf, bin.posInLeaf());
        }
      }
    
      /* Return the id of the last offer in `bin`, assuming `bin`'s leaf is `leaf`. */
      function lastOfBin(Leaf leaf, Bin bin) internal pure returns (uint) {
        unchecked {
          return lastOfPos(leaf, bin.posInLeaf());
        }
      }
    
      /* Return first offer of pair in position `pos` */
      function firstOfPos(Leaf leaf, uint pos) internal pure returns (uint) {
        unchecked {
          uint raw = Leaf.unwrap(leaf);
          return uint(raw << (pos * OFFER_BITS * 2) >> (256 - OFFER_BITS));
        }
      }
    
      /* Return second offer of pair in position `pos` */
      function lastOfPos(Leaf leaf, uint pos) internal pure returns (uint) {
        unchecked {
          uint raw = Leaf.unwrap(leaf);
          return uint(raw << (OFFER_BITS * ((pos * 2) + 1)) >> (256 - OFFER_BITS));
        }
      }
    
      /* Return the position of the first pair of `leaf` (0, 1, 2 or 3) that has a nonzero offer.
    
      Explanation:
      Note that unlike in fields, have their low bin on the most significant bits.
      `pos` is initially 1 if `leaf` has some nonzero bit in its MSB half, 0 otherwise. Then `pos` is `A | B`, where `A` is `iszero(pos)<<1`, so `A` is 0 if leaf has some nonzero bit in its MSB half, 2 otherwise. And `B` is 0 if `leaf >> (pos << 7)` has some nonzero bit in its most significant 192 bits, 1 otherwise.
      */
      function bestNonEmptyBinPos(Leaf leaf) internal pure returns (uint pos) {
        assembly("memory-safe") {
          pos := gt(leaf,0xffffffffffffffffffffffffffffffff)
          pos := or(shl(1,iszero(pos)),iszero(gt(shr(shl(7,pos),leaf),0xffffffffffffffff)))
        }
      }
    
      /* Return the offer id of the first offer of the first non-empty pair in `leaf`. */
      function bestOfferId(Leaf leaf) internal pure returns (uint offerId) {
        unchecked {
          return firstOfPos(leaf,bestNonEmptyBinPos(leaf));
        }
      }
    }
    
    
    /* Bins are numbered from MIN_BIN to MAX_BIN (inclusive). Each bin contains the offers at a given price. For a given `tickSpacing`, bins represent the following prices (centered on the central bin): 
    ```
    ...
    1.0001^-(tickSpacing*2)
    1.0001^-(tickSpacing*1)
    1.0001
    1.0001^(tickSpacing*1)
    1.0001^(tickSpacing*2)
    ...
    ``` 
    
    There are 4 bins per leaf, `4 * 64` bins per level3, etc. The leaf of a bin is the leaf that holds its first/last offer id. The level3 of a bin is the level3 field above its leaf; the level2 of a bin is the level2 field above its level3, etc. */
    
    /* Globally enable `bin.method(...)` */
    type Bin is int;
    using TickTreeLib for Bin global;
    
    library TickTreeLib {
    
      function eq(Bin bin1, Bin bin2) internal pure returns (bool) {
        unchecked {
          return Bin.unwrap(bin1) == Bin.unwrap(bin2);
        }
      }
    
      function inRange(Bin bin) internal pure returns (bool) {
        unchecked {
          return Bin.unwrap(bin) >= MIN_BIN && Bin.unwrap(bin) <= MAX_BIN;
        }
      }
    
      // _This function is not used by Mangrove but is part of the library for convenience._
      
      /* Not optimized for gas. Returns the bin induced by the branch formed by the arguments. Returned value will make no sense if any of the `Field` arguments are empty. */
      function bestBinFromBranch(uint binPosInLeaf,Field level3, Field level2, Field level1, Field root) internal pure returns (Bin) {
        unchecked {
          Local local;
          local = local.binPosInLeaf(binPosInLeaf).level3(level3).level2(level2).level1(level1).root(root);
          return bestBinFromLocal(local);
        }
      }
    
      /* Returns tick held by the `bin`, given a `tickSpacing`. */
      function tick(Bin bin, uint tickSpacing) internal pure returns (Tick) {
        return Tick.wrap(Bin.unwrap(bin) * int(tickSpacing));
      }
    
      /* Returns the bin induced by the branch held in `local`. Returned value will make no sense if any of the fields of `local` are empty. */
      function bestBinFromLocal(Local local) internal pure returns (Bin) {
        unchecked {
          uint ubin = local.binPosInLeaf() |
            ((BitLib.ctz64(Field.unwrap(local.level3())) |
              (BitLib.ctz64(Field.unwrap(local.level2())) |
                (BitLib.ctz64(Field.unwrap(local.level1())) |
                  uint(
                    (int(BitLib.ctz64(Field.unwrap(local.root())))-ROOT_SIZE/2) << LEVEL_SIZE_BITS)) 
                  << LEVEL_SIZE_BITS)
                << LEVEL_SIZE_BITS)
              << LEAF_SIZE_BITS);
          return Bin.wrap(int(ubin));
        }
      }
    
      /* Returns the index of the leaf that holds `bin` */
      function leafIndex(Bin bin) internal pure returns (int) {
        unchecked {
          return Bin.unwrap(bin) >> LEAF_SIZE_BITS;
        }
      }
    
      /* Returns the position of `bin` in its leaf. */
      function posInLeaf(Bin bin) internal pure returns (uint) {
        unchecked {
          return uint(Bin.unwrap(bin)) & LEAF_SIZE_MASK;
        }
      }
    
      /* Returns the index of `bin`'s level3 */
      function level3Index(Bin bin) internal pure returns (int) {
        unchecked {
          return Bin.unwrap(bin) >> (LEAF_SIZE_BITS + LEVEL_SIZE_BITS);
        }
      }
    
      /* Returns the position of `bin`'s leaf in `bin`'s level3 */
      function posInLevel3(Bin bin) internal pure returns (uint) {
        unchecked {
          return uint(bin.leafIndex()) & LEVEL_SIZE_MASK;
        }
      }
    
      /* Returns the index of `bin`'s level2 */
      function level2Index(Bin bin) internal pure returns (int) {
        unchecked {
          return Bin.unwrap(bin) >> (LEAF_SIZE_BITS + 2* LEVEL_SIZE_BITS);
        }
      }
    
      /* Returns the position of `bin`'s level3 in `bin`'s level2 */
      function posInLevel2(Bin bin) internal pure returns (uint) {
        unchecked {
          return uint(bin.level3Index()) & LEVEL_SIZE_MASK;
        }
      }
    
      /* Returns the index of `bin`'s level1 */
      function level1Index(Bin bin) internal pure returns (int) {
        unchecked {
          return Bin.unwrap(bin) >> (LEAF_SIZE_BITS + 3 * LEVEL_SIZE_BITS);
        }
      }
    
      /* Returns the position of `bin`'s level2 in `bin`'s level1 */
      function posInLevel1(Bin bin) internal pure returns (uint) {
        unchecked {
          return uint(bin.level2Index()) & LEVEL_SIZE_MASK;
        }
      }
    
      /* Returns the position of `bin`'s level1 in root */
      function posInRoot(Bin bin) internal pure returns (uint) {
        unchecked {
          return uint(bin.level1Index() + ROOT_SIZE / 2);
        }
      }
    
      /* `<`, typed for bin */
      function strictlyBetter(Bin bin1, Bin bin2) internal pure returns (bool) {
        unchecked {
          return Bin.unwrap(bin1) < Bin.unwrap(bin2);
        }
      }
    
      /* `<=`, typed for bin */
      function better(Bin bin1, Bin bin2) internal pure returns (bool) {
        unchecked {
          return Bin.unwrap(bin1) <= Bin.unwrap(bin2);
        }
      }  
    
    }
    
    /* Globally enable `field.method(...)` */
    type Field is uint;
    using FieldLib for Field global;
    
    /* Fields are bit fields. Each bit position of a field corresponds to a child of the node in the tick tree. The i-th bit of a field is set iff its child is the parent of at least one non-emtpy field.
    
    Using bit fields market orders can locate the next bin containing an offer in constant time: once a leaf has been emptied, one must at most walk up along the branch of the current bin, up to the first 1 in a field, then go down to the of the tree, then go down the corresponding child to the nonempty bin found.
    */
    
    /* In fields, positions are counted from the least significant bits */
    library FieldLib {
      Field constant EMPTY = Field.wrap(uint(0));
    
      /* Checks if a field is dirty or not (see below for more on dirty fields). */
      function dirty(Field field) internal pure returns (DirtyField) {
        unchecked {
          assembly ("memory-safe") {
            field := or(TOPBIT,field)
          }
          return DirtyField.wrap(Field.unwrap(field));
        }
      }
    
      function eq(Field field1, Field field2) internal pure returns (bool) {
        unchecked {
          return Field.unwrap(field1) == Field.unwrap(field2);
        }
      }
    
      function isEmpty(Field field) internal pure returns (bool) {
        unchecked {
          return Field.unwrap(field) == Field.unwrap(EMPTY);
        }
      }
    
      /* Flip the bit at the position of `bin`'s leaf */
      function flipBitAtLevel3(Field level3, Bin bin) internal pure returns (Field) {
        unchecked {
          uint pos = bin.posInLevel3();
          level3 = Field.wrap(Field.unwrap(level3) ^ (1 << pos));
          return level3;
        }
      }
    
      /* Flip the bit at the position of `bin`'s level3 */
      function flipBitAtLevel2(Field level2, Bin bin) internal pure returns (Field) {
        unchecked {
          uint pos = bin.posInLevel2();
          level2 = Field.wrap(Field.unwrap(level2) ^ (1 << pos));
          return level2;
        }
      }
    
      /* Flip the bit at the position of `bin`'s level2 */
      function flipBitAtLevel1(Field level1, Bin bin) internal pure returns (Field) {
        unchecked {
          uint pos = bin.posInLevel1();
          level1 = Field.wrap(Field.unwrap(level1) ^ (1 << pos));
          return level1;
        }
      }
    
      /* Flip the bit at the position of `bin`'s level1 */
      function flipBitAtRoot(Field root, Bin bin) internal pure returns (Field) {
        unchecked {
          uint pos = bin.posInRoot();
          root = Field.wrap(Field.unwrap(root) ^ (1 << pos));
          return root;
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._ 
      /* Assumes `field` is the level3 of `bin`. Erase contents of field up to (not including) bin. */
      function eraseBelowInLevel3(Field field, Bin bin) internal pure returns (Field) {
        unchecked {
          uint mask = ONES << (bin.posInLevel3() + 1);
          return Field.wrap(Field.unwrap(field) & mask);
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._ 
      /* Assumes `field` is the level3 of `bin`. Erase contents of field from (not including) bin. */
      function eraseAboveInLevel3(Field field, Bin bin) internal pure returns (Field) {
        unchecked {
          uint mask = ~(ONES << bin.posInLevel3());
          return Field.wrap(Field.unwrap(field) & mask);
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._ 
      /* Assumes `field` is the level2 of `bin`. Erase contents of field up to (not including) bin. */
      function eraseBelowInLevel2(Field field, Bin bin) internal pure returns (Field) {
        unchecked {
          uint mask = ONES << (bin.posInLevel2() + 1);
          return Field.wrap(Field.unwrap(field) & mask);
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._ 
      /* Assumes `field` is the level2 of `bin`. Erase contents of field from (not including) bin. */
      function eraseAboveInLevel2(Field field, Bin bin) internal pure returns (Field) {
        unchecked {
          uint mask = ~(ONES << bin.posInLevel2());
          return Field.wrap(Field.unwrap(field) & mask);
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._ 
      /* Assumes `field` is the level1 of `bin`. Erase contents of field up to (not including) bin. */
      function eraseBelowInLevel1(Field field, Bin bin) internal pure returns (Field) {
        unchecked {
          uint mask = ONES << (bin.posInLevel1() + 1);
          return Field.wrap(Field.unwrap(field) & mask);
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._ 
      /* Assumes `field` is the level1 of `bin`. Erase contents of field from (not including) bin. */
      function eraseAboveInLevel1(Field field, Bin bin) internal pure returns (Field) {
        unchecked {
          uint mask = ~(ONES << bin.posInLevel1());
          return Field.wrap(Field.unwrap(field) & mask);
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._ 
      /* Assumes `field` is the root of `bin`. Erase contents of field up to (not including) bin. */
      function eraseBelowInRoot(Field field, Bin bin) internal pure returns (Field) {
        unchecked {
          uint mask = ONES << (bin.posInRoot() + 1);
          return Field.wrap(Field.unwrap(field) & mask);
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._ 
      /* Assumes `field` is the root of `bin`. Erase contents of field from (not including) bin. */
      function eraseAboveInRoot(Field field, Bin bin) internal pure returns (Field) {
        unchecked {
          uint mask = ~(ONES << bin.posInRoot());
          return Field.wrap(Field.unwrap(field) & mask);
        }
      }
    
      /* Returns first nonzero position of `field`. Will return 64 if field is empty */
      function firstOnePosition(Field field) internal pure returns (uint) {
        unchecked {
          return BitLib.ctz64(Field.unwrap(field));
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._
      /* Returns last nonzero position of `field`. Will return 256 if field is empty */
      function lastOnePosition(Field field) internal pure returns (uint) {
        unchecked {
          return BitLib.fls(Field.unwrap(field));
        }
      }
    
      /* Return index of the first nonempty level1 below `root` (`root` should not be empty) */
      function firstLevel1Index(Field root) internal pure returns (int) {
        unchecked {
          return int(root.firstOnePosition()) - ROOT_SIZE / 2;
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._
      /* Return index of the last nonempty level1 below `root` (root should not be empty) */
      function lastLevel1Index(Field root) internal pure returns (int) {
        unchecked {
          return int(root.lastOnePosition()) - ROOT_SIZE / 2;
        }
      }
    
      /* Return index of the first nonempty level2 below `level1` assuming its index is `level1Index` (`level1` should not be empty). */
      function firstLevel2Index(Field level1, int level1Index) internal pure returns (int) {
        unchecked {
          return level1Index * LEVEL_SIZE + int(level1.firstOnePosition());
        }
      }
      // _This function is not used by Mangrove but is useful for MgvReader._
      /* Return index of the last nonempty level2 below `level1` assuming its index is `level1Index` (`level1` should not be empty). */
      function lastLevel2Index(Field level1, int level1Index) internal pure returns (int) {
        unchecked {
          return level1Index * LEVEL_SIZE + int(level1.lastOnePosition());
        }
      }
    
      /* Return index of the first nonempty level3 below `level2` assuming its index is `level2Index` (`level2` should not be empty). */
      function firstLevel3Index(Field level2, int level2Index) internal pure returns (int) {
        unchecked {
          return level2Index * LEVEL_SIZE + int(level2.firstOnePosition());
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._
      /* Return index of the last nonempty level3 below `level2` assuming its index is `level2Index` (`level2` should not be empty). */
      function lastLevel3Index(Field level2, int level2Index) internal pure returns (int) {
        unchecked {
          return level2Index * LEVEL_SIZE + int(level2.lastOnePosition());
        }
      }
    
      /* Return index of the first nonempty leaf below `level3` assuming its index is `level3Index` (`level3` should not be empty). */
      function firstLeafIndex(Field level3, int level3Index) internal pure returns (int) {
        unchecked {
          return level3Index * LEVEL_SIZE + int(level3.firstOnePosition());
        }
      }
    
      // _This function is not used by Mangrove but is useful for MgvReader._
      /* Return index of the last nonempty leaf below `level3` assuming its index is `level3Index` (`level3` should not be empty). */
      function lastLeafIndex(Field level3, int level3Index) internal pure returns (int) {
        unchecked {
          return level3Index * LEVEL_SIZE + int(level3.lastOnePosition());
        }
      }
    
     }
    
    /* ## Clean/Dirty Fields and Leaves
    
    To save gas, leaves and fields at never zeroed out but written with a dirty bit. This is especially helpful when the price oscillates quickly between two nodes.
    
    Leaves don't have 'available bits' so an empty leaf is encoded as 1. This is not a valid leaf because for every offer pair in a leaf, either both are 0 (the bin is empty) or both are nonzero (they are the same if the bin has a single offer).
    */
    
    /* Globally enable `dirtyLeaf.method(...)` */
    type DirtyLeaf is uint;
    using DirtyLeafLib for DirtyLeaf global;
    
    library DirtyLeafLib {
      
      /* Return 0 if leaf is 1, leaf otherwise */
      function clean(DirtyLeaf leaf) internal pure returns (Leaf) {
        unchecked {
          assembly ("memory-safe") {
            leaf := xor(eq(leaf,ONE),leaf)
          }
          return Leaf.wrap(DirtyLeaf.unwrap(leaf));
        }
      }
      function isDirty(DirtyLeaf leaf) internal pure returns (bool) {
        unchecked {
          return DirtyLeaf.unwrap(leaf) == ONE;
        }
      }
      function eq(DirtyLeaf leaf1, DirtyLeaf leaf2) internal pure returns (bool) {
        unchecked {
          return DirtyLeaf.unwrap(leaf1) == DirtyLeaf.unwrap(leaf2);
        }
      }
    }
    
    /* We use `TOPBIT` as the optimized in-storage value since 1 is a valid Field value */
    
    /* For fields, it's simpler, since they do not use 64 bits we store the word with top bit at 1 and everything else at 0 to mark emptiness. */
    
    /* Globally enable `dirtyField.method(...)` */
    type DirtyField is uint;
    using DirtyFieldLib for DirtyField global;
    
    library DirtyFieldLib {
      DirtyField constant DIRTY_EMPTY = DirtyField.wrap(TOPBIT);
      DirtyField constant CLEAN_EMPTY = DirtyField.wrap(0);
    
      /* Return clean field with topbit set to 0 */
      function clean(DirtyField field) internal pure returns (Field) {
        unchecked {
          assembly ("memory-safe") {
            field := and(NOT_TOPBIT,field)
          }
          return Field.wrap(DirtyField.unwrap(field));
        }
      }
      function isDirty(DirtyField field) internal pure returns (bool) {
        unchecked {
          return DirtyField.unwrap(field) & TOPBIT == TOPBIT;
        }
      }
    
      function eq(DirtyField leaf1, DirtyField leaf2) internal pure returns (bool) {
        unchecked {
          return DirtyField.unwrap(leaf1) == DirtyField.unwrap(leaf2);
        }
      }
    }
    
    
  • lib/mangrove-core/src/core/MgvLib.sol
    // SPDX-License-Identifier: MIT
    
    /* `MgvLib` contains data structures returned by external calls to Mangrove and the interfaces it uses for its own external calls. */
    
    pragma solidity ^0.8.10;
    
    import "@mgv/src/preprocessed/Structs.post.sol";
    import {IERC20} from "@mgv/lib/IERC20.sol";
    import {Density, DensityLib} from "@mgv/lib/core/DensityLib.sol";
    import "@mgv/lib/core/TickTreeLib.sol";
    import "@mgv/lib/core/TickLib.sol";
    
    /* `OLKey` (for "OfferListKey") contains the information that characterizes an offer list:
      * `outbound_tkn`, token that goes from the maker to the taker (to remember the direction, imagine the token as going out of the Mangrove offer, towards the taker)
      * `inbound_tkn`, token that goes from the taker to the maker (to remember the direction, imagine the token as going into Mangrove from the taker)
      * `tickSpacing`, how many ticks should be jumped between available price points. More volatile outbound/inbound pairs should have a larger `tickSpacing`. */
    struct OLKey {
      address outbound_tkn;
      address inbound_tkn;
      uint tickSpacing;
    }
    
    /* Globally enable `olKey.method(...)` */
    using OLLib for OLKey global;
    
    library OLLib {
      /* The id of an `OLKey` should be `keccak256(abi.encode(olKey))`
      To save gas, `id()` directly hashes the memory (which matches the ABI encoding; there is a fuzz test on that). If the memory layout changes, this function must be updated. */
      function hash(OLKey memory olKey) internal pure returns (bytes32 _id) {
        assembly ("memory-safe") {
          _id := keccak256(olKey, 96)
        }
      }
    
      /* Creates a flipped copy of the `olKey` with same `tickSpacing`. */
      function flipped(OLKey memory olKey) internal pure returns (OLKey memory) {
        return OLKey(olKey.inbound_tkn, olKey.outbound_tkn, olKey.tickSpacing);
      }
    
      /* Convert `tick` to bin according to `olKey.tickSpacing` */
      function nearestBin(OLKey memory olKey, Tick _tick) internal pure returns (Bin) {
        return _tick.nearestBin(olKey.tickSpacing);
      }
    
      /* Convert `bin` to `tick` according to `olKey.tickSpacing` */
      function tick(OLKey memory olKey, Bin bin) internal pure returns (Tick) {
        return bin.tick(olKey.tickSpacing);
      }
    }
    
    /* # Structs
    The structs defined in `structs.js` have their counterpart as solidity structs that are easy to manipulate for outside contracts / callers of view functions. */
    
    library MgvLib {
      /*
       Some miscellaneous data types useful to `Mangrove` and external contracts */
      //+clear+
    
      /* `SingleOrder` holds data about an order-offer match in a struct. Used by `marketOrder` (and some of its nested functions) to avoid stack too deep errors. It is used in market order and cleaning. */
      struct SingleOrder {
        OLKey olKey;
        uint offerId;
        /* The `offer` given to the maker will be cleaned of `prev`/`next` pointers. */
        Offer offer;
        /* `takerWants`/`takerGives` mutate over execution. Initially the `wants`/`gives` from the taker's pov, then actual `wants`/`gives` adjusted by offer's price and volume. */
        uint takerWants;
        uint takerGives;
        /* `offerDetail` is only populated when necessary. */
        OfferDetail offerDetail;
        Global global;
        /* The `local` given to the maker will be cleaned of tick tree information. */
        Local local;
      }
    
      /* <a id="MgvLib/OrderResult"></a> `OrderResult` holds additional data for the maker and is given to them _after_ they fulfilled an offer. It gives them their own returned data from the previous call and an `mgvData` specifying whether Mangrove encountered an error. */
    
      struct OrderResult {
        /* `makerData` holds a message that was either returned by the maker or passed as revert message at the end of the trade execution*/
        bytes32 makerData;
        /* `mgvData` is an [internal Mangrove status code](#MgvOfferTaking/statusCodes) code. */
        bytes32 mgvData;
      }
    
      /* `CleanTarget` holds data about an offer that should be cleaned, i.e. made to fail by executing it with the specified volume. It is used in `MgvOfferTaking.cleanByImpersonation`. */
      struct CleanTarget {
        uint offerId;
        Tick tick;
        uint gasreq;
        uint takerWants;
      }
    }
    
    /* # Events
    The events emitted are listed here: */
    interface HasMgvEvents {
      /* 
        Events in solidity is a hard thing to do in a optimal way. If you look at it as a purely gas efficient issue, you want to emit as few events as possible and with as few fields as possible. But as events also has to be usable for an off chain user, then doing this is not always the best solution.
    
        We tried to list the main forces that drive which events and data to emit:
    
        1. Use as little gas as possible.
        2. An indexer should be able to keep track of the state of Mangrove.
        3. Doing RPC calls directly, should be able to find offers and other information based on offer list, maker, taker, offer id, etc.
    
        These forces are in conflict and it is impossible to find a solution that is optimal for all three.
        The following events are therefore an attempt to balance the trade-offs.
      */
    
      /* ### Mangrove Creation
    
      Emitted at the creation of the new Mangrove contract */
      event NewMgv();
    
      /* ### Mangrove adds or removes wei from `maker`'s account */
      /* 
        * Credit event occurs when an offer is removed from Mangrove or when the `fund` function is called
          This is emitted when a user's account on Mangrove is credited with some native funds, to be used as provision for offers.
    
          It emits the `maker`'s address and the `amount` credited
    
          The `maker` address is indexed so that we can filter on it when doing RPC calls.
    
          These are the scenarios where it can happen:
    
          - Fund Mangrove directly
          - Fund Mangrove when posting an offer
          - When updating an offer
            - Funding Mangrove or
            - the updated offer needs less provision, than it already has. Meaning the user gets credited the difference.
          - When retracting an offer and deprovisioning it. Meaning the user gets credited the provision that was locked by the offer.
          - When an offer fails. The remaining provision gets credited back to the maker
    
          A challenge for an indexer is to know how much provision each offer locks. With the current events, an indexer is going to have to know the liveness, gasreq and gasprice of the offer. If the offer is not live, then also know if it has been deprovisioned. And know what the gasbase of the offer list was when the offer was posted. With this information an indexer can calculate the exact provision locked by the offer.
    
          The indexer also cannot deduce what scenario the credit event happened. E.g., we don't know if the credit event happened because an offer failed or because the user simply funded Mangrove.
      */
      event Credit(address indexed maker, uint amount);
      /* 
        * Debit event occurs when an offer is posted or when the `withdraw` function is called 
          This is emitted when a user's account on Mangrove is debited with some native funds.
    
          It emits the `maker`'s address and the `amount` debited.
    
          The `maker` address is indexed so that we can filter on it when doing RPC calls.
    
          These are the scenarios where it can happen:
    
          - Withdraw funds from Mangrove directly
          - When posting an offer. The user gets debited the provision that the offer locks.
          - When updating an offer and it requires more provision that it already has. Meaning the user gets debited the difference.
    
          Same challenges as for Credit
      */
      event Debit(address indexed maker, uint amount);
    
      /* ### Mangrove reconfiguration */
      /*  
      This event is emitted when an offer list is activated or deactivated. Meaning one half of a market is opened.
    
      It emits the `olKeyHash` and the boolean `value`. By emitting this, an indexer will be able to keep track of what offer lists are active and what their hash is.
    
      The `olKeyHash` and both token addresses are indexed, so that we can filter on it when doing RPC calls.
      */
      event SetActive(
        bytes32 indexed olKeyHash, address indexed outbound_tkn, address indexed inbound_tkn, uint tickSpacing, bool value
      );
    
      /*
      This event is emitted when the fee of an offer list is changed.
    
      It emits the `olKeyHash` and the `value`. By emitting this, an indexer will be able to keep track of what fee each offer list has.
    
      The `olKeyHash` is indexed, so that we can filter on it when doing RPC calls.
      */
    
      event SetFee(bytes32 indexed olKeyHash, uint value);
    
      /*
      This event is emitted when the gasbase of an offer list is changed.
    
      It emits the `olKeyHash` and the `offer_gasbase`. By emitting this, an indexer will be able to keep track of what gasbase each offer list has.
    
      The `olKeyHash` is indexed, so that we can filter on it when doing RPC calls.
      */
      event SetGasbase(bytes32 indexed olKeyHash, uint offer_gasbase);
    
      /*
      This event is emitted when the governance of Mangrove is set.
    
      It emits the `governance` address. By emitting this, an indexer will be able to keep track of what governance address Mangrove has.
    
      No fields are indexed as there is no need for RPC calls to filter on this.
      */
      event SetGovernance(address value);
    
      /*
      This event is emitted when the monitor address of Mangrove is set. Be aware that the address for Monitor is also the address for the oracle.
    
      It emits the `monitor` / `oracle` address. By emitting this, an indexer will be able to keep track of what monitor/oracle address Mangrove use.
    
      No fields are indexed as there is no need for RPC calls to filter on this.
      */
      event SetMonitor(address value);
    
      /*
      This event is emitted when the configuration for whether to use an oracle or not is set.
    
      It emits the `useOracle`, which is a boolean value, that controls whether or not Mangrove reads its `gasprice` and `density` from an oracle or uses its own local values. By emitting this, an indexer will be able to keep track of if Mangrove is using an oracle.
    
      No fields are indexed as there is no need for RPC calls to filter on this.
      */
      event SetUseOracle(bool value);
    
      /*
      This event is emitted when the configuration for notify on Mangrove is set.
    
      It emits a boolean value, to tell whether or not notify is active. By emitting this, an indexer will be able to keep track of whether or not Mangrove notifies the Monitor/Oracle when and offer is taken, either successfully or not.
    
      No fields are indexed as there is no need for RPC calls to filter on this.
      */
      event SetNotify(bool value);
    
      /*
      This event is emitted when the gasmax of Mangrove is set.
    
      It emits the `gasmax`. By emitting this, an indexer will be able to keep track of what gasmax Mangrove has. Read more about Mangroves gasmax on [docs.mangrove.exchange](https://docs.mangrove.exchange)
    
      No fields are indexed as there is no need for RPC calls to filter on this.
      */
      event SetGasmax(uint value);
    
      /*
      This event is emitted when the density of an offer list is changed.
    
      It emits the `olKeyHash` and the `density`. By emitting this, an indexer will be able to keep track of what density each offer list has.
    
      The `olKeyHash` is indexed, so that we can filter on it when doing RPC calls.
      */
      event SetDensity96X32(bytes32 indexed olKeyHash, uint value);
    
      /*
      This event is emitted when the max recursion depth of Mangrove is set.
    
      It emits the max depth `value`. By emitting this, an indexer will be able to keep track of what max recursion depth Mangrove has. Read more about Mangroves max recursion depth on [docs.mangrove.exchange](https://docs.mangrove.exchange)
      */
    
      event SetMaxRecursionDepth(uint value);
    
      /*
      This event is emitted when the max gasreq for failing offers of Mangrove is set.
    
      It emits the max gasreq for failing offers `value`. By emitting this, an indexer will be able to keep track of what max gasreq for failing offers Mangrove has. Read more about Mangroves max gasreq for failing offers on [docs.mangrove.exchange](https://docs.mangrove.exchange)
      */
      event SetMaxGasreqForFailingOffers(uint value);
    
      /*
      This event is emitted when the gasprice of Mangrove is set.
    
      It emits the `gasprice`. By emitting this, an indexer will be able to keep track of what gasprice Mangrove has. Read more about Mangroves gasprice on [docs.mangrove.exchange](https://docs.mangrove.exchange)
    
      No fields are indexed as there is no need for RPC calls to filter on this.
      */
      event SetGasprice(uint value);
      /* ### Clean order execution */
      /*
      This event is emitted when a user tries to clean offers on Mangrove, using the build in clean functionality.
    
      It emits the `olKeyHash`, the `taker` address and `offersToBeCleaned`, which is the number of offers that should be cleaned. By emitting this event, an indexer can save what `offer list` the user is trying to clean and what `taker` is being used. 
      This way it can keep a context for the following events being emitted (Just like `OrderStart`). The `offersToBeCleaned` is emitted so that an indexer can keep track of how many offers the user tried to clean. 
      Combining this with the amount of `OfferFail` events emitted, then an indexer can know how many offers the user actually managed to clean. This could be used for analytics.
    
      The fields `olKeyHash` and `taker` are indexed, so that we can filter on them when doing RPC calls.
      */
      event CleanStart(bytes32 indexed olKeyHash, address indexed taker, uint offersToBeCleaned);
    
      /*
      This event is emitted when a Clean operation is completed.
    
      It does not emit any fields. This event is only needed in order to know that the clean operation is completed. This way an indexer can know exactly in what context we are in. 
      It could emit the total bounty received, but in order to know who got the bounty, an indexer would still be needed or we would have to emit the taker address as well, in order for an RPC call to find the data. 
      But an indexer would still be able to find this info, by collecting all the previous events. So we do not emit the bounty.
      */
      event CleanComplete();
    
      /* ### Market order execution */
      /*
      This event is emitted when a market order is started on Mangrove.
    
      It emits the `olKeyHash`, the `taker`, the `maxTick`, `fillVolume` and `fillWants`.
    
      The fields `olKeyHash` and `taker` are indexed, so that we can filter on them when doing RPC calls.
    
      By emitting this an indexer can keep track of what context the current market order is in. 
      E.g. if a user starts a market order and one of the offers taken also starts a market order, then we can in an indexer have a stack of started market orders and thereby know exactly what offer list the order is running on and the taker.
    
      By emitting `maxTick`, `fillVolume` and `fillWants`, we can now also know how much of the market order was filled and if it matches the price given. See OrderComplete for more.
      */
      event OrderStart(bytes32 indexed olKeyHash, address indexed taker, Tick maxTick, uint fillVolume, bool fillWants);
    
      /*
      This event is emitted when a market order is finished.
    
      It emits `olKeyHash`, the `taker` and the total `fee paid`. We need this event, in order to know that a market order is completed. This way an indexer can know exactly in what context we are in.
      The total `fee paid` for that market order, is needed, as we do not emit this any other places. The fields `olKeyHash` and `taker` is not needed for an indexer, but they are emitted and indexed in order for RPC calls to filter and find the fee.
      */
      event OrderComplete(bytes32 indexed olKeyHash, address indexed taker, uint fee);
    
      /* ### Offer execution */
      /*
      This event is emitted when an offer is successfully taken. Meaning both maker and taker has gotten their funds.
    
      It emits the `olKeyHash`, `taker` address, the `offerId` and the `takerWants` and `takerGives` that the offer was taken at. 
      Just as for `OfferFail`, the `olKeyHash` and `taker` are not needed for an indexer to work, but are needed for RPC calls. 
      `olKeyHash` `taker` and `id` are indexed so that we can filter on them when doing RPC calls. As `maker` can be a strategy and not the actual owner, then we chose not to emit it here and to mark the field `id` indexed, 
      the strat should emit the relation between maker and offerId. This way you can still by RPC calls find the relevant offer successes
      So they are emitted and indexed for that reason. Just like `OfferFail` this event is emitted during posthook end, so it is emitted in reverse order compared to what order they are taken. 
      This event could be emitted at offer execution, but for consistency we emit it at posthook end.
    
      If the posthook of the offer fails. Then we emit `OfferSuccessWithPosthookData` instead of just `OfferSuccess`. This event has one extra field, which is the reason for the posthook failure. 
      By emitting the posthook data, an indexer can keep track of the reason posthook fails, this could for example be used for analytics.
    
      By emitting `offerId`, `wants` and `gives`, an indexer can keep track of whether the offer was partially or fully taken, by looking at the what the offer was posted at.
      */
      event OfferSuccess(
        bytes32 indexed olKeyHash, address indexed taker, uint indexed id, uint takerWants, uint takerGives
      );
    
      event OfferSuccessWithPosthookData(
        bytes32 indexed olKeyHash,
        address indexed taker,
        uint indexed id,
        uint takerWants,
        uint takerGives,
        bytes32 posthookData
      );
    
      /*
      This event is emitted when an offer fails, because of a maker error.
    
      It emits `olKeyHash`, `taker`, the `offerId`, the offers `takerWants`, `takerGives`, `penalty` and the `reason` for failure. 
      `olKeyHash` and `taker` are all fields that we do not need, in order for an indexer to work, as an indexer will be able the get that info from the former `OrderStart` and `OfferWrite` events. 
      But in order for RPC call to filter on this, we need to emit them. 
      `olKeyHash` `taker` and `id` are indexed so that we can filter on them when doing RPC calls. As `maker` can be a strategy and not the actual owner, then we chose to not emit it here and to mark the field `id` indexed, 
      the strat should emit the relation between maker and offerId. This way you can still by RPC calls find the relevant offer successes
    
      If the posthook of the offer fails. Then we emit `OfferFailWithPosthookData` instead of just `OfferFail`. 
      This event has one extra field, which is the reason for the posthook failure. By emitting the posthook data, an indexer can keep track of the reason posthook fails, this could for example be used for analytics.
    
      This event is emitted during posthook end, we wait to emit this event to the end, because we need the information of `penalty`, which is only available at the end of the posthook. 
      This means that `OfferFail` events are emitted in reverse order, compared to what order they are taken. This is due to the way we handle posthooks. The same goes for `OfferSuccess`.
    
      By emitting this event, an indexer can keep track of, if an offer failed and thereby if the offer is live. 
      By emitting the `takerWants` and `takerGives` that the offer was taken with, then an indexer can keep track of these amounts, which could be useful for e.g. strategy manager, to know if their offers fail at a certain amount.
      */
      event OfferFail(
        bytes32 indexed olKeyHash,
        address indexed taker,
        uint indexed id,
        uint takerWants,
        uint takerGives,
        uint penalty,
        // `mgvData` may only be `"mgv/makerRevert"`, `"mgv/makerTransferFail"` or `"mgv/makerReceiveFail"`
        bytes32 mgvData
      );
    
      event OfferFailWithPosthookData(
        bytes32 indexed olKeyHash,
        address indexed taker,
        uint indexed id,
        uint takerWants,
        uint takerGives,
        uint penalty,
        // `mgvData` may only be `"mgv/makerRevert"`, `"mgv/makerTransferFail"` or `"mgv/makerReceiveFail"`
        bytes32 mgvData,
        bytes32 posthookData
      );
    
      /* 
      ### After `permit` and `approve` 
        This is emitted when a user permits another address to use a certain amount of its funds to do market orders, or when a user revokes another address to use a certain amount of its funds.
    
        Approvals are based on the pair of outbound and inbound token. Be aware that it is not offer list bases, as an offer list also holds the tick spacing.
    
        We emit `outbound` token, `inbound` token, `owner`, msg.sender (`spender`), `value`. Where `owner` is the one who owns the funds, `spender` is the one who is allowed to use the funds and `value` is the amount of funds that is allowed to be used.
    
        Outbound, inbound and owner is indexed, this way one can filter on these fields when doing RPC calls. If we could somehow combine outbound and inbound into one field, then we could also index the spender.
      */
      event Approval(
        address indexed outbound_tkn, address indexed inbound_tkn, address indexed owner, address spender, uint value
      );
    
      /* ### Mangrove closure */
      event Kill();
    
      /* ### An offer was created or updated.
      This event is emitted when an offer is posted on Mangrove.
    
      It emits the `olKeyHash`, the `maker` address, the `tick`, the `gives`, the `gasprice`, `gasreq` and the offers `id`.
    
      By emitting the `olKeyHash` and `id`, an indexer will be able to keep track of each offer, because offer list and id together create a unique id for the offer. By emitting the `maker` address, we are able to keep track of who has posted what offer. The `tick` and `gives`, enables an indexer to know exactly how much an offer is willing to give and at what price, this could for example be used to calculate a return. The `gasprice` and `gasreq`, enables an indexer to calculate how much provision is locked by the offer, see `Credit` for more information.
    
      The fields `olKeyHash` and `maker` are indexed, so that we can filter on them when doing RPC calls.
      */
      event OfferWrite(
        bytes32 indexed olKeyHash, address indexed maker, int tick, uint gives, uint gasprice, uint gasreq, uint id
      );
    
      /*
      This event is emitted when a user retracts his offer.
    
      It emits the `olKeyHash`, the `maker` address, `offerId` and whether or not the user chose to `deprovision` the offer.
    
      By emitting this event an indexer knows whether or not an offer is live. And whether or not an offer is deprovisioned. This is important because we need to know this, when we try to calculate how much an offer locks in provision. See the description of `Credit` for more info.
    
      The `maker` is not needed for an indexer to work, but is needed for RPC calls, so it is emitted and indexed for that reason. The `olKeyHash` is only indexed because it is needed for RPC calls. 
      */
      event OfferRetract(bytes32 indexed olKeyHash, address indexed maker, uint id, bool deprovision);
    }
    
    /* # IMaker interface */
    interface IMaker {
      /* Called upon offer execution. 
      - If the call throws, Mangrove will not try to transfer funds and the first 32 bytes of revert reason are passed to `makerPosthook` as `makerData`
      - If the call returns normally, `returnData` is passed to `makerPosthook` as `makerData` and Mangrove will attempt to transfer the funds.
      */
      function makerExecute(MgvLib.SingleOrder calldata order) external returns (bytes32);
    
      /* Called after all offers of an order have been executed. Posthook of the last executed order is called first and full reentrancy into Mangrove is enabled at this time. `order` recalls key arguments of the order that was processed and `result` recalls important information for updating the current offer. (see [above](#MgvLib/OrderResult))*/
      function makerPosthook(MgvLib.SingleOrder calldata order, MgvLib.OrderResult calldata result) external;
    }
    
    /* # Monitor interface
    If enabled, the monitor receives notification after each offer execution and is read for each offer list's `gasprice` and `density`. */
    interface IMgvMonitor {
      function notifySuccess(MgvLib.SingleOrder calldata sor, address taker) external;
    
      function notifyFail(MgvLib.SingleOrder calldata sor, address taker) external;
    
      function read(OLKey memory olKey) external view returns (uint gasprice, Density density);
    }
    
  • lib/mangrove-core/src/preprocessed/Global.post.sol
    // SPDX-License-Identifier: MIT
    
    pragma solidity ^0.8.13;
    
    /* ************************************************** *
                GENERATED FILE. DO NOT EDIT.
     * ************************************************** */
    
    /* since you can't convert bool to uint in an expression without conditionals,
     * we add a file-level function and rely on compiler optimization
     */
    function uint_of_bool(bool b) pure returns (uint u) {
      assembly ("memory-safe") { u := b }
    }
    import "@mgv/lib/core/Constants.sol";
    
    struct GlobalUnpacked {
      address monitor;
      bool useOracle;
      bool notify;
      uint gasprice;
      uint gasmax;
      bool dead;
      uint maxRecursionDepth;
      uint maxGasreqForFailingOffers;
    }
    
    //some type safety for each struct
    type Global is uint;
    using GlobalLib for Global global;
    
    ////////////// ADDITIONAL DEFINITIONS, IF ANY ////////////////
    
    ////////////// END OF ADDITIONAL DEFINITIONS /////////////////
    
    library GlobalLib {
    
      // number of bits in each field
      uint constant monitor_bits                   = 160;
      uint constant useOracle_bits                 = 1;
      uint constant notify_bits                    = 1;
      uint constant gasprice_bits                  = 26;
      uint constant gasmax_bits                    = 24;
      uint constant dead_bits                      = 1;
      uint constant maxRecursionDepth_bits         = 8;
      uint constant maxGasreqForFailingOffers_bits = 32;
    
      // number of bits before each field
      uint constant monitor_before                   = 0                        + 0;
      uint constant useOracle_before                 = monitor_before           + monitor_bits;
      uint constant notify_before                    = useOracle_before         + useOracle_bits;
      uint constant gasprice_before                  = notify_before            + notify_bits;
      uint constant gasmax_before                    = gasprice_before          + gasprice_bits;
      uint constant dead_before                      = gasmax_before            + gasmax_bits;
      uint constant maxRecursionDepth_before         = dead_before              + dead_bits;
      uint constant maxGasreqForFailingOffers_before = maxRecursionDepth_before + maxRecursionDepth_bits;
    
      // focus-mask: 1s at field location, 0s elsewhere
      uint constant monitor_mask_inv                   = (ONES << 256 - monitor_bits) >> monitor_before;
      uint constant useOracle_mask_inv                 = (ONES << 256 - useOracle_bits) >> useOracle_before;
      uint constant notify_mask_inv                    = (ONES << 256 - notify_bits) >> notify_before;
      uint constant gasprice_mask_inv                  = (ONES << 256 - gasprice_bits) >> gasprice_before;
      uint constant gasmax_mask_inv                    = (ONES << 256 - gasmax_bits) >> gasmax_before;
      uint constant dead_mask_inv                      = (ONES << 256 - dead_bits) >> dead_before;
      uint constant maxRecursionDepth_mask_inv         = (ONES << 256 - maxRecursionDepth_bits) >> maxRecursionDepth_before;
      uint constant maxGasreqForFailingOffers_mask_inv = (ONES << 256 - maxGasreqForFailingOffers_bits) >> maxGasreqForFailingOffers_before;
    
      // cleanup-mask: 0s at field location, 1s elsewhere
      uint constant monitor_mask                   = ~monitor_mask_inv;
      uint constant useOracle_mask                 = ~useOracle_mask_inv;
      uint constant notify_mask                    = ~notify_mask_inv;
      uint constant gasprice_mask                  = ~gasprice_mask_inv;
      uint constant gasmax_mask                    = ~gasmax_mask_inv;
      uint constant dead_mask                      = ~dead_mask_inv;
      uint constant maxRecursionDepth_mask         = ~maxRecursionDepth_mask_inv;
      uint constant maxGasreqForFailingOffers_mask = ~maxGasreqForFailingOffers_mask_inv;
    
      // cast-mask: 0s followed by |field| trailing 1s
      uint constant monitor_cast_mask                   = ~(ONES << monitor_bits);
      uint constant useOracle_cast_mask                 = ~(ONES << useOracle_bits);
      uint constant notify_cast_mask                    = ~(ONES << notify_bits);
      uint constant gasprice_cast_mask                  = ~(ONES << gasprice_bits);
      uint constant gasmax_cast_mask                    = ~(ONES << gasmax_bits);
      uint constant dead_cast_mask                      = ~(ONES << dead_bits);
      uint constant maxRecursionDepth_cast_mask         = ~(ONES << maxRecursionDepth_bits);
      uint constant maxGasreqForFailingOffers_cast_mask = ~(ONES << maxGasreqForFailingOffers_bits);
    
      // size-related error message
      string constant monitor_size_error                   = "mgv/config/monitor/160bits";
      string constant useOracle_size_error                 = "mgv/config/useOracle/1bits";
      string constant notify_size_error                    = "mgv/config/notify/1bits";
      string constant gasprice_size_error                  = "mgv/config/gasprice/26bits";
      string constant gasmax_size_error                    = "mgv/config/gasmax/24bits";
      string constant dead_size_error                      = "mgv/config/dead/1bits";
      string constant maxRecursionDepth_size_error         = "mgv/config/maxRecursionDepth/8bits";
      string constant maxGasreqForFailingOffers_size_error = "mgv/config/maxGasreqForFailingOffers/32bits";
    
      // from packed to in-memory struct
      function to_struct(Global __packed) internal pure returns (GlobalUnpacked memory __s) { unchecked {
        __s.monitor                   = address(uint160(uint(Global.unwrap(__packed) << monitor_before) >> (256 - monitor_bits)));
        __s.useOracle                 = ((Global.unwrap(__packed) & useOracle_mask_inv) > 0);
        __s.notify                    = ((Global.unwrap(__packed) & notify_mask_inv) > 0);
        __s.gasprice                  = uint(Global.unwrap(__packed) << gasprice_before) >> (256 - gasprice_bits);
        __s.gasmax                    = uint(Global.unwrap(__packed) << gasmax_before) >> (256 - gasmax_bits);
        __s.dead                      = ((Global.unwrap(__packed) & dead_mask_inv) > 0);
        __s.maxRecursionDepth         = uint(Global.unwrap(__packed) << maxRecursionDepth_before) >> (256 - maxRecursionDepth_bits);
        __s.maxGasreqForFailingOffers = uint(Global.unwrap(__packed) << maxGasreqForFailingOffers_before) >> (256 - maxGasreqForFailingOffers_bits);
      }}
    
      // equality checking
      function eq(Global __packed1, Global __packed2) internal pure returns (bool) { unchecked {
        return Global.unwrap(__packed1) == Global.unwrap(__packed2);
      }}
    
      // from packed to a tuple
      function unpack(Global __packed) internal pure returns (address __monitor, bool __useOracle, bool __notify, uint __gasprice, uint __gasmax, bool __dead, uint __maxRecursionDepth, uint __maxGasreqForFailingOffers) { unchecked {
        __monitor                   = address(uint160(uint(Global.unwrap(__packed) << monitor_before) >> (256 - monitor_bits)));
        __useOracle                 = ((Global.unwrap(__packed) & useOracle_mask_inv) > 0);
        __notify                    = ((Global.unwrap(__packed) & notify_mask_inv) > 0);
        __gasprice                  = uint(Global.unwrap(__packed) << gasprice_before) >> (256 - gasprice_bits);
        __gasmax                    = uint(Global.unwrap(__packed) << gasmax_before) >> (256 - gasmax_bits);
        __dead                      = ((Global.unwrap(__packed) & dead_mask_inv) > 0);
        __maxRecursionDepth         = uint(Global.unwrap(__packed) << maxRecursionDepth_before) >> (256 - maxRecursionDepth_bits);
        __maxGasreqForFailingOffers = uint(Global.unwrap(__packed) << maxGasreqForFailingOffers_before) >> (256 - maxGasreqForFailingOffers_bits);
      }}
    
      // getters
      function monitor(Global __packed) internal pure returns(address) { unchecked {
        return address(uint160(uint(Global.unwrap(__packed) << monitor_before) >> (256 - monitor_bits)));
      }}
    
      // setters
      function monitor(Global __packed,address val) internal pure returns(Global) { unchecked {
        return Global.wrap((Global.unwrap(__packed) & monitor_mask) | (uint(uint160(val)) << (256 - monitor_bits)) >> monitor_before);
      }}
      
      function useOracle(Global __packed) internal pure returns(bool) { unchecked {
        return ((Global.unwrap(__packed) & useOracle_mask_inv) > 0);
      }}
    
      // setters
      function useOracle(Global __packed,bool val) internal pure returns(Global) { unchecked {
        return Global.wrap((Global.unwrap(__packed) & useOracle_mask) | (uint_of_bool(val) << (256 - useOracle_bits)) >> useOracle_before);
      }}
      
      function notify(Global __packed) internal pure returns(bool) { unchecked {
        return ((Global.unwrap(__packed) & notify_mask_inv) > 0);
      }}
    
      // setters
      function notify(Global __packed,bool val) internal pure returns(Global) { unchecked {
        return Global.wrap((Global.unwrap(__packed) & notify_mask) | (uint_of_bool(val) << (256 - notify_bits)) >> notify_before);
      }}
      
      function gasprice(Global __packed) internal pure returns(uint) { unchecked {
        return uint(Global.unwrap(__packed) << gasprice_before) >> (256 - gasprice_bits);
      }}
    
      // setters
      function gasprice(Global __packed,uint val) internal pure returns(Global) { unchecked {
        return Global.wrap((Global.unwrap(__packed) & gasprice_mask) | (val << (256 - gasprice_bits)) >> gasprice_before);
      }}
      
      function gasmax(Global __packed) internal pure returns(uint) { unchecked {
        return uint(Global.unwrap(__packed) << gasmax_before) >> (256 - gasmax_bits);
      }}
    
      // setters
      function gasmax(Global __packed,uint val) internal pure returns(Global) { unchecked {
        return Global.wrap((Global.unwrap(__packed) & gasmax_mask) | (val << (256 - gasmax_bits)) >> gasmax_before);
      }}
      
      function dead(Global __packed) internal pure returns(bool) { unchecked {
        return ((Global.unwrap(__packed) & dead_mask_inv) > 0);
      }}
    
      // setters
      function dead(Global __packed,bool val) internal pure returns(Global) { unchecked {
        return Global.wrap((Global.unwrap(__packed) & dead_mask) | (uint_of_bool(val) << (256 - dead_bits)) >> dead_before);
      }}
      
      function maxRecursionDepth(Global __packed) internal pure returns(uint) { unchecked {
        return uint(Global.unwrap(__packed) << maxRecursionDepth_before) >> (256 - maxRecursionDepth_bits);
      }}
    
      // setters
      function maxRecursionDepth(Global __packed,uint val) internal pure returns(Global) { unchecked {
        return Global.wrap((Global.unwrap(__packed) & maxRecursionDepth_mask) | (val << (256 - maxRecursionDepth_bits)) >> maxRecursionDepth_before);
      }}
      
      function maxGasreqForFailingOffers(Global __packed) internal pure returns(uint) { unchecked {
        return uint(Global.unwrap(__packed) << maxGasreqForFailingOffers_before) >> (256 - maxGasreqForFailingOffers_bits);
      }}
    
      // setters
      function maxGasreqForFailingOffers(Global __packed,uint val) internal pure returns(Global) { unchecked {
        return Global.wrap((Global.unwrap(__packed) & maxGasreqForFailingOffers_mask) | (val << (256 - maxGasreqForFailingOffers_bits)) >> maxGasreqForFailingOffers_before);
      }}
      
    
      // from in-memory struct to packed
      function t_of_struct(GlobalUnpacked memory __s) internal pure returns (Global) { unchecked {
        return pack(__s.monitor, __s.useOracle, __s.notify, __s.gasprice, __s.gasmax, __s.dead, __s.maxRecursionDepth, __s.maxGasreqForFailingOffers);
      }}
    
      // from arguments to packed
      function pack(address __monitor, bool __useOracle, bool __notify, uint __gasprice, uint __gasmax, bool __dead, uint __maxRecursionDepth, uint __maxGasreqForFailingOffers) internal pure returns (Global) { unchecked {
        uint __packed;
        __packed |= (uint(uint160(__monitor)) << (256 - monitor_bits)) >> monitor_before;
        __packed |= (uint_of_bool(__useOracle) << (256 - useOracle_bits)) >> useOracle_before;
        __packed |= (uint_of_bool(__notify) << (256 - notify_bits)) >> notify_before;
        __packed |= (__gasprice << (256 - gasprice_bits)) >> gasprice_before;
        __packed |= (__gasmax << (256 - gasmax_bits)) >> gasmax_before;
        __packed |= (uint_of_bool(__dead) << (256 - dead_bits)) >> dead_before;
        __packed |= (__maxRecursionDepth << (256 - maxRecursionDepth_bits)) >> maxRecursionDepth_before;
        __packed |= (__maxGasreqForFailingOffers << (256 - maxGasreqForFailingOffers_bits)) >> maxGasreqForFailingOffers_before;
        return Global.wrap(__packed);
      }}
    
      // input checking
      function monitor_check(address __monitor) internal pure returns (bool) { unchecked {
        return (uint(uint160(__monitor)) & monitor_cast_mask) == uint(uint160(__monitor));
      }}
      function useOracle_check(bool __useOracle) internal pure returns (bool) { unchecked {
        return (uint_of_bool(__useOracle) & useOracle_cast_mask) == uint_of_bool(__useOracle);
      }}
      function notify_check(bool __notify) internal pure returns (bool) { unchecked {
        return (uint_of_bool(__notify) & notify_cast_mask) == uint_of_bool(__notify);
      }}
      function gasprice_check(uint __gasprice) internal pure returns (bool) { unchecked {
        return (__gasprice & gasprice_cast_mask) == __gasprice;
      }}
      function gasmax_check(uint __gasmax) internal pure returns (bool) { unchecked {
        return (__gasmax & gasmax_cast_mask) == __gasmax;
      }}
      function dead_check(bool __dead) internal pure returns (bool) { unchecked {
        return (uint_of_bool(__dead) & dead_cast_mask) == uint_of_bool(__dead);
      }}
      function maxRecursionDepth_check(uint __maxRecursionDepth) internal pure returns (bool) { unchecked {
        return (__maxRecursionDepth & maxRecursionDepth_cast_mask) == __maxRecursionDepth;
      }}
      function maxGasreqForFailingOffers_check(uint __maxGasreqForFailingOffers) internal pure returns (bool) { unchecked {
        return (__maxGasreqForFailingOffers & maxGasreqForFailingOffers_cast_mask) == __maxGasreqForFailingOffers;
      }}
    }
    
    
  • lib/mangrove-core/src/preprocessed/Local.post.sol
    // SPDX-License-Identifier: MIT
    
    pragma solidity ^0.8.13;
    
    /* ************************************************** *
                GENERATED FILE. DO NOT EDIT.
     * ************************************************** */
    
    /* since you can't convert bool to uint in an expression without conditionals,
     * we add a file-level function and rely on compiler optimization
     */
    function uint_of_bool(bool b) pure returns (uint u) {
      assembly ("memory-safe") { u := b }
    }
    import "@mgv/lib/core/Constants.sol";
    
    struct LocalUnpacked {
      bool active;
      uint fee;
      Density density;
      uint binPosInLeaf;
      Field level3;
      Field level2;
      Field level1;
      Field root;
      uint kilo_offer_gasbase;
      bool lock;
      uint last;
    }
    
    //some type safety for each struct
    type Local is uint;
    using LocalLib for Local global;
    
    ////////////// ADDITIONAL DEFINITIONS, IF ANY ////////////////
    import {Density, DensityLib} from "@mgv/lib/core/DensityLib.sol";
    import {Bin,TickTreeLib,Field} from "@mgv/lib/core/TickTreeLib.sol";
    /* Globally enable global.method(...) */
    import {LocalExtra,LocalUnpackedExtra} from "@mgv/lib/core/LocalExtra.sol";
    using LocalExtra for Local global;
    using LocalUnpackedExtra for LocalUnpacked global;
    
    ////////////// END OF ADDITIONAL DEFINITIONS /////////////////
    
    library LocalLib {
    
      // number of bits in each field
      uint constant active_bits             = 1;
      uint constant fee_bits                = 8;
      uint constant density_bits            = 9;
      uint constant binPosInLeaf_bits       = 2;
      uint constant level3_bits             = 64;
      uint constant level2_bits             = 64;
      uint constant level1_bits             = 64;
      uint constant root_bits               = 2;
      uint constant kilo_offer_gasbase_bits = 9;
      uint constant lock_bits               = 1;
      uint constant last_bits               = 32;
    
      // number of bits before each field
      uint constant active_before             = 0                         + 0;
      uint constant fee_before                = active_before             + active_bits;
      uint constant density_before            = fee_before                + fee_bits;
      uint constant binPosInLeaf_before       = density_before            + density_bits;
      uint constant level3_before             = binPosInLeaf_before       + binPosInLeaf_bits;
      uint constant level2_before             = level3_before             + level3_bits;
      uint constant level1_before             = level2_before             + level2_bits;
      uint constant root_before               = level1_before             + level1_bits;
      uint constant kilo_offer_gasbase_before = root_before               + root_bits;
      uint constant lock_before               = kilo_offer_gasbase_before + kilo_offer_gasbase_bits;
      uint constant last_before               = lock_before               + lock_bits;
    
      // focus-mask: 1s at field location, 0s elsewhere
      uint constant active_mask_inv             = (ONES << 256 - active_bits) >> active_before;
      uint constant fee_mask_inv                = (ONES << 256 - fee_bits) >> fee_before;
      uint constant density_mask_inv            = (ONES << 256 - density_bits) >> density_before;
      uint constant binPosInLeaf_mask_inv       = (ONES << 256 - binPosInLeaf_bits) >> binPosInLeaf_before;
      uint constant level3_mask_inv             = (ONES << 256 - level3_bits) >> level3_before;
      uint constant level2_mask_inv             = (ONES << 256 - level2_bits) >> level2_before;
      uint constant level1_mask_inv             = (ONES << 256 - level1_bits) >> level1_before;
      uint constant root_mask_inv               = (ONES << 256 - root_bits) >> root_before;
      uint constant kilo_offer_gasbase_mask_inv = (ONES << 256 - kilo_offer_gasbase_bits) >> kilo_offer_gasbase_before;
      uint constant lock_mask_inv               = (ONES << 256 - lock_bits) >> lock_before;
      uint constant last_mask_inv               = (ONES << 256 - last_bits) >> last_before;
    
      // cleanup-mask: 0s at field location, 1s elsewhere
      uint constant active_mask             = ~active_mask_inv;
      uint constant fee_mask                = ~fee_mask_inv;
      uint constant density_mask            = ~density_mask_inv;
      uint constant binPosInLeaf_mask       = ~binPosInLeaf_mask_inv;
      uint constant level3_mask             = ~level3_mask_inv;
      uint constant level2_mask             = ~level2_mask_inv;
      uint constant level1_mask             = ~level1_mask_inv;
      uint constant root_mask               = ~root_mask_inv;
      uint constant kilo_offer_gasbase_mask = ~kilo_offer_gasbase_mask_inv;
      uint constant lock_mask               = ~lock_mask_inv;
      uint constant last_mask               = ~last_mask_inv;
    
      // cast-mask: 0s followed by |field| trailing 1s
      uint constant active_cast_mask             = ~(ONES << active_bits);
      uint constant fee_cast_mask                = ~(ONES << fee_bits);
      uint constant density_cast_mask            = ~(ONES << density_bits);
      uint constant binPosInLeaf_cast_mask       = ~(ONES << binPosInLeaf_bits);
      uint constant level3_cast_mask             = ~(ONES << level3_bits);
      uint constant level2_cast_mask             = ~(ONES << level2_bits);
      uint constant level1_cast_mask             = ~(ONES << level1_bits);
      uint constant root_cast_mask               = ~(ONES << root_bits);
      uint constant kilo_offer_gasbase_cast_mask = ~(ONES << kilo_offer_gasbase_bits);
      uint constant lock_cast_mask               = ~(ONES << lock_bits);
      uint constant last_cast_mask               = ~(ONES << last_bits);
    
      // size-related error message
      string constant active_size_error             = "mgv/config/active/1bits";
      string constant fee_size_error                = "mgv/config/fee/8bits";
      string constant density_size_error            = "mgv/config/density/9bits";
      string constant binPosInLeaf_size_error       = "mgv/config/binPosInLeaf/2bits";
      string constant level3_size_error             = "mgv/config/level3/64bits";
      string constant level2_size_error             = "mgv/config/level2/64bits";
      string constant level1_size_error             = "mgv/config/level1/64bits";
      string constant root_size_error               = "mgv/config/root/2bits";
      string constant kilo_offer_gasbase_size_error = "mgv/config/kilo_offer_gasbase/9bits";
      string constant lock_size_error               = "mgv/config/lock/1bits";
      string constant last_size_error               = "mgv/config/last/32bits";
    
      // from packed to in-memory struct
      function to_struct(Local __packed) internal pure returns (LocalUnpacked memory __s) { unchecked {
        __s.active             = ((Local.unwrap(__packed) & active_mask_inv) > 0);
        __s.fee                = uint(Local.unwrap(__packed) << fee_before) >> (256 - fee_bits);
        __s.density            = Density.wrap(uint(Local.unwrap(__packed) << density_before) >> (256 - density_bits));
        __s.binPosInLeaf       = uint(Local.unwrap(__packed) << binPosInLeaf_before) >> (256 - binPosInLeaf_bits);
        __s.level3             = Field.wrap(uint(Local.unwrap(__packed) << level3_before) >> (256 - level3_bits));
        __s.level2             = Field.wrap(uint(Local.unwrap(__packed) << level2_before) >> (256 - level2_bits));
        __s.level1             = Field.wrap(uint(Local.unwrap(__packed) << level1_before) >> (256 - level1_bits));
        __s.root               = Field.wrap(uint(Local.unwrap(__packed) << root_before) >> (256 - root_bits));
        __s.kilo_offer_gasbase = uint(Local.unwrap(__packed) << kilo_offer_gasbase_before) >> (256 - kilo_offer_gasbase_bits);
        __s.lock               = ((Local.unwrap(__packed) & lock_mask_inv) > 0);
        __s.last               = uint(Local.unwrap(__packed) << last_before) >> (256 - last_bits);
      }}
    
      // equality checking
      function eq(Local __packed1, Local __packed2) internal pure returns (bool) { unchecked {
        return Local.unwrap(__packed1) == Local.unwrap(__packed2);
      }}
    
      // from packed to a tuple
      function unpack(Local __packed) internal pure returns (bool __active, uint __fee, Density __density, uint __binPosInLeaf, Field __level3, Field __level2, Field __level1, Field __root, uint __kilo_offer_gasbase, bool __lock, uint __last) { unchecked {
        __active             = ((Local.unwrap(__packed) & active_mask_inv) > 0);
        __fee                = uint(Local.unwrap(__packed) << fee_before) >> (256 - fee_bits);
        __density            = Density.wrap(uint(Local.unwrap(__packed) << density_before) >> (256 - density_bits));
        __binPosInLeaf       = uint(Local.unwrap(__packed) << binPosInLeaf_before) >> (256 - binPosInLeaf_bits);
        __level3             = Field.wrap(uint(Local.unwrap(__packed) << level3_before) >> (256 - level3_bits));
        __level2             = Field.wrap(uint(Local.unwrap(__packed) << level2_before) >> (256 - level2_bits));
        __level1             = Field.wrap(uint(Local.unwrap(__packed) << level1_before) >> (256 - level1_bits));
        __root               = Field.wrap(uint(Local.unwrap(__packed) << root_before) >> (256 - root_bits));
        __kilo_offer_gasbase = uint(Local.unwrap(__packed) << kilo_offer_gasbase_before) >> (256 - kilo_offer_gasbase_bits);
        __lock               = ((Local.unwrap(__packed) & lock_mask_inv) > 0);
        __last               = uint(Local.unwrap(__packed) << last_before) >> (256 - last_bits);
      }}
    
      // getters
      function active(Local __packed) internal pure returns(bool) { unchecked {
        return ((Local.unwrap(__packed) & active_mask_inv) > 0);
      }}
    
      // setters
      function active(Local __packed,bool val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & active_mask) | (uint_of_bool(val) << (256 - active_bits)) >> active_before);
      }}
      
      function fee(Local __packed) internal pure returns(uint) { unchecked {
        return uint(Local.unwrap(__packed) << fee_before) >> (256 - fee_bits);
      }}
    
      // setters
      function fee(Local __packed,uint val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & fee_mask) | (val << (256 - fee_bits)) >> fee_before);
      }}
      
      function density(Local __packed) internal pure returns(Density) { unchecked {
        return Density.wrap(uint(Local.unwrap(__packed) << density_before) >> (256 - density_bits));
      }}
    
      // setters
      function density(Local __packed,Density val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & density_mask) | (Density.unwrap(val) << (256 - density_bits)) >> density_before);
      }}
      
      function binPosInLeaf(Local __packed) internal pure returns(uint) { unchecked {
        return uint(Local.unwrap(__packed) << binPosInLeaf_before) >> (256 - binPosInLeaf_bits);
      }}
    
      // setters
      function binPosInLeaf(Local __packed,uint val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & binPosInLeaf_mask) | (val << (256 - binPosInLeaf_bits)) >> binPosInLeaf_before);
      }}
      
      function level3(Local __packed) internal pure returns(Field) { unchecked {
        return Field.wrap(uint(Local.unwrap(__packed) << level3_before) >> (256 - level3_bits));
      }}
    
      // setters
      function level3(Local __packed,Field val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & level3_mask) | (Field.unwrap(val) << (256 - level3_bits)) >> level3_before);
      }}
      
      function level2(Local __packed) internal pure returns(Field) { unchecked {
        return Field.wrap(uint(Local.unwrap(__packed) << level2_before) >> (256 - level2_bits));
      }}
    
      // setters
      function level2(Local __packed,Field val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & level2_mask) | (Field.unwrap(val) << (256 - level2_bits)) >> level2_before);
      }}
      
      function level1(Local __packed) internal pure returns(Field) { unchecked {
        return Field.wrap(uint(Local.unwrap(__packed) << level1_before) >> (256 - level1_bits));
      }}
    
      // setters
      function level1(Local __packed,Field val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & level1_mask) | (Field.unwrap(val) << (256 - level1_bits)) >> level1_before);
      }}
      
      function root(Local __packed) internal pure returns(Field) { unchecked {
        return Field.wrap(uint(Local.unwrap(__packed) << root_before) >> (256 - root_bits));
      }}
    
      // setters
      function root(Local __packed,Field val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & root_mask) | (Field.unwrap(val) << (256 - root_bits)) >> root_before);
      }}
      
      function kilo_offer_gasbase(Local __packed) internal pure returns(uint) { unchecked {
        return uint(Local.unwrap(__packed) << kilo_offer_gasbase_before) >> (256 - kilo_offer_gasbase_bits);
      }}
    
      // setters
      function kilo_offer_gasbase(Local __packed,uint val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & kilo_offer_gasbase_mask) | (val << (256 - kilo_offer_gasbase_bits)) >> kilo_offer_gasbase_before);
      }}
      
      function lock(Local __packed) internal pure returns(bool) { unchecked {
        return ((Local.unwrap(__packed) & lock_mask_inv) > 0);
      }}
    
      // setters
      function lock(Local __packed,bool val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & lock_mask) | (uint_of_bool(val) << (256 - lock_bits)) >> lock_before);
      }}
      
      function last(Local __packed) internal pure returns(uint) { unchecked {
        return uint(Local.unwrap(__packed) << last_before) >> (256 - last_bits);
      }}
    
      // setters
      function last(Local __packed,uint val) internal pure returns(Local) { unchecked {
        return Local.wrap((Local.unwrap(__packed) & last_mask) | (val << (256 - last_bits)) >> last_before);
      }}
      
    
      // from in-memory struct to packed
      function t_of_struct(LocalUnpacked memory __s) internal pure returns (Local) { unchecked {
        return pack(__s.active, __s.fee, __s.density, __s.binPosInLeaf, __s.level3, __s.level2, __s.level1, __s.root, __s.kilo_offer_gasbase, __s.lock, __s.last);
      }}
    
      // from arguments to packed
      function pack(bool __active, uint __fee, Density __density, uint __binPosInLeaf, Field __level3, Field __level2, Field __level1, Field __root, uint __kilo_offer_gasbase, bool __lock, uint __last) internal pure returns (Local) { unchecked {
        uint __packed;
        __packed |= (uint_of_bool(__active) << (256 - active_bits)) >> active_before;
        __packed |= (__fee << (256 - fee_bits)) >> fee_before;
        __packed |= (Density.unwrap(__density) << (256 - density_bits)) >> density_before;
        __packed |= (__binPosInLeaf << (256 - binPosInLeaf_bits)) >> binPosInLeaf_before;
        __packed |= (Field.unwrap(__level3) << (256 - level3_bits)) >> level3_before;
        __packed |= (Field.unwrap(__level2) << (256 - level2_bits)) >> level2_before;
        __packed |= (Field.unwrap(__level1) << (256 - level1_bits)) >> level1_before;
        __packed |= (Field.unwrap(__root) << (256 - root_bits)) >> root_before;
        __packed |= (__kilo_offer_gasbase << (256 - kilo_offer_gasbase_bits)) >> kilo_offer_gasbase_before;
        __packed |= (uint_of_bool(__lock) << (256 - lock_bits)) >> lock_before;
        __packed |= (__last << (256 - last_bits)) >> last_before;
        return Local.wrap(__packed);
      }}
    
      // input checking
      function active_check(bool __active) internal pure returns (bool) { unchecked {
        return (uint_of_bool(__active) & active_cast_mask) == uint_of_bool(__active);
      }}
      function fee_check(uint __fee) internal pure returns (bool) { unchecked {
        return (__fee & fee_cast_mask) == __fee;
      }}
      function density_check(Density __density) internal pure returns (bool) { unchecked {
        return (Density.unwrap(__density) & density_cast_mask) == Density.unwrap(__density);
      }}
      function binPosInLeaf_check(uint __binPosInLeaf) internal pure returns (bool) { unchecked {
        return (__binPosInLeaf & binPosInLeaf_cast_mask) == __binPosInLeaf;
      }}
      function level3_check(Field __level3) internal pure returns (bool) { unchecked {
        return (Field.unwrap(__level3) & level3_cast_mask) == Field.unwrap(__level3);
      }}
      function level2_check(Field __level2) internal pure returns (bool) { unchecked {
        return (Field.unwrap(__level2) & level2_cast_mask) == Field.unwrap(__level2);
      }}
      function level1_check(Field __level1) internal pure returns (bool) { unchecked {
        return (Field.unwrap(__level1) & level1_cast_mask) == Field.unwrap(__level1);
      }}
      function root_check(Field __root) internal pure returns (bool) { unchecked {
        return (Field.unwrap(__root) & root_cast_mask) == Field.unwrap(__root);
      }}
      function kilo_offer_gasbase_check(uint __kilo_offer_gasbase) internal pure returns (bool) { unchecked {
        return (__kilo_offer_gasbase & kilo_offer_gasbase_cast_mask) == __kilo_offer_gasbase;
      }}
      function lock_check(bool __lock) internal pure returns (bool) { unchecked {
        return (uint_of_bool(__lock) & lock_cast_mask) == uint_of_bool(__lock);
      }}
      function last_check(uint __last) internal pure returns (bool) { unchecked {
        return (__last & last_cast_mask) == __last;
      }}
    }
    
    
  • lib/mangrove-core/src/preprocessed/Offer.post.sol
    // SPDX-License-Identifier: MIT
    
    pragma solidity ^0.8.13;
    
    /* ************************************************** *
                GENERATED FILE. DO NOT EDIT.
     * ************************************************** */
    
    /* since you can't convert bool to uint in an expression without conditionals,
     * we add a file-level function and rely on compiler optimization
     */
    function uint_of_bool(bool b) pure returns (uint u) {
      assembly ("memory-safe") { u := b }
    }
    import "@mgv/lib/core/Constants.sol";
    
    struct OfferUnpacked {
      uint prev;
      uint next;
      Tick tick;
      uint gives;
    }
    
    //some type safety for each struct
    type Offer is uint;
    using OfferLib for Offer global;
    
    ////////////// ADDITIONAL DEFINITIONS, IF ANY ////////////////
    import {Bin} from "@mgv/lib/core/TickTreeLib.sol";
    import {Tick} from "@mgv/lib/core/TickLib.sol";
    import {OfferExtra,OfferUnpackedExtra} from "@mgv/lib/core/OfferExtra.sol";
    
    using OfferExtra for Offer global;
    using OfferUnpackedExtra for OfferUnpacked global;
    
    ////////////// END OF ADDITIONAL DEFINITIONS /////////////////
    
    library OfferLib {
    
      // number of bits in each field
      uint constant prev_bits  = 32;
      uint constant next_bits  = 32;
      uint constant tick_bits  = 21;
      uint constant gives_bits = 127;
    
      // number of bits before each field
      uint constant prev_before  = 0           + 0;
      uint constant next_before  = prev_before + prev_bits;
      uint constant tick_before  = next_before + next_bits;
      uint constant gives_before = tick_before + tick_bits;
    
      // focus-mask: 1s at field location, 0s elsewhere
      uint constant prev_mask_inv  = (ONES << 256 - prev_bits) >> prev_before;
      uint constant next_mask_inv  = (ONES << 256 - next_bits) >> next_before;
      uint constant tick_mask_inv  = (ONES << 256 - tick_bits) >> tick_before;
      uint constant gives_mask_inv = (ONES << 256 - gives_bits) >> gives_before;
    
      // cleanup-mask: 0s at field location, 1s elsewhere
      uint constant prev_mask  = ~prev_mask_inv;
      uint constant next_mask  = ~next_mask_inv;
      uint constant tick_mask  = ~tick_mask_inv;
      uint constant gives_mask = ~gives_mask_inv;
    
      // cast-mask: 0s followed by |field| trailing 1s
      uint constant prev_cast_mask  = ~(ONES << prev_bits);
      uint constant next_cast_mask  = ~(ONES << next_bits);
      uint constant tick_cast_mask  = ~(ONES << tick_bits);
      uint constant gives_cast_mask = ~(ONES << gives_bits);
    
      // size-related error message
      string constant prev_size_error  = "mgv/config/prev/32bits";
      string constant next_size_error  = "mgv/config/next/32bits";
      string constant tick_size_error  = "mgv/config/tick/21bits";
      string constant gives_size_error = "mgv/config/gives/127bits";
    
      // from packed to in-memory struct
      function to_struct(Offer __packed) internal pure returns (OfferUnpacked memory __s) { unchecked {
        __s.prev  = uint(Offer.unwrap(__packed) << prev_before) >> (256 - prev_bits);
        __s.next  = uint(Offer.unwrap(__packed) << next_before) >> (256 - next_bits);
        __s.tick  = Tick.wrap(int(int(Offer.unwrap(__packed) << tick_before) >> (256 - tick_bits)));
        __s.gives = uint(Offer.unwrap(__packed) << gives_before) >> (256 - gives_bits);
      }}
    
      // equality checking
      function eq(Offer __packed1, Offer __packed2) internal pure returns (bool) { unchecked {
        return Offer.unwrap(__packed1) == Offer.unwrap(__packed2);
      }}
    
      // from packed to a tuple
      function unpack(Offer __packed) internal pure returns (uint __prev, uint __next, Tick __tick, uint __gives) { unchecked {
        __prev  = uint(Offer.unwrap(__packed) << prev_before) >> (256 - prev_bits);
        __next  = uint(Offer.unwrap(__packed) << next_before) >> (256 - next_bits);
        __tick  = Tick.wrap(int(int(Offer.unwrap(__packed) << tick_before) >> (256 - tick_bits)));
        __gives = uint(Offer.unwrap(__packed) << gives_before) >> (256 - gives_bits);
      }}
    
      // getters
      function prev(Offer __packed) internal pure returns(uint) { unchecked {
        return uint(Offer.unwrap(__packed) << prev_before) >> (256 - prev_bits);
      }}
    
      // setters
      function prev(Offer __packed,uint val) internal pure returns(Offer) { unchecked {
        return Offer.wrap((Offer.unwrap(__packed) & prev_mask) | (val << (256 - prev_bits)) >> prev_before);
      }}
      
      function next(Offer __packed) internal pure returns(uint) { unchecked {
        return uint(Offer.unwrap(__packed) << next_before) >> (256 - next_bits);
      }}
    
      // setters
      function next(Offer __packed,uint val) internal pure returns(Offer) { unchecked {
        return Offer.wrap((Offer.unwrap(__packed) & next_mask) | (val << (256 - next_bits)) >> next_before);
      }}
      
      function tick(Offer __packed) internal pure returns(Tick) { unchecked {
        return Tick.wrap(int(int(Offer.unwrap(__packed) << tick_before) >> (256 - tick_bits)));
      }}
    
      // setters
      function tick(Offer __packed,Tick val) internal pure returns(Offer) { unchecked {
        return Offer.wrap((Offer.unwrap(__packed) & tick_mask) | (uint(Tick.unwrap(val)) << (256 - tick_bits)) >> tick_before);
      }}
      
      function gives(Offer __packed) internal pure returns(uint) { unchecked {
        return uint(Offer.unwrap(__packed) << gives_before) >> (256 - gives_bits);
      }}
    
      // setters
      function gives(Offer __packed,uint val) internal pure returns(Offer) { unchecked {
        return Offer.wrap((Offer.unwrap(__packed) & gives_mask) | (val << (256 - gives_bits)) >> gives_before);
      }}
      
    
      // from in-memory struct to packed
      function t_of_struct(OfferUnpacked memory __s) internal pure returns (Offer) { unchecked {
        return pack(__s.prev, __s.next, __s.tick, __s.gives);
      }}
    
      // from arguments to packed
      function pack(uint __prev, uint __next, Tick __tick, uint __gives) internal pure returns (Offer) { unchecked {
        uint __packed;
        __packed |= (__prev << (256 - prev_bits)) >> prev_before;
        __packed |= (__next << (256 - next_bits)) >> next_before;
        __packed |= (uint(Tick.unwrap(__tick)) << (256 - tick_bits)) >> tick_before;
        __packed |= (__gives << (256 - gives_bits)) >> gives_before;
        return Offer.wrap(__packed);
      }}
    
      // input checking
      function prev_check(uint __prev) internal pure returns (bool) { unchecked {
        return (__prev & prev_cast_mask) == __prev;
      }}
      function next_check(uint __next) internal pure returns (bool) { unchecked {
        return (__next & next_cast_mask) == __next;
      }}
      function tick_check(Tick __tick) internal pure returns (bool) { unchecked {
        return (uint(Tick.unwrap(__tick)) & tick_cast_mask) == uint(Tick.unwrap(__tick));
      }}
      function gives_check(uint __gives) internal pure returns (bool) { unchecked {
        return (__gives & gives_cast_mask) == __gives;
      }}
    }
    
    
  • lib/mangrove-core/src/preprocessed/OfferDetail.post.sol
    // SPDX-License-Identifier: MIT
    
    pragma solidity ^0.8.13;
    
    /* ************************************************** *
                GENERATED FILE. DO NOT EDIT.
     * ************************************************** */
    
    /* since you can't convert bool to uint in an expression without conditionals,
     * we add a file-level function and rely on compiler optimization
     */
    function uint_of_bool(bool b) pure returns (uint u) {
      assembly ("memory-safe") { u := b }
    }
    import "@mgv/lib/core/Constants.sol";
    
    struct OfferDetailUnpacked {
      address maker;
      uint gasreq;
      uint kilo_offer_gasbase;
      uint gasprice;
    }
    
    //some type safety for each struct
    type OfferDetail is uint;
    using OfferDetailLib for OfferDetail global;
    
    ////////////// ADDITIONAL DEFINITIONS, IF ANY ////////////////
    import {OfferDetailExtra,OfferDetailUnpackedExtra} from "@mgv/lib/core/OfferDetailExtra.sol";
    using OfferDetailExtra for OfferDetail global;
    using OfferDetailUnpackedExtra for OfferDetailUnpacked global;
    
    ////////////// END OF ADDITIONAL DEFINITIONS /////////////////
    
    library OfferDetailLib {
    
      // number of bits in each field
      uint constant maker_bits              = 160;
      uint constant gasreq_bits             = 24;
      uint constant kilo_offer_gasbase_bits = 9;
      uint constant gasprice_bits           = 26;
    
      // number of bits before each field
      uint constant maker_before              = 0                         + 0;
      uint constant gasreq_before             = maker_before              + maker_bits;
      uint constant kilo_offer_gasbase_before = gasreq_before             + gasreq_bits;
      uint constant gasprice_before           = kilo_offer_gasbase_before + kilo_offer_gasbase_bits;
    
      // focus-mask: 1s at field location, 0s elsewhere
      uint constant maker_mask_inv              = (ONES << 256 - maker_bits) >> maker_before;
      uint constant gasreq_mask_inv             = (ONES << 256 - gasreq_bits) >> gasreq_before;
      uint constant kilo_offer_gasbase_mask_inv = (ONES << 256 - kilo_offer_gasbase_bits) >> kilo_offer_gasbase_before;
      uint constant gasprice_mask_inv           = (ONES << 256 - gasprice_bits) >> gasprice_before;
    
      // cleanup-mask: 0s at field location, 1s elsewhere
      uint constant maker_mask              = ~maker_mask_inv;
      uint constant gasreq_mask             = ~gasreq_mask_inv;
      uint constant kilo_offer_gasbase_mask = ~kilo_offer_gasbase_mask_inv;
      uint constant gasprice_mask           = ~gasprice_mask_inv;
    
      // cast-mask: 0s followed by |field| trailing 1s
      uint constant maker_cast_mask              = ~(ONES << maker_bits);
      uint constant gasreq_cast_mask             = ~(ONES << gasreq_bits);
      uint constant kilo_offer_gasbase_cast_mask = ~(ONES << kilo_offer_gasbase_bits);
      uint constant gasprice_cast_mask           = ~(ONES << gasprice_bits);
    
      // size-related error message
      string constant maker_size_error              = "mgv/config/maker/160bits";
      string constant gasreq_size_error             = "mgv/config/gasreq/24bits";
      string constant kilo_offer_gasbase_size_error = "mgv/config/kilo_offer_gasbase/9bits";
      string constant gasprice_size_error           = "mgv/config/gasprice/26bits";
    
      // from packed to in-memory struct
      function to_struct(OfferDetail __packed) internal pure returns (OfferDetailUnpacked memory __s) { unchecked {
        __s.maker              = address(uint160(uint(OfferDetail.unwrap(__packed) << maker_before) >> (256 - maker_bits)));
        __s.gasreq             = uint(OfferDetail.unwrap(__packed) << gasreq_before) >> (256 - gasreq_bits);
        __s.kilo_offer_gasbase = uint(OfferDetail.unwrap(__packed) << kilo_offer_gasbase_before) >> (256 - kilo_offer_gasbase_bits);
        __s.gasprice           = uint(OfferDetail.unwrap(__packed) << gasprice_before) >> (256 - gasprice_bits);
      }}
    
      // equality checking
      function eq(OfferDetail __packed1, OfferDetail __packed2) internal pure returns (bool) { unchecked {
        return OfferDetail.unwrap(__packed1) == OfferDetail.unwrap(__packed2);
      }}
    
      // from packed to a tuple
      function unpack(OfferDetail __packed) internal pure returns (address __maker, uint __gasreq, uint __kilo_offer_gasbase, uint __gasprice) { unchecked {
        __maker              = address(uint160(uint(OfferDetail.unwrap(__packed) << maker_before) >> (256 - maker_bits)));
        __gasreq             = uint(OfferDetail.unwrap(__packed) << gasreq_before) >> (256 - gasreq_bits);
        __kilo_offer_gasbase = uint(OfferDetail.unwrap(__packed) << kilo_offer_gasbase_before) >> (256 - kilo_offer_gasbase_bits);
        __gasprice           = uint(OfferDetail.unwrap(__packed) << gasprice_before) >> (256 - gasprice_bits);
      }}
    
      // getters
      function maker(OfferDetail __packed) internal pure returns(address) { unchecked {
        return address(uint160(uint(OfferDetail.unwrap(__packed) << maker_before) >> (256 - maker_bits)));
      }}
    
      // setters
      function maker(OfferDetail __packed,address val) internal pure returns(OfferDetail) { unchecked {
        return OfferDetail.wrap((OfferDetail.unwrap(__packed) & maker_mask) | (uint(uint160(val)) << (256 - maker_bits)) >> maker_before);
      }}
      
      function gasreq(OfferDetail __packed) internal pure returns(uint) { unchecked {
        return uint(OfferDetail.unwrap(__packed) << gasreq_before) >> (256 - gasreq_bits);
      }}
    
      // setters
      function gasreq(OfferDetail __packed,uint val) internal pure returns(OfferDetail) { unchecked {
        return OfferDetail.wrap((OfferDetail.unwrap(__packed) & gasreq_mask) | (val << (256 - gasreq_bits)) >> gasreq_before);
      }}
      
      function kilo_offer_gasbase(OfferDetail __packed) internal pure returns(uint) { unchecked {
        return uint(OfferDetail.unwrap(__packed) << kilo_offer_gasbase_before) >> (256 - kilo_offer_gasbase_bits);
      }}
    
      // setters
      function kilo_offer_gasbase(OfferDetail __packed,uint val) internal pure returns(OfferDetail) { unchecked {
        return OfferDetail.wrap((OfferDetail.unwrap(__packed) & kilo_offer_gasbase_mask) | (val << (256 - kilo_offer_gasbase_bits)) >> kilo_offer_gasbase_before);
      }}
      
      function gasprice(OfferDetail __packed) internal pure returns(uint) { unchecked {
        return uint(OfferDetail.unwrap(__packed) << gasprice_before) >> (256 - gasprice_bits);
      }}
    
      // setters
      function gasprice(OfferDetail __packed,uint val) internal pure returns(OfferDetail) { unchecked {
        return OfferDetail.wrap((OfferDetail.unwrap(__packed) & gasprice_mask) | (val << (256 - gasprice_bits)) >> gasprice_before);
      }}
      
    
      // from in-memory struct to packed
      function t_of_struct(OfferDetailUnpacked memory __s) internal pure returns (OfferDetail) { unchecked {
        return pack(__s.maker, __s.gasreq, __s.kilo_offer_gasbase, __s.gasprice);
      }}
    
      // from arguments to packed
      function pack(address __maker, uint __gasreq, uint __kilo_offer_gasbase, uint __gasprice) internal pure returns (OfferDetail) { unchecked {
        uint __packed;
        __packed |= (uint(uint160(__maker)) << (256 - maker_bits)) >> maker_before;
        __packed |= (__gasreq << (256 - gasreq_bits)) >> gasreq_before;
        __packed |= (__kilo_offer_gasbase << (256 - kilo_offer_gasbase_bits)) >> kilo_offer_gasbase_before;
        __packed |= (__gasprice << (256 - gasprice_bits)) >> gasprice_before;
        return OfferDetail.wrap(__packed);
      }}
    
      // input checking
      function maker_check(address __maker) internal pure returns (bool) { unchecked {
        return (uint(uint160(__maker)) & maker_cast_mask) == uint(uint160(__maker));
      }}
      function gasreq_check(uint __gasreq) internal pure returns (bool) { unchecked {
        return (__gasreq & gasreq_cast_mask) == __gasreq;
      }}
      function kilo_offer_gasbase_check(uint __kilo_offer_gasbase) internal pure returns (bool) { unchecked {
        return (__kilo_offer_gasbase & kilo_offer_gasbase_cast_mask) == __kilo_offer_gasbase;
      }}
      function gasprice_check(uint __gasprice) internal pure returns (bool) { unchecked {
        return (__gasprice & gasprice_cast_mask) == __gasprice;
      }}
    }
    
    
  • lib/mangrove-core/src/preprocessed/Structs.post.sol
    // SPDX-License-Identifier: MIT
    
    pragma solidity ^0.8.13;
    
    /* ************************************************** *
                GENERATED FILE. DO NOT EDIT.
     * ************************************************** */
    
    
    import {Offer, OfferUnpacked, OfferLib}  from "./Offer.post.sol";
    
    import {OfferDetail, OfferDetailUnpacked, OfferDetailLib}  from "./OfferDetail.post.sol";
    
    import {Global, GlobalUnpacked, GlobalLib}  from "./Global.post.sol";
    
    import {Local, LocalUnpacked, LocalLib}  from "./Local.post.sol";
  • lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.3.0) (interfaces/IERC4626.sol)
    
    pragma solidity ^0.8.20;
    
    import {IERC20} from "../token/ERC20/IERC20.sol";
    import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
    
    /**
     * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
     * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
     */
    interface IERC4626 is IERC20, IERC20Metadata {
        event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
    
        event Withdraw(
            address indexed sender,
            address indexed receiver,
            address indexed owner,
            uint256 assets,
            uint256 shares
        );
    
        /**
         * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
         *
         * - MUST be an ERC-20 token contract.
         * - MUST NOT revert.
         */
        function asset() external view returns (address assetTokenAddress);
    
        /**
         * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
         *
         * - SHOULD include any compounding that occurs from yield.
         * - MUST be inclusive of any fees that are charged against assets in the Vault.
         * - MUST NOT revert.
         */
        function totalAssets() external view returns (uint256 totalManagedAssets);
    
        /**
         * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
         * scenario where all the conditions are met.
         *
         * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
         * - MUST NOT show any variations depending on the caller.
         * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
         * - MUST NOT revert.
         *
         * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
         * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
         * from.
         */
        function convertToShares(uint256 assets) external view returns (uint256 shares);
    
        /**
         * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
         * scenario where all the conditions are met.
         *
         * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
         * - MUST NOT show any variations depending on the caller.
         * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
         * - MUST NOT revert.
         *
         * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
         * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
         * from.
         */
        function convertToAssets(uint256 shares) external view returns (uint256 assets);
    
        /**
         * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
         * through a deposit call.
         *
         * - MUST return a limited value if receiver is subject to some deposit limit.
         * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
         * - MUST NOT revert.
         */
        function maxDeposit(address receiver) external view returns (uint256 maxAssets);
    
        /**
         * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
         * current on-chain conditions.
         *
         * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
         *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
         *   in the same transaction.
         * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
         *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
         * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
         * - MUST NOT revert.
         *
         * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
         * share price or some other type of condition, meaning the depositor will lose assets by depositing.
         */
        function previewDeposit(uint256 assets) external view returns (uint256 shares);
    
        /**
         * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
         *
         * - MUST emit the Deposit event.
         * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
         *   deposit execution, and are accounted for during deposit.
         * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
         *   approving enough underlying tokens to the Vault contract, etc).
         *
         * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
         */
        function deposit(uint256 assets, address receiver) external returns (uint256 shares);
    
        /**
         * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
         * - MUST return a limited value if receiver is subject to some mint limit.
         * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
         * - MUST NOT revert.
         */
        function maxMint(address receiver) external view returns (uint256 maxShares);
    
        /**
         * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
         * current on-chain conditions.
         *
         * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
         *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
         *   same transaction.
         * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
         *   would be accepted, regardless if the user has enough tokens approved, etc.
         * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
         * - MUST NOT revert.
         *
         * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
         * share price or some other type of condition, meaning the depositor will lose assets by minting.
         */
        function previewMint(uint256 shares) external view returns (uint256 assets);
    
        /**
         * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
         *
         * - MUST emit the Deposit event.
         * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
         *   execution, and are accounted for during mint.
         * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
         *   approving enough underlying tokens to the Vault contract, etc).
         *
         * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
         */
        function mint(uint256 shares, address receiver) external returns (uint256 assets);
    
        /**
         * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
         * Vault, through a withdraw call.
         *
         * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
         * - MUST NOT revert.
         */
        function maxWithdraw(address owner) external view returns (uint256 maxAssets);
    
        /**
         * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
         * given current on-chain conditions.
         *
         * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
         *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
         *   called
         *   in the same transaction.
         * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
         *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
         * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
         * - MUST NOT revert.
         *
         * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
         * share price or some other type of condition, meaning the depositor will lose assets by depositing.
         */
        function previewWithdraw(uint256 assets) external view returns (uint256 shares);
    
        /**
         * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
         *
         * - MUST emit the Withdraw event.
         * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
         *   withdraw execution, and are accounted for during withdraw.
         * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
         *   not having enough shares, etc).
         *
         * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
         * Those methods should be performed separately.
         */
        function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
    
        /**
         * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
         * through a redeem call.
         *
         * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
         * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
         * - MUST NOT revert.
         */
        function maxRedeem(address owner) external view returns (uint256 maxShares);
    
        /**
         * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
         * given current on-chain conditions.
         *
         * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
         *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
         *   same transaction.
         * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
         *   redemption would be accepted, regardless if the user has enough shares, etc.
         * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
         * - MUST NOT revert.
         *
         * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
         * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
         */
        function previewRedeem(uint256 shares) external view returns (uint256 assets);
    
        /**
         * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
         *
         * - MUST emit the Withdraw event.
         * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
         *   redeem execution, and are accounted for during redeem.
         * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
         *   not having enough shares, etc).
         *
         * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
         * Those methods should be performed separately.
         */
        function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
    }
    
  • 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/utils/Panic.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
    
    pragma solidity ^0.8.20;
    
    /**
     * @dev Helper library for emitting standardized panic codes.
     *
     * ```solidity
     * contract Example {
     *      using Panic for uint256;
     *
     *      // Use any of the declared internal constants
     *      function foo() { Panic.GENERIC.panic(); }
     *
     *      // Alternatively
     *      function foo() { Panic.panic(Panic.GENERIC); }
     * }
     * ```
     *
     * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
     *
     * _Available since v5.1._
     */
    // slither-disable-next-line unused-state
    library Panic {
        /// @dev generic / unspecified error
        uint256 internal constant GENERIC = 0x00;
        /// @dev used by the assert() builtin
        uint256 internal constant ASSERT = 0x01;
        /// @dev arithmetic underflow or overflow
        uint256 internal constant UNDER_OVERFLOW = 0x11;
        /// @dev division or modulo by zero
        uint256 internal constant DIVISION_BY_ZERO = 0x12;
        /// @dev enum conversion error
        uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
        /// @dev invalid encoding in storage
        uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
        /// @dev empty array pop
        uint256 internal constant EMPTY_ARRAY_POP = 0x31;
        /// @dev array out of bounds access
        uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
        /// @dev resource error (too large allocation or too large array)
        uint256 internal constant RESOURCE_ERROR = 0x41;
        /// @dev calling invalid internal function
        uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
    
        /// @dev Reverts with a panic code. Recommended to use with
        /// the internal constants with predefined codes.
        function panic(uint256 code) internal pure {
            assembly ("memory-safe") {
                mstore(0x00, 0x4e487b71)
                mstore(0x20, code)
                revert(0x1c, 0x24)
            }
        }
    }
    
  • lib/openzeppelin-contracts/contracts/utils/math/Math.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
    
    pragma solidity ^0.8.20;
    
    import {Panic} from "../Panic.sol";
    import {SafeCast} from "./SafeCast.sol";
    
    /**
     * @dev Standard math utilities missing in the Solidity language.
     */
    library Math {
        enum Rounding {
            Floor, // Toward negative infinity
            Ceil, // Toward positive infinity
            Trunc, // Toward zero
            Expand // Away from zero
        }
    
        /**
         * @dev Return the 512-bit addition of two uint256.
         *
         * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
         */
        function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
            assembly ("memory-safe") {
                low := add(a, b)
                high := lt(low, a)
            }
        }
    
        /**
         * @dev Return the 512-bit multiplication of two uint256.
         *
         * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
         */
        function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
            // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = high * 2²⁵⁶ + low.
            assembly ("memory-safe") {
                let mm := mulmod(a, b, not(0))
                low := mul(a, b)
                high := sub(sub(mm, low), lt(mm, low))
            }
        }
    
        /**
         * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
         */
        function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
            unchecked {
                uint256 c = a + b;
                success = c >= a;
                result = c * SafeCast.toUint(success);
            }
        }
    
        /**
         * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
         */
        function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
            unchecked {
                uint256 c = a - b;
                success = c <= a;
                result = c * SafeCast.toUint(success);
            }
        }
    
        /**
         * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
         */
        function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
            unchecked {
                uint256 c = a * b;
                assembly ("memory-safe") {
                    // Only true when the multiplication doesn't overflow
                    // (c / a == b) || (a == 0)
                    success := or(eq(div(c, a), b), iszero(a))
                }
                // equivalent to: success ? c : 0
                result = c * SafeCast.toUint(success);
            }
        }
    
        /**
         * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
         */
        function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
            unchecked {
                success = b > 0;
                assembly ("memory-safe") {
                    // The `DIV` opcode returns zero when the denominator is 0.
                    result := div(a, b)
                }
            }
        }
    
        /**
         * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
         */
        function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
            unchecked {
                success = b > 0;
                assembly ("memory-safe") {
                    // The `MOD` opcode returns zero when the denominator is 0.
                    result := mod(a, b)
                }
            }
        }
    
        /**
         * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
         */
        function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
            (bool success, uint256 result) = tryAdd(a, b);
            return ternary(success, result, type(uint256).max);
        }
    
        /**
         * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
         */
        function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
            (, uint256 result) = trySub(a, b);
            return result;
        }
    
        /**
         * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
         */
        function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
            (bool success, uint256 result) = tryMul(a, b);
            return ternary(success, result, type(uint256).max);
        }
    
        /**
         * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
         *
         * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
         * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
         * one branch when needed, making this function more expensive.
         */
        function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
            unchecked {
                // branchless ternary works because:
                // b ^ (a ^ b) == a
                // b ^ 0 == b
                return b ^ ((a ^ b) * SafeCast.toUint(condition));
            }
        }
    
        /**
         * @dev Returns the largest of two numbers.
         */
        function max(uint256 a, uint256 b) internal pure returns (uint256) {
            return ternary(a > b, a, b);
        }
    
        /**
         * @dev Returns the smallest of two numbers.
         */
        function min(uint256 a, uint256 b) internal pure returns (uint256) {
            return ternary(a < b, a, b);
        }
    
        /**
         * @dev Returns the average of two numbers. The result is rounded towards
         * zero.
         */
        function average(uint256 a, uint256 b) internal pure returns (uint256) {
            // (a + b) / 2 can overflow.
            return (a & b) + (a ^ b) / 2;
        }
    
        /**
         * @dev Returns the ceiling of the division of two numbers.
         *
         * This differs from standard division with `/` in that it rounds towards infinity instead
         * of rounding towards zero.
         */
        function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
            if (b == 0) {
                // Guarantee the same behavior as in a regular Solidity division.
                Panic.panic(Panic.DIVISION_BY_ZERO);
            }
    
            // The following calculation ensures accurate ceiling division without overflow.
            // Since a is non-zero, (a - 1) / b will not overflow.
            // The largest possible result occurs when (a - 1) / b is type(uint256).max,
            // but the largest value we can obtain is type(uint256).max - 1, which happens
            // when a = type(uint256).max and b = 1.
            unchecked {
                return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
            }
        }
    
        /**
         * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
         * denominator == 0.
         *
         * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
         * Uniswap Labs also under MIT license.
         */
        function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
            unchecked {
                (uint256 high, uint256 low) = mul512(x, y);
    
                // Handle non-overflow cases, 256 by 256 division.
                if (high == 0) {
                    // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                    // The surrounding unchecked block does not change this fact.
                    // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                    return low / denominator;
                }
    
                // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
                if (denominator <= high) {
                    Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
                }
    
                ///////////////////////////////////////////////
                // 512 by 256 division.
                ///////////////////////////////////////////////
    
                // Make division exact by subtracting the remainder from [high low].
                uint256 remainder;
                assembly ("memory-safe") {
                    // Compute remainder using mulmod.
                    remainder := mulmod(x, y, denominator)
    
                    // Subtract 256 bit number from 512 bit number.
                    high := sub(high, gt(remainder, low))
                    low := sub(low, remainder)
                }
    
                // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
                // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
    
                uint256 twos = denominator & (0 - denominator);
                assembly ("memory-safe") {
                    // Divide denominator by twos.
                    denominator := div(denominator, twos)
    
                    // Divide [high low] by twos.
                    low := div(low, twos)
    
                    // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                    twos := add(div(sub(0, twos), twos), 1)
                }
    
                // Shift in bits from high into low.
                low |= high * twos;
    
                // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
                // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
                // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
                uint256 inverse = (3 * denominator) ^ 2;
    
                // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
                // works in modular arithmetic, doubling the correct bits in each step.
                inverse *= 2 - denominator * inverse; // inverse mod 2⁸
                inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
                inverse *= 2 - denominator * inverse; // inverse mod 2³²
                inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
                inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
                inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
    
                // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
                // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
                // is no longer required.
                result = low * inverse;
                return result;
            }
        }
    
        /**
         * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
         */
        function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
            return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
        }
    
        /**
         * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
         */
        function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
            unchecked {
                (uint256 high, uint256 low) = mul512(x, y);
                if (high >= 1 << n) {
                    Panic.panic(Panic.UNDER_OVERFLOW);
                }
                return (high << (256 - n)) | (low >> n);
            }
        }
    
        /**
         * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
         */
        function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
            return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
        }
    
        /**
         * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
         *
         * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
         * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
         *
         * If the input value is not inversible, 0 is returned.
         *
         * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
         * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
         */
        function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
            unchecked {
                if (n == 0) return 0;
    
                // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
                // Used to compute integers x and y such that: ax + ny = gcd(a, n).
                // When the gcd is 1, then the inverse of a modulo n exists and it's x.
                // ax + ny = 1
                // ax = 1 + (-y)n
                // ax ≡ 1 (mod n) # x is the inverse of a modulo n
    
                // If the remainder is 0 the gcd is n right away.
                uint256 remainder = a % n;
                uint256 gcd = n;
    
                // Therefore the initial coefficients are:
                // ax + ny = gcd(a, n) = n
                // 0a + 1n = n
                int256 x = 0;
                int256 y = 1;
    
                while (remainder != 0) {
                    uint256 quotient = gcd / remainder;
    
                    (gcd, remainder) = (
                        // The old remainder is the next gcd to try.
                        remainder,
                        // Compute the next remainder.
                        // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                        // where gcd is at most n (capped to type(uint256).max)
                        gcd - remainder * quotient
                    );
    
                    (x, y) = (
                        // Increment the coefficient of a.
                        y,
                        // Decrement the coefficient of n.
                        // Can overflow, but the result is casted to uint256 so that the
                        // next value of y is "wrapped around" to a value between 0 and n - 1.
                        x - y * int256(quotient)
                    );
                }
    
                if (gcd != 1) return 0; // No inverse exists.
                return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
            }
        }
    
        /**
         * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
         *
         * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
         * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
         * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
         *
         * NOTE: this function does NOT check that `p` is a prime greater than `2`.
         */
        function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
            unchecked {
                return Math.modExp(a, p - 2, p);
            }
        }
    
        /**
         * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
         *
         * Requirements:
         * - modulus can't be zero
         * - underlying staticcall to precompile must succeed
         *
         * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
         * sure the chain you're using it on supports the precompiled contract for modular exponentiation
         * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
         * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
         * interpreted as 0.
         */
        function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
            (bool success, uint256 result) = tryModExp(b, e, m);
            if (!success) {
                Panic.panic(Panic.DIVISION_BY_ZERO);
            }
            return result;
        }
    
        /**
         * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
         * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
         * to operate modulo 0 or if the underlying precompile reverted.
         *
         * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
         * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
         * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
         * of a revert, but the result may be incorrectly interpreted as 0.
         */
        function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
            if (m == 0) return (false, 0);
            assembly ("memory-safe") {
                let ptr := mload(0x40)
                // | Offset    | Content    | Content (Hex)                                                      |
                // |-----------|------------|--------------------------------------------------------------------|
                // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
                // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
                // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
                // | 0x60:0x7f | value of b | 0x<.............................................................b> |
                // | 0x80:0x9f | value of e | 0x<.............................................................e> |
                // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
                mstore(ptr, 0x20)
                mstore(add(ptr, 0x20), 0x20)
                mstore(add(ptr, 0x40), 0x20)
                mstore(add(ptr, 0x60), b)
                mstore(add(ptr, 0x80), e)
                mstore(add(ptr, 0xa0), m)
    
                // Given the result < m, it's guaranteed to fit in 32 bytes,
                // so we can use the memory scratch space located at offset 0.
                success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
                result := mload(0x00)
            }
        }
    
        /**
         * @dev Variant of {modExp} that supports inputs of arbitrary length.
         */
        function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
            (bool success, bytes memory result) = tryModExp(b, e, m);
            if (!success) {
                Panic.panic(Panic.DIVISION_BY_ZERO);
            }
            return result;
        }
    
        /**
         * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
         */
        function tryModExp(
            bytes memory b,
            bytes memory e,
            bytes memory m
        ) internal view returns (bool success, bytes memory result) {
            if (_zeroBytes(m)) return (false, new bytes(0));
    
            uint256 mLen = m.length;
    
            // Encode call args in result and move the free memory pointer
            result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
    
            assembly ("memory-safe") {
                let dataPtr := add(result, 0x20)
                // Write result on top of args to avoid allocating extra memory.
                success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
                // Overwrite the length.
                // result.length > returndatasize() is guaranteed because returndatasize() == m.length
                mstore(result, mLen)
                // Set the memory pointer after the returned data.
                mstore(0x40, add(dataPtr, mLen))
            }
        }
    
        /**
         * @dev Returns whether the provided byte array is zero.
         */
        function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
            for (uint256 i = 0; i < byteArray.length; ++i) {
                if (byteArray[i] != 0) {
                    return false;
                }
            }
            return true;
        }
    
        /**
         * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
         * towards zero.
         *
         * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
         * using integer operations.
         */
        function sqrt(uint256 a) internal pure returns (uint256) {
            unchecked {
                // Take care of easy edge cases when a == 0 or a == 1
                if (a <= 1) {
                    return a;
                }
    
                // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
                // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
                // the current value as `ε_n = | x_n - sqrt(a) |`.
                //
                // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
                // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
                // bigger than any uint256.
                //
                // By noticing that
                // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
                // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
                // to the msb function.
                uint256 aa = a;
                uint256 xn = 1;
    
                if (aa >= (1 << 128)) {
                    aa >>= 128;
                    xn <<= 64;
                }
                if (aa >= (1 << 64)) {
                    aa >>= 64;
                    xn <<= 32;
                }
                if (aa >= (1 << 32)) {
                    aa >>= 32;
                    xn <<= 16;
                }
                if (aa >= (1 << 16)) {
                    aa >>= 16;
                    xn <<= 8;
                }
                if (aa >= (1 << 8)) {
                    aa >>= 8;
                    xn <<= 4;
                }
                if (aa >= (1 << 4)) {
                    aa >>= 4;
                    xn <<= 2;
                }
                if (aa >= (1 << 2)) {
                    xn <<= 1;
                }
    
                // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
                //
                // We can refine our estimation by noticing that the middle of that interval minimizes the error.
                // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
                // This is going to be our x_0 (and ε_0)
                xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
    
                // From here, Newton's method give us:
                // x_{n+1} = (x_n + a / x_n) / 2
                //
                // One should note that:
                // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
                //              = ((x_n² + a) / (2 * x_n))² - a
                //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
                //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
                //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
                //              = (x_n² - a)² / (2 * x_n)²
                //              = ((x_n² - a) / (2 * x_n))²
                //              ≥ 0
                // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
                //
                // This gives us the proof of quadratic convergence of the sequence:
                // ε_{n+1} = | x_{n+1} - sqrt(a) |
                //         = | (x_n + a / x_n) / 2 - sqrt(a) |
                //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
                //         = | (x_n - sqrt(a))² / (2 * x_n) |
                //         = | ε_n² / (2 * x_n) |
                //         = ε_n² / | (2 * x_n) |
                //
                // For the first iteration, we have a special case where x_0 is known:
                // ε_1 = ε_0² / | (2 * x_0) |
                //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
                //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
                //     ≤ 2**(e-3) / 3
                //     ≤ 2**(e-3-log2(3))
                //     ≤ 2**(e-4.5)
                //
                // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
                // ε_{n+1} = ε_n² / | (2 * x_n) |
                //         ≤ (2**(e-k))² / (2 * 2**(e-1))
                //         ≤ 2**(2*e-2*k) / 2**e
                //         ≤ 2**(e-2*k)
                xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
                xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
                xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
                xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
                xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
                xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72
    
                // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
                // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
                // sqrt(a) or sqrt(a) + 1.
                return xn - SafeCast.toUint(xn > a / xn);
            }
        }
    
        /**
         * @dev Calculates sqrt(a), following the selected rounding direction.
         */
        function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
            unchecked {
                uint256 result = sqrt(a);
                return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
            }
        }
    
        /**
         * @dev Return the log in base 2 of a positive value rounded towards zero.
         * Returns 0 if given 0.
         */
        function log2(uint256 x) internal pure returns (uint256 r) {
            // If value has upper 128 bits set, log2 result is at least 128
            r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
            // If upper 64 bits of 128-bit half set, add 64 to result
            r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
            // If upper 32 bits of 64-bit half set, add 32 to result
            r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
            // If upper 16 bits of 32-bit half set, add 16 to result
            r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
            // If upper 8 bits of 16-bit half set, add 8 to result
            r |= SafeCast.toUint((x >> r) > 0xff) << 3;
            // If upper 4 bits of 8-bit half set, add 4 to result
            r |= SafeCast.toUint((x >> r) > 0xf) << 2;
    
            // Shifts value right by the current result and use it as an index into this lookup table:
            //
            // | x (4 bits) |  index  | table[index] = MSB position |
            // |------------|---------|-----------------------------|
            // |    0000    |    0    |        table[0] = 0         |
            // |    0001    |    1    |        table[1] = 0         |
            // |    0010    |    2    |        table[2] = 1         |
            // |    0011    |    3    |        table[3] = 1         |
            // |    0100    |    4    |        table[4] = 2         |
            // |    0101    |    5    |        table[5] = 2         |
            // |    0110    |    6    |        table[6] = 2         |
            // |    0111    |    7    |        table[7] = 2         |
            // |    1000    |    8    |        table[8] = 3         |
            // |    1001    |    9    |        table[9] = 3         |
            // |    1010    |   10    |        table[10] = 3        |
            // |    1011    |   11    |        table[11] = 3        |
            // |    1100    |   12    |        table[12] = 3        |
            // |    1101    |   13    |        table[13] = 3        |
            // |    1110    |   14    |        table[14] = 3        |
            // |    1111    |   15    |        table[15] = 3        |
            //
            // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
            assembly ("memory-safe") {
                r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
            }
        }
    
        /**
         * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
         * Returns 0 if given 0.
         */
        function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
            unchecked {
                uint256 result = log2(value);
                return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
            }
        }
    
        /**
         * @dev Return the log in base 10 of a positive value rounded towards zero.
         * Returns 0 if given 0.
         */
        function log10(uint256 value) internal pure returns (uint256) {
            uint256 result = 0;
            unchecked {
                if (value >= 10 ** 64) {
                    value /= 10 ** 64;
                    result += 64;
                }
                if (value >= 10 ** 32) {
                    value /= 10 ** 32;
                    result += 32;
                }
                if (value >= 10 ** 16) {
                    value /= 10 ** 16;
                    result += 16;
                }
                if (value >= 10 ** 8) {
                    value /= 10 ** 8;
                    result += 8;
                }
                if (value >= 10 ** 4) {
                    value /= 10 ** 4;
                    result += 4;
                }
                if (value >= 10 ** 2) {
                    value /= 10 ** 2;
                    result += 2;
                }
                if (value >= 10 ** 1) {
                    result += 1;
                }
            }
            return result;
        }
    
        /**
         * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
         * Returns 0 if given 0.
         */
        function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
            unchecked {
                uint256 result = log10(value);
                return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
            }
        }
    
        /**
         * @dev Return the log in base 256 of a positive value rounded towards zero.
         * Returns 0 if given 0.
         *
         * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
         */
        function log256(uint256 x) internal pure returns (uint256 r) {
            // If value has upper 128 bits set, log2 result is at least 128
            r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
            // If upper 64 bits of 128-bit half set, add 64 to result
            r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
            // If upper 32 bits of 64-bit half set, add 32 to result
            r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
            // If upper 16 bits of 32-bit half set, add 16 to result
            r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
            // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
            return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
        }
    
        /**
         * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
         * Returns 0 if given 0.
         */
        function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
            unchecked {
                uint256 result = log256(value);
                return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
            }
        }
    
        /**
         * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
         */
        function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
            return uint8(rounding) % 2 == 1;
        }
    }
    
  • lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
    // This file was procedurally generated from scripts/generate/templates/SafeCast.js.
    
    pragma solidity ^0.8.20;
    
    /**
     * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
     * checks.
     *
     * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
     * easily result in undesired exploitation or bugs, since developers usually
     * assume that overflows raise errors. `SafeCast` restores this intuition by
     * reverting the transaction when such an operation overflows.
     *
     * Using this library instead of the unchecked operations eliminates an entire
     * class of bugs, so it's recommended to use it always.
     */
    library SafeCast {
        /**
         * @dev Value doesn't fit in an uint of `bits` size.
         */
        error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
    
        /**
         * @dev An int value doesn't fit in an uint of `bits` size.
         */
        error SafeCastOverflowedIntToUint(int256 value);
    
        /**
         * @dev Value doesn't fit in an int of `bits` size.
         */
        error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
    
        /**
         * @dev An uint value doesn't fit in an int of `bits` size.
         */
        error SafeCastOverflowedUintToInt(uint256 value);
    
        /**
         * @dev Returns the downcasted uint248 from uint256, reverting on
         * overflow (when the input is greater than largest uint248).
         *
         * Counterpart to Solidity's `uint248` operator.
         *
         * Requirements:
         *
         * - input must fit into 248 bits
         */
        function toUint248(uint256 value) internal pure returns (uint248) {
            if (value > type(uint248).max) {
                revert SafeCastOverflowedUintDowncast(248, value);
            }
            return uint248(value);
        }
    
        /**
         * @dev Returns the downcasted uint240 from uint256, reverting on
         * overflow (when the input is greater than largest uint240).
         *
         * Counterpart to Solidity's `uint240` operator.
         *
         * Requirements:
         *
         * - input must fit into 240 bits
         */
        function toUint240(uint256 value) internal pure returns (uint240) {
            if (value > type(uint240).max) {
                revert SafeCastOverflowedUintDowncast(240, value);
            }
            return uint240(value);
        }
    
        /**
         * @dev Returns the downcasted uint232 from uint256, reverting on
         * overflow (when the input is greater than largest uint232).
         *
         * Counterpart to Solidity's `uint232` operator.
         *
         * Requirements:
         *
         * - input must fit into 232 bits
         */
        function toUint232(uint256 value) internal pure returns (uint232) {
            if (value > type(uint232).max) {
                revert SafeCastOverflowedUintDowncast(232, value);
            }
            return uint232(value);
        }
    
        /**
         * @dev Returns the downcasted uint224 from uint256, reverting on
         * overflow (when the input is greater than largest uint224).
         *
         * Counterpart to Solidity's `uint224` operator.
         *
         * Requirements:
         *
         * - input must fit into 224 bits
         */
        function toUint224(uint256 value) internal pure returns (uint224) {
            if (value > type(uint224).max) {
                revert SafeCastOverflowedUintDowncast(224, value);
            }
            return uint224(value);
        }
    
        /**
         * @dev Returns the downcasted uint216 from uint256, reverting on
         * overflow (when the input is greater than largest uint216).
         *
         * Counterpart to Solidity's `uint216` operator.
         *
         * Requirements:
         *
         * - input must fit into 216 bits
         */
        function toUint216(uint256 value) internal pure returns (uint216) {
            if (value > type(uint216).max) {
                revert SafeCastOverflowedUintDowncast(216, value);
            }
            return uint216(value);
        }
    
        /**
         * @dev Returns the downcasted uint208 from uint256, reverting on
         * overflow (when the input is greater than largest uint208).
         *
         * Counterpart to Solidity's `uint208` operator.
         *
         * Requirements:
         *
         * - input must fit into 208 bits
         */
        function toUint208(uint256 value) internal pure returns (uint208) {
            if (value > type(uint208).max) {
                revert SafeCastOverflowedUintDowncast(208, value);
            }
            return uint208(value);
        }
    
        /**
         * @dev Returns the downcasted uint200 from uint256, reverting on
         * overflow (when the input is greater than largest uint200).
         *
         * Counterpart to Solidity's `uint200` operator.
         *
         * Requirements:
         *
         * - input must fit into 200 bits
         */
        function toUint200(uint256 value) internal pure returns (uint200) {
            if (value > type(uint200).max) {
                revert SafeCastOverflowedUintDowncast(200, value);
            }
            return uint200(value);
        }
    
        /**
         * @dev Returns the downcasted uint192 from uint256, reverting on
         * overflow (when the input is greater than largest uint192).
         *
         * Counterpart to Solidity's `uint192` operator.
         *
         * Requirements:
         *
         * - input must fit into 192 bits
         */
        function toUint192(uint256 value) internal pure returns (uint192) {
            if (value > type(uint192).max) {
                revert SafeCastOverflowedUintDowncast(192, value);
            }
            return uint192(value);
        }
    
        /**
         * @dev Returns the downcasted uint184 from uint256, reverting on
         * overflow (when the input is greater than largest uint184).
         *
         * Counterpart to Solidity's `uint184` operator.
         *
         * Requirements:
         *
         * - input must fit into 184 bits
         */
        function toUint184(uint256 value) internal pure returns (uint184) {
            if (value > type(uint184).max) {
                revert SafeCastOverflowedUintDowncast(184, value);
            }
            return uint184(value);
        }
    
        /**
         * @dev Returns the downcasted uint176 from uint256, reverting on
         * overflow (when the input is greater than largest uint176).
         *
         * Counterpart to Solidity's `uint176` operator.
         *
         * Requirements:
         *
         * - input must fit into 176 bits
         */
        function toUint176(uint256 value) internal pure returns (uint176) {
            if (value > type(uint176).max) {
                revert SafeCastOverflowedUintDowncast(176, value);
            }
            return uint176(value);
        }
    
        /**
         * @dev Returns the downcasted uint168 from uint256, reverting on
         * overflow (when the input is greater than largest uint168).
         *
         * Counterpart to Solidity's `uint168` operator.
         *
         * Requirements:
         *
         * - input must fit into 168 bits
         */
        function toUint168(uint256 value) internal pure returns (uint168) {
            if (value > type(uint168).max) {
                revert SafeCastOverflowedUintDowncast(168, value);
            }
            return uint168(value);
        }
    
        /**
         * @dev Returns the downcasted uint160 from uint256, reverting on
         * overflow (when the input is greater than largest uint160).
         *
         * Counterpart to Solidity's `uint160` operator.
         *
         * Requirements:
         *
         * - input must fit into 160 bits
         */
        function toUint160(uint256 value) internal pure returns (uint160) {
            if (value > type(uint160).max) {
                revert SafeCastOverflowedUintDowncast(160, value);
            }
            return uint160(value);
        }
    
        /**
         * @dev Returns the downcasted uint152 from uint256, reverting on
         * overflow (when the input is greater than largest uint152).
         *
         * Counterpart to Solidity's `uint152` operator.
         *
         * Requirements:
         *
         * - input must fit into 152 bits
         */
        function toUint152(uint256 value) internal pure returns (uint152) {
            if (value > type(uint152).max) {
                revert SafeCastOverflowedUintDowncast(152, value);
            }
            return uint152(value);
        }
    
        /**
         * @dev Returns the downcasted uint144 from uint256, reverting on
         * overflow (when the input is greater than largest uint144).
         *
         * Counterpart to Solidity's `uint144` operator.
         *
         * Requirements:
         *
         * - input must fit into 144 bits
         */
        function toUint144(uint256 value) internal pure returns (uint144) {
            if (value > type(uint144).max) {
                revert SafeCastOverflowedUintDowncast(144, value);
            }
            return uint144(value);
        }
    
        /**
         * @dev Returns the downcasted uint136 from uint256, reverting on
         * overflow (when the input is greater than largest uint136).
         *
         * Counterpart to Solidity's `uint136` operator.
         *
         * Requirements:
         *
         * - input must fit into 136 bits
         */
        function toUint136(uint256 value) internal pure returns (uint136) {
            if (value > type(uint136).max) {
                revert SafeCastOverflowedUintDowncast(136, value);
            }
            return uint136(value);
        }
    
        /**
         * @dev Returns the downcasted uint128 from uint256, reverting on
         * overflow (when the input is greater than largest uint128).
         *
         * Counterpart to Solidity's `uint128` operator.
         *
         * Requirements:
         *
         * - input must fit into 128 bits
         */
        function toUint128(uint256 value) internal pure returns (uint128) {
            if (value > type(uint128).max) {
                revert SafeCastOverflowedUintDowncast(128, value);
            }
            return uint128(value);
        }
    
        /**
         * @dev Returns the downcasted uint120 from uint256, reverting on
         * overflow (when the input is greater than largest uint120).
         *
         * Counterpart to Solidity's `uint120` operator.
         *
         * Requirements:
         *
         * - input must fit into 120 bits
         */
        function toUint120(uint256 value) internal pure returns (uint120) {
            if (value > type(uint120).max) {
                revert SafeCastOverflowedUintDowncast(120, value);
            }
            return uint120(value);
        }
    
        /**
         * @dev Returns the downcasted uint112 from uint256, reverting on
         * overflow (when the input is greater than largest uint112).
         *
         * Counterpart to Solidity's `uint112` operator.
         *
         * Requirements:
         *
         * - input must fit into 112 bits
         */
        function toUint112(uint256 value) internal pure returns (uint112) {
            if (value > type(uint112).max) {
                revert SafeCastOverflowedUintDowncast(112, value);
            }
            return uint112(value);
        }
    
        /**
         * @dev Returns the downcasted uint104 from uint256, reverting on
         * overflow (when the input is greater than largest uint104).
         *
         * Counterpart to Solidity's `uint104` operator.
         *
         * Requirements:
         *
         * - input must fit into 104 bits
         */
        function toUint104(uint256 value) internal pure returns (uint104) {
            if (value > type(uint104).max) {
                revert SafeCastOverflowedUintDowncast(104, value);
            }
            return uint104(value);
        }
    
        /**
         * @dev Returns the downcasted uint96 from uint256, reverting on
         * overflow (when the input is greater than largest uint96).
         *
         * Counterpart to Solidity's `uint96` operator.
         *
         * Requirements:
         *
         * - input must fit into 96 bits
         */
        function toUint96(uint256 value) internal pure returns (uint96) {
            if (value > type(uint96).max) {
                revert SafeCastOverflowedUintDowncast(96, value);
            }
            return uint96(value);
        }
    
        /**
         * @dev Returns the downcasted uint88 from uint256, reverting on
         * overflow (when the input is greater than largest uint88).
         *
         * Counterpart to Solidity's `uint88` operator.
         *
         * Requirements:
         *
         * - input must fit into 88 bits
         */
        function toUint88(uint256 value) internal pure returns (uint88) {
            if (value > type(uint88).max) {
                revert SafeCastOverflowedUintDowncast(88, value);
            }
            return uint88(value);
        }
    
        /**
         * @dev Returns the downcasted uint80 from uint256, reverting on
         * overflow (when the input is greater than largest uint80).
         *
         * Counterpart to Solidity's `uint80` operator.
         *
         * Requirements:
         *
         * - input must fit into 80 bits
         */
        function toUint80(uint256 value) internal pure returns (uint80) {
            if (value > type(uint80).max) {
                revert SafeCastOverflowedUintDowncast(80, value);
            }
            return uint80(value);
        }
    
        /**
         * @dev Returns the downcasted uint72 from uint256, reverting on
         * overflow (when the input is greater than largest uint72).
         *
         * Counterpart to Solidity's `uint72` operator.
         *
         * Requirements:
         *
         * - input must fit into 72 bits
         */
        function toUint72(uint256 value) internal pure returns (uint72) {
            if (value > type(uint72).max) {
                revert SafeCastOverflowedUintDowncast(72, value);
            }
            return uint72(value);
        }
    
        /**
         * @dev Returns the downcasted uint64 from uint256, reverting on
         * overflow (when the input is greater than largest uint64).
         *
         * Counterpart to Solidity's `uint64` operator.
         *
         * Requirements:
         *
         * - input must fit into 64 bits
         */
        function toUint64(uint256 value) internal pure returns (uint64) {
            if (value > type(uint64).max) {
                revert SafeCastOverflowedUintDowncast(64, value);
            }
            return uint64(value);
        }
    
        /**
         * @dev Returns the downcasted uint56 from uint256, reverting on
         * overflow (when the input is greater than largest uint56).
         *
         * Counterpart to Solidity's `uint56` operator.
         *
         * Requirements:
         *
         * - input must fit into 56 bits
         */
        function toUint56(uint256 value) internal pure returns (uint56) {
            if (value > type(uint56).max) {
                revert SafeCastOverflowedUintDowncast(56, value);
            }
            return uint56(value);
        }
    
        /**
         * @dev Returns the downcasted uint48 from uint256, reverting on
         * overflow (when the input is greater than largest uint48).
         *
         * Counterpart to Solidity's `uint48` operator.
         *
         * Requirements:
         *
         * - input must fit into 48 bits
         */
        function toUint48(uint256 value) internal pure returns (uint48) {
            if (value > type(uint48).max) {
                revert SafeCastOverflowedUintDowncast(48, value);
            }
            return uint48(value);
        }
    
        /**
         * @dev Returns the downcasted uint40 from uint256, reverting on
         * overflow (when the input is greater than largest uint40).
         *
         * Counterpart to Solidity's `uint40` operator.
         *
         * Requirements:
         *
         * - input must fit into 40 bits
         */
        function toUint40(uint256 value) internal pure returns (uint40) {
            if (value > type(uint40).max) {
                revert SafeCastOverflowedUintDowncast(40, value);
            }
            return uint40(value);
        }
    
        /**
         * @dev Returns the downcasted uint32 from uint256, reverting on
         * overflow (when the input is greater than largest uint32).
         *
         * Counterpart to Solidity's `uint32` operator.
         *
         * Requirements:
         *
         * - input must fit into 32 bits
         */
        function toUint32(uint256 value) internal pure returns (uint32) {
            if (value > type(uint32).max) {
                revert SafeCastOverflowedUintDowncast(32, value);
            }
            return uint32(value);
        }
    
        /**
         * @dev Returns the downcasted uint24 from uint256, reverting on
         * overflow (when the input is greater than largest uint24).
         *
         * Counterpart to Solidity's `uint24` operator.
         *
         * Requirements:
         *
         * - input must fit into 24 bits
         */
        function toUint24(uint256 value) internal pure returns (uint24) {
            if (value > type(uint24).max) {
                revert SafeCastOverflowedUintDowncast(24, value);
            }
            return uint24(value);
        }
    
        /**
         * @dev Returns the downcasted uint16 from uint256, reverting on
         * overflow (when the input is greater than largest uint16).
         *
         * Counterpart to Solidity's `uint16` operator.
         *
         * Requirements:
         *
         * - input must fit into 16 bits
         */
        function toUint16(uint256 value) internal pure returns (uint16) {
            if (value > type(uint16).max) {
                revert SafeCastOverflowedUintDowncast(16, value);
            }
            return uint16(value);
        }
    
        /**
         * @dev Returns the downcasted uint8 from uint256, reverting on
         * overflow (when the input is greater than largest uint8).
         *
         * Counterpart to Solidity's `uint8` operator.
         *
         * Requirements:
         *
         * - input must fit into 8 bits
         */
        function toUint8(uint256 value) internal pure returns (uint8) {
            if (value > type(uint8).max) {
                revert SafeCastOverflowedUintDowncast(8, value);
            }
            return uint8(value);
        }
    
        /**
         * @dev Converts a signed int256 into an unsigned uint256.
         *
         * Requirements:
         *
         * - input must be greater than or equal to 0.
         */
        function toUint256(int256 value) internal pure returns (uint256) {
            if (value < 0) {
                revert SafeCastOverflowedIntToUint(value);
            }
            return uint256(value);
        }
    
        /**
         * @dev Returns the downcasted int248 from int256, reverting on
         * overflow (when the input is less than smallest int248 or
         * greater than largest int248).
         *
         * Counterpart to Solidity's `int248` operator.
         *
         * Requirements:
         *
         * - input must fit into 248 bits
         */
        function toInt248(int256 value) internal pure returns (int248 downcasted) {
            downcasted = int248(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(248, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int240 from int256, reverting on
         * overflow (when the input is less than smallest int240 or
         * greater than largest int240).
         *
         * Counterpart to Solidity's `int240` operator.
         *
         * Requirements:
         *
         * - input must fit into 240 bits
         */
        function toInt240(int256 value) internal pure returns (int240 downcasted) {
            downcasted = int240(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(240, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int232 from int256, reverting on
         * overflow (when the input is less than smallest int232 or
         * greater than largest int232).
         *
         * Counterpart to Solidity's `int232` operator.
         *
         * Requirements:
         *
         * - input must fit into 232 bits
         */
        function toInt232(int256 value) internal pure returns (int232 downcasted) {
            downcasted = int232(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(232, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int224 from int256, reverting on
         * overflow (when the input is less than smallest int224 or
         * greater than largest int224).
         *
         * Counterpart to Solidity's `int224` operator.
         *
         * Requirements:
         *
         * - input must fit into 224 bits
         */
        function toInt224(int256 value) internal pure returns (int224 downcasted) {
            downcasted = int224(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(224, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int216 from int256, reverting on
         * overflow (when the input is less than smallest int216 or
         * greater than largest int216).
         *
         * Counterpart to Solidity's `int216` operator.
         *
         * Requirements:
         *
         * - input must fit into 216 bits
         */
        function toInt216(int256 value) internal pure returns (int216 downcasted) {
            downcasted = int216(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(216, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int208 from int256, reverting on
         * overflow (when the input is less than smallest int208 or
         * greater than largest int208).
         *
         * Counterpart to Solidity's `int208` operator.
         *
         * Requirements:
         *
         * - input must fit into 208 bits
         */
        function toInt208(int256 value) internal pure returns (int208 downcasted) {
            downcasted = int208(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(208, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int200 from int256, reverting on
         * overflow (when the input is less than smallest int200 or
         * greater than largest int200).
         *
         * Counterpart to Solidity's `int200` operator.
         *
         * Requirements:
         *
         * - input must fit into 200 bits
         */
        function toInt200(int256 value) internal pure returns (int200 downcasted) {
            downcasted = int200(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(200, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int192 from int256, reverting on
         * overflow (when the input is less than smallest int192 or
         * greater than largest int192).
         *
         * Counterpart to Solidity's `int192` operator.
         *
         * Requirements:
         *
         * - input must fit into 192 bits
         */
        function toInt192(int256 value) internal pure returns (int192 downcasted) {
            downcasted = int192(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(192, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int184 from int256, reverting on
         * overflow (when the input is less than smallest int184 or
         * greater than largest int184).
         *
         * Counterpart to Solidity's `int184` operator.
         *
         * Requirements:
         *
         * - input must fit into 184 bits
         */
        function toInt184(int256 value) internal pure returns (int184 downcasted) {
            downcasted = int184(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(184, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int176 from int256, reverting on
         * overflow (when the input is less than smallest int176 or
         * greater than largest int176).
         *
         * Counterpart to Solidity's `int176` operator.
         *
         * Requirements:
         *
         * - input must fit into 176 bits
         */
        function toInt176(int256 value) internal pure returns (int176 downcasted) {
            downcasted = int176(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(176, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int168 from int256, reverting on
         * overflow (when the input is less than smallest int168 or
         * greater than largest int168).
         *
         * Counterpart to Solidity's `int168` operator.
         *
         * Requirements:
         *
         * - input must fit into 168 bits
         */
        function toInt168(int256 value) internal pure returns (int168 downcasted) {
            downcasted = int168(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(168, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int160 from int256, reverting on
         * overflow (when the input is less than smallest int160 or
         * greater than largest int160).
         *
         * Counterpart to Solidity's `int160` operator.
         *
         * Requirements:
         *
         * - input must fit into 160 bits
         */
        function toInt160(int256 value) internal pure returns (int160 downcasted) {
            downcasted = int160(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(160, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int152 from int256, reverting on
         * overflow (when the input is less than smallest int152 or
         * greater than largest int152).
         *
         * Counterpart to Solidity's `int152` operator.
         *
         * Requirements:
         *
         * - input must fit into 152 bits
         */
        function toInt152(int256 value) internal pure returns (int152 downcasted) {
            downcasted = int152(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(152, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int144 from int256, reverting on
         * overflow (when the input is less than smallest int144 or
         * greater than largest int144).
         *
         * Counterpart to Solidity's `int144` operator.
         *
         * Requirements:
         *
         * - input must fit into 144 bits
         */
        function toInt144(int256 value) internal pure returns (int144 downcasted) {
            downcasted = int144(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(144, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int136 from int256, reverting on
         * overflow (when the input is less than smallest int136 or
         * greater than largest int136).
         *
         * Counterpart to Solidity's `int136` operator.
         *
         * Requirements:
         *
         * - input must fit into 136 bits
         */
        function toInt136(int256 value) internal pure returns (int136 downcasted) {
            downcasted = int136(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(136, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int128 from int256, reverting on
         * overflow (when the input is less than smallest int128 or
         * greater than largest int128).
         *
         * Counterpart to Solidity's `int128` operator.
         *
         * Requirements:
         *
         * - input must fit into 128 bits
         */
        function toInt128(int256 value) internal pure returns (int128 downcasted) {
            downcasted = int128(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(128, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int120 from int256, reverting on
         * overflow (when the input is less than smallest int120 or
         * greater than largest int120).
         *
         * Counterpart to Solidity's `int120` operator.
         *
         * Requirements:
         *
         * - input must fit into 120 bits
         */
        function toInt120(int256 value) internal pure returns (int120 downcasted) {
            downcasted = int120(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(120, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int112 from int256, reverting on
         * overflow (when the input is less than smallest int112 or
         * greater than largest int112).
         *
         * Counterpart to Solidity's `int112` operator.
         *
         * Requirements:
         *
         * - input must fit into 112 bits
         */
        function toInt112(int256 value) internal pure returns (int112 downcasted) {
            downcasted = int112(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(112, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int104 from int256, reverting on
         * overflow (when the input is less than smallest int104 or
         * greater than largest int104).
         *
         * Counterpart to Solidity's `int104` operator.
         *
         * Requirements:
         *
         * - input must fit into 104 bits
         */
        function toInt104(int256 value) internal pure returns (int104 downcasted) {
            downcasted = int104(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(104, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int96 from int256, reverting on
         * overflow (when the input is less than smallest int96 or
         * greater than largest int96).
         *
         * Counterpart to Solidity's `int96` operator.
         *
         * Requirements:
         *
         * - input must fit into 96 bits
         */
        function toInt96(int256 value) internal pure returns (int96 downcasted) {
            downcasted = int96(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(96, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int88 from int256, reverting on
         * overflow (when the input is less than smallest int88 or
         * greater than largest int88).
         *
         * Counterpart to Solidity's `int88` operator.
         *
         * Requirements:
         *
         * - input must fit into 88 bits
         */
        function toInt88(int256 value) internal pure returns (int88 downcasted) {
            downcasted = int88(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(88, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int80 from int256, reverting on
         * overflow (when the input is less than smallest int80 or
         * greater than largest int80).
         *
         * Counterpart to Solidity's `int80` operator.
         *
         * Requirements:
         *
         * - input must fit into 80 bits
         */
        function toInt80(int256 value) internal pure returns (int80 downcasted) {
            downcasted = int80(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(80, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int72 from int256, reverting on
         * overflow (when the input is less than smallest int72 or
         * greater than largest int72).
         *
         * Counterpart to Solidity's `int72` operator.
         *
         * Requirements:
         *
         * - input must fit into 72 bits
         */
        function toInt72(int256 value) internal pure returns (int72 downcasted) {
            downcasted = int72(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(72, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int64 from int256, reverting on
         * overflow (when the input is less than smallest int64 or
         * greater than largest int64).
         *
         * Counterpart to Solidity's `int64` operator.
         *
         * Requirements:
         *
         * - input must fit into 64 bits
         */
        function toInt64(int256 value) internal pure returns (int64 downcasted) {
            downcasted = int64(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(64, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int56 from int256, reverting on
         * overflow (when the input is less than smallest int56 or
         * greater than largest int56).
         *
         * Counterpart to Solidity's `int56` operator.
         *
         * Requirements:
         *
         * - input must fit into 56 bits
         */
        function toInt56(int256 value) internal pure returns (int56 downcasted) {
            downcasted = int56(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(56, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int48 from int256, reverting on
         * overflow (when the input is less than smallest int48 or
         * greater than largest int48).
         *
         * Counterpart to Solidity's `int48` operator.
         *
         * Requirements:
         *
         * - input must fit into 48 bits
         */
        function toInt48(int256 value) internal pure returns (int48 downcasted) {
            downcasted = int48(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(48, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int40 from int256, reverting on
         * overflow (when the input is less than smallest int40 or
         * greater than largest int40).
         *
         * Counterpart to Solidity's `int40` operator.
         *
         * Requirements:
         *
         * - input must fit into 40 bits
         */
        function toInt40(int256 value) internal pure returns (int40 downcasted) {
            downcasted = int40(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(40, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int32 from int256, reverting on
         * overflow (when the input is less than smallest int32 or
         * greater than largest int32).
         *
         * Counterpart to Solidity's `int32` operator.
         *
         * Requirements:
         *
         * - input must fit into 32 bits
         */
        function toInt32(int256 value) internal pure returns (int32 downcasted) {
            downcasted = int32(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(32, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int24 from int256, reverting on
         * overflow (when the input is less than smallest int24 or
         * greater than largest int24).
         *
         * Counterpart to Solidity's `int24` operator.
         *
         * Requirements:
         *
         * - input must fit into 24 bits
         */
        function toInt24(int256 value) internal pure returns (int24 downcasted) {
            downcasted = int24(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(24, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int16 from int256, reverting on
         * overflow (when the input is less than smallest int16 or
         * greater than largest int16).
         *
         * Counterpart to Solidity's `int16` operator.
         *
         * Requirements:
         *
         * - input must fit into 16 bits
         */
        function toInt16(int256 value) internal pure returns (int16 downcasted) {
            downcasted = int16(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(16, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int8 from int256, reverting on
         * overflow (when the input is less than smallest int8 or
         * greater than largest int8).
         *
         * Counterpart to Solidity's `int8` operator.
         *
         * Requirements:
         *
         * - input must fit into 8 bits
         */
        function toInt8(int256 value) internal pure returns (int8 downcasted) {
            downcasted = int8(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(8, value);
            }
        }
    
        /**
         * @dev Converts an unsigned uint256 into a signed int256.
         *
         * Requirements:
         *
         * - input must be less than or equal to maxInt256.
         */
        function toInt256(uint256 value) internal pure returns (int256) {
            // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
            if (value > uint256(type(int256).max)) {
                revert SafeCastOverflowedUintToInt(value);
            }
            return int256(value);
        }
    
        /**
         * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
         */
        function toUint(bool b) internal pure returns (uint256 u) {
            assembly ("memory-safe") {
                u := iszero(iszero(b))
            }
        }
    }
    
  • src/lib/MangroveVaultErrors.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    /**
     * @title MangroveVaultErrors
     * @notice A library containing custom error definitions for the MangroveVault contract
     * @dev This library defines various error types that can be thrown in the MangroveVault contract
     */
    library MangroveVaultErrors {
      /**
       * @notice Thrown when a zero address is provided where a non-zero address is required
       * @dev This can occur in various functions in MangroveVault.sol where addresses are expected
       */
      error ZeroAddress();
    
      /**
       * @notice Thrown when attempting to perform an operation with a zero amount
       * @dev This can occur in mint and burn functions in MangroveVault.sol when the amount is zero
       */
      error ZeroAmount();
    
      /**
       * @notice Thrown when there's a mismatch between expected and actual initial mint shares
       * @dev This occurs in the mint function in MangroveVault.sol during the initial mint
       * @param expected The expected number of shares
       * @param actual The actual number of shares
       */
      error InitialMintSharesMismatch(uint256 expected, uint256 actual);
    
      /**
       * @notice Thrown when the oracle returns an invalid (negative) price
       * @dev This occurs in the getPrice function in ChainlinkConsumer.sol
       */
      error OracleInvalidPrice();
    
      /**
       * @notice Thrown when attempting to withdraw an unauthorized token
       * @dev This can occur in withdrawal functions in MangroveVault.sol
       * @param unauthorizedToken The address of the unauthorized token
       */
      error CannotWithdrawToken(address unauthorizedToken);
    
      /**
       * @notice Thrown when a fee exceeds the maximum allowed
       * @dev This can occur when setting fees in MangroveVault.sol
       * @param maxAllowed The maximum allowed fee
       * @param attempted The attempted fee
       */
      error MaxFeeExceeded(uint256 maxAllowed, uint256 attempted);
    
      /**
       * @notice Thrown when a quote amount calculation results in an overflow
       * @dev This can occur in various calculations involving quote amounts in MangroveVault.sol
       */
      error QuoteAmountOverflow();
    
      /**
       * @notice Thrown when a deposit would exceed the maximum total allowed
       * @dev This occurs in the mint function in MangroveVault.sol
       * @param currentTotal The current total in quote
       * @param nextTotal The next total in quote after the deposit
       * @param maxTotal The maximum allowed total in quote
       */
      error DepositExceedsMaxTotal(uint256 currentTotal, uint256 nextTotal, uint256 maxTotal);
    
      /**
       * @notice Thrown when an unauthorized contract attempts to perform a swap
       * @dev This occurs in swap-related functions in MangroveVault.sol
       * @param target The address of the unauthorized swap contract
       */
      error UnauthorizedSwapContract(address target);
    
      /**
       * @notice Thrown when slippage exceeds the allowed amount in a transaction
       * @dev This can occur in mint, burn, and swap functions in MangroveVault.sol
       * @param expected The expected amount
       * @param received The actual received amount
       */
      error SlippageExceeded(uint256 expected, uint256 received);
    
      /**
       * @notice Thrown when a native transfer fails
       * @dev This can occur in the withdrawNative function in MangroveVault.sol
       */
      error NativeTransferFailed();
    
      /**
       * @notice Thrown when an unauthorized account attempts to perform an owner/manager-only action
       * @dev This error is used to restrict access to functions that should only be callable by the owner of the manager
       * @param account The address of the unauthorized account that attempted the action
       */
      error ManagerOwnerUnauthorized(address account);
    
      /**
       * @notice Thrown when the maximum price spread is invalid
       * @dev This can occur when setting the maximum price spread in MangroveVault.sol
       * @param maxPriceSpread The invalid maximum price spread
       */
      error InvalidMaxPriceSpread(uint256 maxPriceSpread);
    }
    
  • src/oracles/IOracle.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    import {Tick} from "@mgv/lib/core/TickLib.sol";
    import {OLKey} from "@mgv/src/core/MgvLib.sol";
    
    /**
     * @title IOracle
     * @notice Interface for oracle contracts that provide price information in the form of a tick
     */
    interface IOracle {
      /**
       * @notice Retrieves the current price tick from the oracle
       * @return Tick The current price tick
       * @dev The tick represents the price in a logarithmic scale, as used in Mangrove's order book
       */
      function tick() external view returns (Tick);
    }
    
  • src/vendor/ERC4626/ERC4626Consumer.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
    import {TickLib, Tick} from "@mgv/lib/core/TickLib.sol";
    
    /**
     * @title ERC4626Consumer
     * @notice Library for interacting with ERC4626 vaults to get price information in Mangrove tick format
     */
    library ERC4626Consumer {
      /**
       * @notice Gets the current price tick for an ERC4626 vault
       * @dev Calculates the tick based on the ratio of assets to shares using convertToAssets
       * @param vault The ERC4626 vault to get the price for
       * @param conversion_sample The amount of shares to use as a sample for price conversion
       * @return The price tick representing assets per share
       */
      function getTick(IERC4626 vault, uint256 conversion_sample) internal view returns (int256) {
        if (address(vault) == address(0)) return 0;
        uint256 assets = vault.convertToAssets(conversion_sample);
        return Tick.unwrap(TickLib.tickFromVolumes(assets, conversion_sample));
      }
    }
    
  • src/vendor/chainlink/AggregatorV3Interface.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    
    interface AggregatorV3Interface {
      function decimals() external view returns (uint8);
    
      function description() external view returns (string memory);
    
      function version() external view returns (uint256);
    
      function getRoundData(uint80 _roundId)
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
    
      function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
    }
    
  • src/vendor/chainlink/ChainlinkConsumer.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    import {AggregatorV3Interface} from "./AggregatorV3Interface.sol";
    import {MangroveVaultErrors} from "../../lib/MangroveVaultErrors.sol";
    import {TickLib, Tick} from "@mgv/lib/core/TickLib.sol";
    
    /**
     * @title ChainlinkConsumer
     * @notice A library for interacting with Chainlink price feeds
     */
    library ChainlinkConsumer {
      /**
       * @notice Get the latest price from a Chainlink price feed
       * @param _aggregator The Chainlink price feed aggregator
       * @return The latest price as a uint256
       * @dev If the aggregator address is zero, it returns 1 as a default value
       * @dev Reverts if the price is negative
       * @dev Notes on safety:
       * * Staleness is not checked because it's assumed that Chainlink will keep an up to date price feed
       * * Arbitrum outages and sequenced down on L2s are not checked because expected to not happen.
       * * In case this the above expected events happen, users should withdraw their shares and trusted managers should remove fees and keep the MangroveVault unpaused.
       */
      function getPrice(AggregatorV3Interface _aggregator) internal view returns (uint256) {
        if (address(_aggregator) == address(0)) return 1;
        (, int256 price,,,) = _aggregator.latestRoundData();
        if (price < 0) revert MangroveVaultErrors.OracleInvalidPrice();
        return uint256(price);
      }
    
      /**
       * @notice Calculate the tick value based on the price from Chainlink
       * @param _aggregator The Chainlink price feed aggregator
       * @param priceDecimals The number of decimals in the price feed
       * @param baseDecimals The number of decimals in the base token
       * @param quoteDecimals The number of decimals in the quote token
       * @return The calculated tick value as an int256
       * @dev Returns 0 if the aggregator address is zero (price is 1)
       */
      function getTick(
        AggregatorV3Interface _aggregator,
        uint256 priceDecimals,
        uint256 baseDecimals,
        uint256 quoteDecimals
      ) internal view returns (int256) {
        if (address(_aggregator) == address(0)) return 0;
        uint256 price = getPrice(_aggregator);
        if (baseDecimals > quoteDecimals) {
          return Tick.unwrap(TickLib.tickFromVolumes(price, 10 ** (baseDecimals - quoteDecimals) * 10 ** priceDecimals));
        } else {
          return Tick.unwrap(TickLib.tickFromVolumes(price * 10 ** (quoteDecimals - baseDecimals), 10 ** priceDecimals));
        }
      }
    
      /**
       * @notice Get the number of decimals for a Chainlink price feed
       * @param _aggregator The Chainlink price feed aggregator
       * @return decimals The number of decimals used in the price feed
       * @dev Returns 0 if the aggregator address is zero
       */
      function getDecimals(AggregatorV3Interface _aggregator) internal view returns (uint256 decimals) {
        if (address(_aggregator) != address(0)) decimals = _aggregator.decimals();
      }
    }
    
ABI · 23 entries
json
[
  {
    "type": "constructor",
    "inputs": [
      {
        "name": "_baseFeed1",
        "type": "tuple",
        "components": [
          {
            "name": "feed",
            "type": "address",
            "internalType": "address"
          },
          {
            "name": "baseDecimals",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "quoteDecimals",
            "type": "uint256",
            "internalType": "uint256"
          }
        ],
        "internalType": "struct ChainlinkFeed"
      },
      {
        "name": "_baseFeed2",
        "type": "tuple",
        "components": [
          {
            "name": "feed",
            "type": "address",
            "internalType": "address"
          },
          {
            "name": "baseDecimals",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "quoteDecimals",
            "type": "uint256",
            "internalType": "uint256"
          }
        ],
        "internalType": "struct ChainlinkFeed"
      },
      {
        "name": "_quoteFeed1",
        "type": "tuple",
        "components": [
          {
            "name": "feed",
            "type": "address",
            "internalType": "address"
          },
          {
            "name": "baseDecimals",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "quoteDecimals",
            "type": "uint256",
            "internalType": "uint256"
          }
        ],
        "internalType": "struct ChainlinkFeed"
      },
      {
        "name": "_quoteFeed2",
        "type": "tuple",
        "components": [
          {
            "name": "feed",
            "type": "address",
            "internalType": "address"
          },
          {
            "name": "baseDecimals",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "quoteDecimals",
            "type": "uint256",
            "internalType": "uint256"
          }
        ],
        "internalType": "struct ChainlinkFeed"
      },
      {
        "name": "_baseVault",
        "type": "tuple",
        "components": [
          {
            "name": "vault",
            "type": "address",
            "internalType": "address"
          },
          {
            "name": "conversionSample",
            "type": "uint256",
            "internalType": "uint256"
          }
        ],
        "internalType": "struct ERC4626Feed"
      },
      {
        "name": "_quoteVault",
        "type": "tuple",
        "components": [
          {
            "name": "vault",
            "type": "address",
            "internalType": "address"
          },
          {
            "name": "conversionSample",
            "type": "uint256",
            "internalType": "uint256"
          }
        ],
        "internalType": "struct ERC4626Feed"
      }
    ],
    "stateMutability": "nonpayable"
  },
  {
    "name": "OracleInvalidPrice",
    "type": "error",
    "inputs": []
  },
  {
    "name": "baseFeed1",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "address",
        "internalType": "contract AggregatorV3Interface"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "baseFeed1BaseDecimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "baseFeed1Decimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "baseFeed1QuoteDecimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "baseFeed2",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "address",
        "internalType": "contract AggregatorV3Interface"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "baseFeed2BaseDecimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "baseFeed2Decimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "baseFeed2QuoteDecimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "baseVault",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "address",
        "internalType": "contract IERC4626"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "baseVaultConversionSample",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "quoteFeed1",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "address",
        "internalType": "contract AggregatorV3Interface"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "quoteFeed1BaseDecimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "quoteFeed1Decimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "quoteFeed1QuoteDecimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "quoteFeed2",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "address",
        "internalType": "contract AggregatorV3Interface"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "quoteFeed2BaseDecimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "quoteFeed2Decimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "quoteFeed2QuoteDecimals",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "quoteVault",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "address",
        "internalType": "contract IERC4626"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "quoteVaultConversionSample",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "tick",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "int256",
        "internalType": "Tick"
      }
    ],
    "stateMutability": "view"
  }
]