LiquidityManager

Git Source

Inherits: ILiquidityManager, Ownable

Author: Scale Labs Ltd.

Fully automated luxury smart contract managing protocol encapsulated liquidity.

A high-powered mutant of some kind never even considered for mass production. Too weird to live, and too rare to die.

State Variables

ENS_NAME

'ENS_NAME' is a public constant storing the project's ENS domain, enhancing user experience by providing a readable alternative to the hexadecimal contract address. "liquidity" highlights the focus on smooth asset exchange, and "hbhart" abbreviates Half Baked Heroes Art, emphasizing the collection's artistic narrative.

string public constant ENS_NAME = "liquidity.hbhart.eth";

uniswapV2LiquidityPool

Holds the address for Uniswap V2 Mementos/WETH liquidity pool.

address public uniswapV2LiquidityPool;

uniswapV3LiquidityPoolWEth

Holds the address for Uniswap V3 Mementos/WETH liquidity pool.

address public uniswapV3LiquidityPoolWEth;

uniswapV3LiquidityPoolRocketPoolEth

Holds the address for Uniswap V3 Mementos/RETH liquidity pool.

address public uniswapV3LiquidityPoolRocketPoolEth;

_lastPositionCheck

uint256 private _lastPositionCheck;

positionsMoteWEth

The reservoir of positions where Mementos tokens paired with WETH are cultivated within the liquidity pool.

This fixed-size array stores identifiers for active liquidity positions in the Uniswap V3 WETH pool. Each position represents a commitment of resources, fostering a stable and fertile ground for transactions involving Mementos and WETH tokens. The positionsMoteWEth array is instrumental in managing the landscape of liquidity, allowing the harvestAndRecycleFees function to reap the transaction fees generated by these positions and allocateToResilience to refresh and enhance them periodically. It is a public array, granting transparency and allowing anyone to observe the stronghold of liquidity positions held within the Half Baked Heroes realm. The size of this array is determined by the POSITIONS limit, reflecting the designed capacity of the system to maintain a diverse yet manageable consortium of liquidity positions. It encapsulates the guardianship of resources, aligning with the vision of a fortified and thriving Web3 ecosystem promoted by the Half Baked Heroes narrative.

uint256[POSITIONS] public positionsMoteWEth;

positionsMoteRocketPoolEth

Repository for Mementos tokens paired with Rocket Pool staked ETH within the liquidity gardens.

This array maintains the indexes of liquidity positions where Mementos tokens are harmonized with Rocket Pool ETH in a Uniswap V3 pool. It is a vital component in the liquidity ecosystem, ensuring the flow and availability of these tokens for community cultivation. The positionsMoteRocketPoolEth array aids in the orchestration of the liquidity pool's dynamics, facilitating the collection of transaction fees through harvestAndRecycleFees and the strategic reinforcement of positions via allocateToResilience. It is set to public visibility, offering an open ledger of the liquidity positions upheld in the network, showcasing the commitment to a resilient and robust infrastructure. The size of this array is determined by the POSITIONS limit, reflecting the designed capacity of the system to maintain a diverse yet manageable consortium of liquidity positions. It encapsulates the guardianship of resources, aligning with the vision of a fortified and thriving Web3 ecosystem promoted by the Half Baked Heroes narrative.

uint256[POSITIONS] public positionsMoteRocketPoolEth;

positionsMoteWEthLength

uint256 public positionsMoteWEthLength = POSITIONS;

positionsMoteRocketPoolEthLength

uint256 public positionsMoteRocketPoolEthLength = POSITIONS;

positionMoteWEthFloor

uint256 public positionMoteWEthFloor;

positionMoteRocketPoolEthFloor

uint256 public positionMoteRocketPoolEthFloor;

nextConsolidation

Marks the epoch for the next unification of efforts within the Web3 odyssey.

This variable sets the threshold for the next 'Consolidation Event' in the context of liquidity management. It is initialized to the maximum value a uint256 can hold, effectively setting the initial state to 'distant future', signifying that the event is not immediately impending. The 'Consolidation Event' is a conceptual metaphor drawn from the Half Baked Heroes narrative, representing a pivotal moment when the community's collective endeavors are synchronized to reinforce the infrastructure of the Web3 journey. It realigns liquidity positions enhancing the harmony and efficiency of the system. When the nextConsolidation is set to a block timestamp, it acts as a beacon, signaling the approach of a strategic inflection point where the collective resources are marshaled to fortify the pathway through the 'blockchain maze'. This underscores the community's preparedness for the continuous evolution of the Web3 landscape.

uint256 public nextConsolidation = type(uint256).max;

nextInjection

Sets the timestamp for the next strategic empowerment of the network's resilience.

nextInjection serves as a timestamp indicating when the next strategic contribution to the network's liquidity will occur. Initialized to the maximum value for a uint256, it metaphorically represents an uncharted future point in the Web3 expedition, akin to a distant milestone awaiting arrival in the Half Baked Heroes narrative. In the lore of Half Baked Heroes, an 'Injection' is likened to a surge of communal energy or a bolstering of the infrastructure that sustains the community's progress through the digital labyrinth of Web3. Practically, this variable will be updated to reflect the block timestamp after a successful liquidity injection, symbolizing the periodic reinforcement of the ecosystem's foundational liquidity pools, which are crucial for the seamless exchange of the Mementos reflective of the community's journey. This variable plays a crucial role in pacing the financial fortifications in a controlled manner, preventing premature or too frequent modifications that could disrupt the delicate balance of the Web3 environment that Half Baked Heroes traverse.

uint256 public nextInjection = type(uint256).max;

_rethTicks

int24[TICKS] private _rethTicks;

_wethTicks

int24[TICKS] private _wethTicks = [
    -108600,
    -110000,
    -115600,
    -116800,
    -120400,
    -121600,
    -125200,
    -126600,
    -130000,
    -131400,
    -134800,
    -136200,
    -139600,
    -141000,
    -144400,
    -145800,
    -149200,
    -150600,
    -154000,
    -155400,
    -158800,
    -160200,
    -163600,
    -165000,
    -168400,
    -169800,
    -173200,
    -174600,
    -178000,
    -179400,
    -182800,
    -184200,
    -187600,
    -189000,
    -192600,
    -193800,
    -197400,
    -198600,
    -202200,
    -203400,
    -207000,
    -208400,
    -211800,
    -213200,
    -216600,
    -218000,
    -221400,
    -222800,
    -226200,
    -227600,
    -231000,
    -232400,
    -235800,
    -237200,
    -240600,
    -242000,
    -245600,
    -246800,
    -250200,
    -251600,
    -255400,
    -256600,
    -259000,
    -260800
];

Functions

onlyHBHContract

onlyHBHContract() restricts function execution to the Half Baked Heroes primary contract.

Modifier ensures only the designated HBH main contract can call the guarded function, maintaining secure contract-to-contract communication.

modifier onlyHBHContract();

constructor

constructor() payable;

initializePools

Constructs the liquidity pools on Uniswap V2 and V3. Invoked by the mighty constructor of the HBH, engages the ancient ritual of 'initializePools' to awaken the streams of commerce. This incantation establishes the sacred Uniswap V2 and V3 pools, ordaining the ticks and bands with cryptic accuracy, creating a haven for our heroes to conduct their transcendent trades.

*This function sets up the initial state for trading on Uniswap by creating liquidity pools. It uses both Uniswap V2 and V3 factories to create two types of pools: one for MOTE/WETH pairs, and another for MOTE/RETH pairs. The created pools are then stored in the contract's state. The process involves:

  • Creating a V2 liquidity pool for MOTE/WETH using the Uniswap V2 factory.
  • Creating a V3 liquidity pool for MOTE/WETH, initializing it with a specified price range.
  • Calculating the price of RETH relative to WETH from an existing Uniswap V3 pool.
  • Creating a V3 liquidity pool for MOTE/RETH, with tick ranges adjusted for the relative price. Each liquidity pool's address is then assigned to a public variable for later use in liquidity management.*
function initializePools() external payable onlyHBHContract;

activateTradeWinds

Harnesses the received Ether and injects it into the pre-ordained bands.

The 'ActivateTradeWinds' function is the key that unlocks the bustling bazaar of our digital realm. Once the HBH contract lays its foundation, this essential mechanism springs into action. It injects Ethereum into the newly crafted liquidity bands, setting the stage for a vibrant exchange. By converting a portion of Ethereum into Rocket Pool's staked variant, it ensures that our liquidity is as dynamic and robust as the heroes it supports. Completing its mission, 'ActivateTradeWinds' then transfers the mantle of control, decentralizing its power by revoking it's own ownership. The gates are now open, inviting traders to embark on their epic journey.

function activateTradeWinds() external payable onlyHBHContract;

_setUpLiquidity

function _setUpLiquidity(uint256 totalAmountWEth) private;

_setUpUniswapV3

Establishes liquidity positions in the DeFi ecosystem to enhance protocol resilience and ensure steady yield generation through strategic WETH and RETH deployment.

Sets up Uniswap V3 positions using WETH and Rocket Pool Staked ETH, converting a portion of WETH to RETH for both diversified exposure.

function _setUpUniswapV3(uint256 totalAmountWEth) private;

Parameters

NameTypeDescription
totalAmountWEthuint256The total amount of WETH designated for liquidity positions.

_setUpPositions

function _setUpPositions(
    address pairToken,
    uint256 amountPair,
    uint256 totalAmountToken,
    int24[TICKS] storage ticks,
    address pool,
    uint256[POSITIONS] storage positions,
    int24 floorTick
) private returns (uint256 positionsFloor);

onERC721Received

function onERC721Received(address operator, address, uint256, bytes calldata) external pure returns (bytes4);

harvestAndRecycleFees

Collects trading fees and reinjects to the ecosystem.

The 'harvestAndRecycleFees' is the automated custodian of the marketplace, collecting fees, burning surplus tokens to sustain market health, and converting the rest into liquidity. It ensures a continuous, self-sustaining loop that empowers the Liquidity Manager to maintain a robust environment.

function harvestAndRecycleFees() external payable;

allocateToResilience

Allocates unused liquidity to reinforce market bands.

The 'allocateToResilience' function acts as a market sentinel, wisely allocating dormant liquidity into designated bands to fortify their structure. With a cadence that allows activation only once every three days, it serves as an architect, reinforcing the market’s framework and upholding a robust economic environment for the community.

function allocateToResilience() external returns (bool result);

_getIndexForPrice

function _getIndexForPrice(uint160 sqrtRatio, int24[TICKS] storage ticks) private view returns (uint256 index);

_injectLiquidity

Strategically enhances liquidity positions in response to market conditions, reinforcing financial battlements and fortifying asset ramparts within the DeFi landscape.

Injects liquidity into a specified Uniswap V3 pool, considering current and TWAP prices to determine the optimal liquidity distribution across different price bands.

function _injectLiquidity(
    IUniswapV3Pool pool,
    address pairToken,
    int24[TICKS] storage ticks,
    uint256[POSITIONS] storage positions,
    uint256 length
) private returns (bool);

Parameters

NameTypeDescription
poolIUniswapV3PoolThe Uniswap V3 pool into which liquidity is to be injected.
pairTokenaddressThe ERC20 token used in pair with the pool's native token.
ticksint24[TICKS]Array of tick ranges for liquidity provision.
positionsuint256[POSITIONS]Array storing the pool's liquidity positions.
lengthuint256The number of active ticks/positions for consideration.

Returns

NameTypeDescription
<none>boolA boolean indicating if the liquidity was successfully injected.

_increaseLiquidity

Augments the liquidity of a given position, bolstering our defenses in the liquidity battlefield.

Increases the liquidity of a specific token position within a Uniswap V3 pool.

function _increaseLiquidity(uint256 tokenId, uint256 amount) private;

Parameters

NameTypeDescription
tokenIduint256The unique identifier for the liquidity position within the pool.
amountuint256The amount of liquidity to add to the position.

streamlineReserves

Recovers and reallocates funds from out-of-reach bands.

The 'streamlineReserves' function prudently audits the liquidity landscape, identifying and retracting resources from bands now beyond market reach due to token burns and rising liquidity levels. Recovered funds are then returned to the Liquidity Manager for strategic redeployment. This function operates on an independent three-day cycle, ensuring its actions are both timely and impactful.

function streamlineReserves() external returns (bool changed);

_consolidateLiquidity

Consolidates liquidity by removing the last position's liquidity band and burning excess tokens. This mirrors a hero's strategy to fine-tune their resources, enhancing their agility in the Web3 maze.

"_consolidateLiquidity" is the alchemic process where our Half Baked Heroes refine their essence, sharpen their focus, and prepare for deeper forays into the labyrinth of Web3. It's a ritual of shedding the non-essential symbolizing renewal and the cycle of growth and decay. This act is not of destruction but of purification, preparing for the new creations that will rise from the old, much like a phoenix from ashes.

For a given array of position IDs and a length indicator, this function identifies the position at the specified length, retrieves its liquidity details, and then reduces the liquidity for that position. Any collected MOTE are then burned to optimize the token balance. The return value from 'positions' is ignored to streamline execution. This function is private and can only be called internally.

This function acts as a custodian of liquidity, strategically withdrawing from the last position to enhance future manoeuvrability. It symbolizes a decisive moment where choices must be made to either carry on with the gathered resources or to let go, allowing the hero to move unburdened. The function pulls the details of the specified liquidity position, casts away the excess by calling "_removeBand", and purges the remnants through "_burnExcessTokens".

function _consolidateLiquidity(uint256[POSITIONS] storage positions, uint256 length) private;

Parameters

NameTypeDescription
positionsuint256[POSITIONS]The array of liquidity positions managed by the contract.
lengthuint256The index in the 'positions' array that indicates which position's liquidity to consolidate.

_burnExcessTokens

This incinerates any mementos that linger unnecessarily within the contract's coffers.

This function is a meticulous spell that eradicates any excess mementos held by the contract. This symbolic conflagration ensures the economic environment remains balanced and uncluttered, echoing the theme of transformation and rebirth.

function _burnExcessTokens() private;

_collectPosition

function _collectPosition(uint256 positionId) private returns (uint256 amount1);

_removeBand

function _removeBand(uint256 positionId, uint128 liquidity) private;

prospectNadir

Detects the most dormant liquidity band in pools.

The 'prospectNadir' function scouts the liquidity landscape of Ether and Rocket Pool, unearthing bands that are no longer strategically necessary due to the evolved market dynamics. It hones in on the most dormant bands, identifying the one with the greatest potential for liquidity reallocation.

function prospectNadir() public view returns (address poolWithRemovablePosition);

_getPositionsTokens

function _getPositionsTokens(uint256 currentPrice, uint256[POSITIONS] storage positions, uint256 length)
    private
    view
    returns (uint256 poolTokens, uint256 absorbableTokens);

getAmount0ForLiquidity

Computes the amount of token0 for a given amount of liquidity and a price range

function getAmount0ForLiquidity(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity)
    private
    pure
    returns (uint256 amount0);

Parameters

NameTypeDescription
sqrtRatioAX96uint160A sqrt price representing the first tick boundary
sqrtRatioBX96uint160A sqrt price representing the second tick boundary
liquidityuint128The liquidity being valued

Returns

NameTypeDescription
amount0uint256The amount of token0

receive

receive() external payable;

_getTokenRethPriceFromTick

rETH price Calculation. Calculates the ETH price of Rocket Pool's staked ETH (rETH) based on Uniswap V3 price tick.

This private view function converts the Uniswap V3 price tick into a token price. It should only be called internally within the contract as part of liquidity management or pricing mechanisms.

function _getTokenRethPriceFromTick(int24 tick) private view returns (uint256 tokenPriceV3Reth);

Parameters

NameTypeDescription
tickint24The price tick from Uniswap V3 to be converted into the token's price.

Returns

NameTypeDescription
tokenPriceV3Rethuint256The calculated price of the token in terms of rETH.

_getTokenRethPrice

Token price in rETH price retrieved from the Uniswap pool directly

function _getTokenRethPrice() private view returns (uint256 tokenPriceV3Reth);

Returns

NameTypeDescription
tokenPriceV3Rethuint256The Uniswap V3 price of the token in Reth

_getTokenRethPrice

function _getTokenRethPrice(uint256 tokenPriceV3Reth) private view returns (uint256 tokenPrice);

replenishRewards

Balances miner rewards by arbitraging across three pools.

The 'replenishRewards' function taps into the triumvirate of pools, each a cornerstone in the miner's reward system. It harmonizes the bounty from this triad, utilizing arbitrage to equilibrate rewards. Like the points of a triquetra, it binds the essence of balance, ensuring a smooth flow of recognition through the veins of the mining community.

function replenishRewards(address sender) external payable onlyHBHContract returns (uint256 output);

addToLiquidty

Invokes the alchemy of liquidity by accepting Ether from the hallowed HBHART contract and transmuting it into our realm's token through the liquidity pools. The mystical process determines the most favorable cauldron of creation between V2 and V3 pools by conjuring the current token prices from the depths of each. A portion of the Ether may be alchemized into rETH as an offering to the spirits of liquidity, enhancing the pool's power. The act of liquidity creation is a sacred rite, and thus this function can only be called by the HBHART Contract, the keeper of our heroes' essence. It returns the bounty of tokens received from the liquidity ritual.

function addToLiquidty(address sender) external payable onlyHBHContract returns (uint256 output);

Parameters

NameTypeDescription
senderaddressThe noble provider of Ether, who shall receive the tokens from the liquidity ritual.

Returns

NameTypeDescription
outputuint256The amount of tokens conjured from the Ether provided.

_selectPool

function _selectPool() private view returns (uint256 tokenPrice, uint16 poolVersion);

_checkIsHeroesContract

Ensures that the calling entity is the esteemed HBHART contract, the sanctum of our heroes. It is a safeguard that permits only the HBHART, the creator of legends, to initiate the sacred call. Any impostor invoking this ritual without being the HBHART shall be denied with the decree "Not HBH".

function _checkIsHeroesContract() private view;

Events

DeployingMoreCapitalSteadyLads

event DeployingMoreCapitalSteadyLads(address indexed pool, uint256 nearBand, uint256 farBand, uint256 supportBand);