Half Baked Heroes Art Experience Half Baked Heroes Art Experience

Delve into the vivid universe of Half Baked Heroes, a dual NFT collection where the boundaries between digital art, provenance, programming, and the act of mining meld into an interactive artistic experience. The mining process itself is a choreographed dance between blockchain technology and imaginative expression. When you mine a hero; you're not just acquiring art, you're engaging in the combined artistic event of design and code.

Each transfer of a Hero weaves a new thread into the intricate tapestry of its accompanying certificate, vividly chronicling the Hero's journey through a chain of custody in the art world. This tapestry not only traces the lineage of ownership but also resolves onchain and renders the ENS names for associated addresses, seamlessly blending the Hero's odyssey with the dynamic, evolving story of its guardians in the Web3 realm. You as an owner become part of the artwork of the Certificate of Authenticity and the lore of the Hero.

This is a celebration of art, code, and the vibrant community they birth.

Contributors

A David Gokhshtein (@davidgokhshtein) production. A Half Baked Heroes (@hbh_nft) art experience. Illustrated by Daniel Sulzberg (@Danvillageart). Contracts developed by Scale Labs (@scale_labs). Audited by Nethermind Security (@NethermindEth).


David GokhshteinDan Village ArtScale LabsNethermind Security
David GokhshteinDan Village ArtScale LabsNethermind SecurityNethermind Security

Overview

'Half Baked Heroes' is a creative art experience that celebrates the personalities and journeys of the Web3 community.

While 22 smart contracts comprise the experience, it mainly presents via two ERC721 NTF contracts, and one ERC20 reward token. For the ERC20 token the protocol handles the liquidity for at least 25% of the supply. It does this passively via a Uniswap v2 pool where all the LP tokens are burnt; or actively via two Uniswap v3 pools where the liquidity is permanently locked in a revoked smart contract for complete decentralization.

The ERC20 token associated with this project exemplifies the principles of fairness and decentralization in its launch and distribution. Its allocation to miners ensures that the distribution process is equitable and transparent.

For full fairness, there are no allocations for insiders or team members, nor are there any private sales, pre-sales, or scheduled vesting unlocks that could potentially skew the equitable distribution. This approach fosters a level playing field for all participants.

In a definitive move towards complete decentralization, the ownership of the ERC20 token and its liquidity management is irrevocably renounced at the onset of trading. This act ensures that the token operates in a fully decentralized environment, with no central authority or figure exerting influence or control over its trajectory. This bold step solidifies the token's position as a truly community-driven, aligning perfectly with the ethos of the DeFi (decentralized finance) space.

The ERC20 token "Mementos" (MOTE) are tokenized mementos issued in association with the Half Baked Heroes NFT art experience and are purely commemorative and do not represent shares, equity, or any form of investment in any entity or venture.

They do not confer any rights of ownership, dividends, profit-sharing, or any other financial entitlement. These tokens are solely a mark of participation in the NFT mining experience and should not be construed or treated as a financial instrument; investment contract or a security.

Artifacts

  • HBH Logo HalfBakedHeroes
    • 15,000 Premium Art ERC721 NFTs.
    • Metadata on-chain — delivered via an IRenderer contract.
    • Art off-chain — delivered via IPFS.
    • Unrevealed at mining, only revealed at mining complete.
    • ENS named forward and reverse — hbhart.eth.
  • Cert Logo CertificateOfAuthenticity
    • 15,000 Onchain record of custody ERC721 NFTs.
    • Metadata on-chain — delivered via an IRenderer contract.
    • Art on-chain — delivered via an IRenderer contract.
    • Revealed at mining.
    • Handles routing of fees (royalties, swap).
    • ENS named forward and reverse — certificate.hbhart.eth.
  • MOTE Logo Mementos(MOTE)
    • 2.718 Tn (e*10^12) Mementos (MOTE) ERC20 Tokens at 18 decimals.
    • Simple token - 0% buy, 0% sell fees.
    • 68% available for mining, 32% in liquidity pools.
    • Method to covert any trapped tokens to Weth and send to LiquidityManager (below).
    • ENS named forward and reverse — mementos.hbhart.eth.
  • LiquidityManager
    • Protocol held and automatically managed liquidity:
    • Holds undeployed WETH (Wrapped Ether).
    • Holds undeployed RETH (Rocket Pool Staked ETH).
    • Holds and manages Uniswap v3 Position NFTs (MOTE/RETH+MOTE/WETH).
    • ENS named forward and reverse — liquidity.hbhart.eth.
While these tokens are transferable, their availability on secondary markets is beyond our control and purview. Participating in the mining does not guarantee any future value or returns on secondary markets.

FeaturesHalf Baked HeroCertificate of Authenticity
ERC-721 Token
ERC-721 Metadata
EIP‑721 Metadata Update
RevealOn mining completeImmediately
MetadataOn-ChainOn-Chain
Metadata RenderingDynamicDynamic
ImagesIPFSOn-Chain
Image RenderingImmutableGenerative

*On-chain means is stored or generated on the Ethereum blockchain directly.

FeaturesMementos (MOTE)
ERC-20 Token
Ownership renounced
Fully decentralized
Uniswap v2 Liquidity burnt
Uniswap v3 LiquidityHeld in renounced LiquidityManager
Uniswap v2 pairsMOTE/WETH
Uniswap v3 pairsMOTE/WETH, MOTE/RETH
Token buy fees0%
Token sell fees0%

Supply Tokenomics

FeaturesHalf Baked HeroCertificate of AuthenticityMementos (MOTE)
BlockchainEthereumEthereumEthereum
Supply issued at end of mining100%100%100%
Allocated to mining100%100%61.8%
Allocated to Uniswap0%0%38.2%
Reserved for "marketing"0%0%0%
Team allocations0%0%0%
Pre-allocations0%0%0%
VC private sale0%0%0%
Pre-sale0%0%0%
Whitelisting0%0%0%
Vesting0%0%0%
All tokens associated with this project will be 100% issued by the end of the NFT mining. There are no team, insider, pre-sale, private sale, or investor allocations.

Any tokens that remain unmined at the end of the NFT mint will be automatically burned. The unmined amount is fully determined by the miners and the amount they mine per transaction, ensuring full transparency and fairness in distribution.

HBH Logo HalfBakedHeroes (HalfBakedHeroes.sol)

The 'Half Baked Heroes' collection offers an innovative and interactive approach to NFT mining, celebrating the diverse personalities and stories within the Web3 community. This unique collection consists of 15,000 distinct characters, with each NFT portraying a character navigating the intricate maze of Web3's challenges and opportunities.

To mine an NFT from this collection, participants send ETH to the designated hbhart.eth address. The mining process is facilitated by the receive() function, which not only assigns the msg.sender a Half Baked Hero NFT with a semi-randomly assigned ID but also generates a sequential ID certificate specific to that Hero. In addition to these items, the process awards a quantity of Memento tokens.

Example Half Baked Hero
Example "The Dev" Half Baked Hero

Each Hero NFT is designed to be independently transferable from its corresponding certificate. This allows for flexible ownership and trading possibilities. The tokenURI metadata of each Hero NFT is dynamically generated on-chain by a specialized renderer. This renderer not only updates the metadata in real-time but also links to an image hosted on IPFS, ensuring a permanent, decentralized record of the artwork.

This innovative mining process not only ensures that each Half Baked Hero is a living part of the Web3 narrative but also enhances security significantly. Participants can mine an NFT without the need to connect their wallet to a website; instead, they simply send ETH to the designated address. This method minimizes potential security risks associated with wallet integration on websites, offering a safer and more streamlined approach to acquiring these unique digital assets.

FeaturesHalf Baked Hero
ERC-721 Token
ERC-721 Metadata
EIP‑721 Metadata Update
RevealOn mining complete
MetadataOn-Chain
Metadata RenderingDynamic
ImagesIPFS
Image RenderingImmutable

*On-chain means is stored or generated on the Ethereum blockchain directly.

Supply Tokenomics

FeaturesHalf Baked Hero
BlockchainEthereum
Supply issued at end of mining100%
Allocated to mining100%
Reserved for "marketing"0%
Team allocations0%
Pre-allocations0%
VC private sale0%
Pre-sale0%
Whitelisting0%
Vesting0%

The key feature of this contract is:

  • ERC721 NFT with all behaviours
flowchart TD
    W -->|Send fab:fa-ethereum ETH| C
    C -->| far:fa-clock not<br>started| R
    C -->| 15,000 HBH<br>already  mined| R
    C -->| < min ETH| R
    C --> | >= min ETH| M
    M --> |one| D
    M --> |one| E
    M --> |Based on ETH send| V
    V --> |mine reserves<br>formula| MP2(* Mining Pool)
    V --> |no reserves<br>market rate| LP2(* Liquidity Pool)
    W[fab:fa-ethereum Wallet]
    M{fas:fa-check-circle Mine}
    R(fas:fa-times-circle Revert)
    C{fas:fa-code hbhnft.eth}
    D["fas:fa-portrait Half Baked Heroes (HBH)"<br>ERC-721 NFT<br>Meta: OnChain<br>Image: IPFS<br>Reveal: Mining Complete]
        E["fa:fa-certificate HBH Certificate of Authenticity (CAHBH)"<br>ERC-721 NFT<br>Meta: OnChain<br>Image: OnChain<br>Reveal: Immediately]
    O[Mined Output -> Wallet]
    MP2 --> O
    LP2 --> O
    D --> O
    E --> O 
    V{"Mine Mementos (MOTE)<br>Amount: Based on tx send<br>No reserves -> market rate"}

Non-standard EOA callable non-view functions on this contract

  • constructor()
    1. Calls initializePools on LiquidityManager
    2. Calls addPools on Mementos
    3. Calls setName on Nameable
    4. Calls _setDefaultRoyalty to set the royalties bps and direct the royalties to CertificateOfAuthenticity
  • openMining() payable onlyOwner
    1. Sets lastMineBlock to current block
    2. Calls activateTradeWinds() on LiquidityManager passing all sent ETH
    3. Calls bonAppetit() on Mementos to renounce that contract
  • receive() payable
    1. Mining is done by directly sending ETH to this contract; avoiding risks from connecting wallet to a website and authorizing complex transactions it send to your wallet.
    2. If first call, initializes _lastSkillChoice to a default semi-random number
    3. Checks amount sent is not below minimum mine cost
    4. Checks amount set is not large than the bitlength we will store this into
    5. Calls _excavate()
  • reveal(address) onlyOwner
    • Updates the renderer contract; confirming it's code matches the provenance hash set before deployment. (To prove devs didn't change NFT decoding after minting)
    • emits BatchMetadataUpdate(uint256, uint256)
  • errorsAndOmissionsExcepted(address) onlyOwner
    • Updates the renderer contract; as escape hatch to correct any issues discovered after reveal; or set initial unrevealed renderer.
    • emits BatchMetadataUpdate(uint256, uint256)
  • feedDevs()
    • Pull payment method
  • cleanseThePalate()
    • Pull payment method
  • burnRemaining() onlyHeroes
    • Burns any remaining Mementos (MOTE) tokens in the contract only after mining is complete.

Notable private or internal functions on this contract

  • _excavate() private

    1. Check are still Heroes to mine
    2. Get a skill based random number
    3. Use a variant of Fisher–Yates shuffle to get random hero
    4. Get block gap since last mining event
    5. Allocate a portion to devs
    6. Mine and send a CertificateOfAuthenticity
    7. Store the current holding; whether G3Verse pass holder and block gap
    8. Allocate 4000 gwei * sqrt(ETH sent * 1 gwei) Memento tokens to miner
      • If enough tokens available in HalfBakedHeroes send directly
      • If not use 50% of the ETH sent to replenish the token supply from market via LiquidityManager function replenishRewards
    9. Use 20% of the ETH sent for an additional reward at the rate the market determines; capped at a maximum of the initial allocation, with the remaining staying in contract as additional reward replenishment.
    10. Mine and send a HalfBakedHero
    11. emit a HeroFullyCooked(heroId, certificateId, mementosCount) event
  • _afterTokenTransfer(address, address, uint256) internal

    • Refreshes Certificate metadata
    • If current receiver now holds the record on Heroes NFTs held, updates record against account to note this datetime and count; and stores as new top holder record.

Cert Logo CertificateOfAuthenticity (Certificate.sol)

The Certificate NFT accompanying each Half Baked Hero is a dynamic record that meticulously tracks and presents key statistics about the mined hero. This certificate offers a detailed provenance, chronicling the history of ownership over time. Additionally, it provides insightful metrics such as the amount of ETH used to mine the hero; which also determines the Hero's title, the exact mint date of the hero, and the 'block gap'—the number of blocks elapsed without mining activity prior to the hero's mining.

Example Half Baked Heroes' Certificate
Example Certificate rendered onchain with multiple previous owners

Uniquely, this Certificate NFT is transferable independently of the hero, enhancing its utility and significance. Its tokenURI, along with the certificate's image rendered in SVG format, is generated dynamically on-chain, ensuring that the metadata and visual representation are always current and accurately reflect the hero's ongoing journey and transaction history.

FeaturesCertificate of Authenticity
ERC-721 Token
ERC-721 Metadata
EIP‑721 Metadata Update
RevealImmediately
MetadataOn-Chain
Metadata RenderingDynamic
ImagesOn-Chain
Image RenderingGenerative

*On-chain means is stored or generated on the Ethereum blockchain directly.

Supply Tokenomics

FeaturesCertificate of Authenticity
BlockchainEthereum
Supply issued at end of mining100%
Allocated to mining100%
Reserved for "marketing"0%
Team allocations0%
Pre-allocations0%
VC private sale0%
Pre-sale0%
Whitelisting0%
Vesting0%

The key features of this contract are:

  • ERC721 NFT with all behaviors
  • Handles collection (storage) and routing of fees (royalties, swap)
  • Provides access to history of Hero transfers
  • Provides access to statistics about the amount of ETH that was sent during the initial mining, mint date and the block gap (how many non-mining blocks there were before the hero was minted).
  • Can be transferred independently of the HalfBakedHeroes NFT

Non-standard EOA external non-view functions on this contract

  • updateVibesDirection(address) onlyOwner
    • Changes where 50% of fees (vibes) are directed; to allow changes to a contract destination in future.
    • emits VibesUpdate(address)
  • distributeEth()
    • Sends 50% of ETH in contract to project multi-sig
    • Sends 50% of ETH in contract to LiquidityManger
  • distributeToken(address)
    • 100% of Mementos(MOTE) tokens in this contract are burnt
    • 100% of Rocket Pools Staked ETH (RETH) in this contract are sent to LiquidityManger
    • Other tokens are converted to WETH
      • Sends 50% of WETH in contract to project multi-sig
      • Sends 50% of WETH in contract to LiquidityManger
  • setRenderer(address) external onlyOwner
    • Updates the renderer contract
    • emits BatchMetadataUpdate(uint256, uint256)

Ecosystem only external methods on this contract (cross contract calls)

  • notarize(address, uint16, uint80) onlyHBHContract returns (uint16)
    • Issues Certificate NFT
    • Stores additional sent data
    • emits MetadataUpdate(uint256)
  • refreshMetadata(uint256) onlyHBHContract
    • Called after transfers of HBH to refresh the providence list
    • emits MetadataUpdate(uint256)

MOTE Logo Mementos (Mementos.sol)

This is a reward token given in a 4000 * sqrt(ETH mined * gwei) amount + up to x2 based on market rates. If the mining rewards are depleted from large mining amounts then they are bought at market rates.

FeaturesMementos (MOTE)
ERC-20 Token
Ownership renounced
Fully decentralized
Uniswap v2 Liquidity burnt
Uniswap v3 LiquidityHeld in renounced LiquidityManager
Uniswap v2 pairsMOTE/WETH
Uniswap v3 pairsMOTE/WETH, MOTE/RETH
Token buy fees0%
Token sell fees0%

Supply Tokenomics

FeaturesMementos (MOTE)
BlockchainEthereum
Supply issued at end of mining100%
Allocated to mining61.8%
Allocated to Uniswap38.2%
Reserved for "marketing"0%
Team allocations0%
Pre-allocations0%
VC private sale0%
Pre-sale0%
Whitelisting0%
Vesting0%

The key feature of this contract is:

  • ERC20 token with all behaviors

Non-standard EOA external non-view functions on this contract

  • sacrificeDonatedTokens(address) onlyHeroes returns (uint256)
    • Can only be called by a holder of a Half Baked Heroes NFT
    • Allows random tokens sent to the contract to be processed and used for liquidity rather than being trapped in the contract.
    • Gives a 10% reward to the caller, when the tokens aren't MOTE, RETH or WETH.
    • 100% of Mementos (MOTE) tokens are burnt
    • 100% of Rocket Pools Staked ETH (RETH) are sent to LiquidityManger
    • Other tokens are converted to WETH
      • Sends 10% of WETH in contract to the hero who executes it as reward
      • Sends remaining WETH in contract to LiquidityManager either converting to RETH first or as WETH if slippage too high.

Ecosystem only external methods on this contract (cross contract calls)

  • addPools(address[] calldata) onlyHBHContract
    • Called by HalfBakedHeroes from constructor() to add the created liquidity pools .
  • bonAppetit() onlyHBHContract
    • Called by HalfBakedHeroes from openMining() to renounce the ownership of this token contract.

Notable private or internal functions on this contract

  • _afterTokenTransfer(address, address, uint256) internal
    • If to or from is NOT one of the original liquidity pools or an ecosystem contract then it calls harvestAndRecycleFees() on LiquidityManager

LiquidityManager (LiquidityManager.sol)

This is a decentralised Uniswap v3 position manager; for liquidity of the Mementos token.

The key feature of this contract is:

  • Automated protocol managed token liquidity
flowchart TD
    T["fas:fa-coins Mementos (MOTE)"<br>ERC-20 Tokens<br>0% Transfer Fees 0,0]
    MP(* Mining Pool<br>61.8034% MOTE Supply)
    LP(* Liquidity Pools)
    LP2(* Liquidity v2 Pool<br>LP Tokens Burned)
    LP3Weth(* Liquidity Pool<br>Locked in Protocol)
    LP3Reth(* Liquidity Pool<br>Locked in Protocol)
    T --> |61.8034% MOTE Supply| MP
    T --> |38.1966% MOTE Supply| LP
    LP --> |Only at init<br>0.5 ETH| LP2
    LP --> LP3Weth
    LP --> LP3Reth
    MP -->|post-mine<br>unmined MOTE supply| B
    LP2 --> |LP Tokens| B
    LP3Weth --> |post mine<br>+3 day| F
    LP3Reth --> |post mine<br>+3 day| F
    F --> |Collected ETH| LP
    F --> |Collected MOTE| B
    F{Collect Position Fees<br>or Adjust Floor Position}
    B[Burn -> 0xdEaD]

Non-standard EOA callable non-view functions on this contract

  • allocateToResilience() returns (bool)
    1. Checks has been 3 days since last call, or trade start
    2. Sets next call time to be 3 days from now
    3. Calls _injectLiquidity for MOTE/WETH pool
    4. Calls _injectLiquidity for MOTE/RETH pool
  • streamlineReserves() returns (bool)
    1. Checks has been 3 days since last call, or trade start
    2. Sets next call time to be 3 days from now
    3. Find if any position can be removed by calling prospectNadir()
    4. Calls _consolidateLiquidity for the selected pool
    5. If was the last position in the start set, also calls _removeBand on the floor position for that pool

Notable public view only functions on this contract

  • prospectNadir() returns (address)

    Finds the liquidity pool with the most distant lower liquidity band and sees if it can be removed while maintaining the protocol's liquidity coverage for 25% of the token supply.

    1. Gets the MOTE/RETH price reverting if beyond an acceptable distance of the TWAP
    2. Gets the MOTE/WETH price reverting if beyond an acceptable distance of the TWAP
    3. Check how many tokens the MOTE/WETH pool can absorb
    4. Check how many tokens the MOTE/RETH pool can absorb
    5. Simulate a sale of remaining tokens from the 25% of outstanding supply to v2 pool and get a price.
    6. If v2 after price is higher than MOTE/WETH pool's lowest band it can be removed
    7. If both prices are higher than MOTE/RETH pool's lowest band it can be removed instead

Ecosystem only callable methods on this contract

  • initializePools() payable onlyHBHContract

    Called by the HalfBakedHeroes function constructor(); initializes the 3 liquidity pools.

    1. Creates Uniswap v2 pair (MOTE/WETH)
    2. Creates Uniswap v3 pair (MOTE/WETH)
    3. Initializes v3 pair pool (MOTE/WETH)
    4. Gets current RETH/WETH price
    5. Creates Uniswap v3 pair (MOTE/RETH)
    6. Recalibrates WETH pool ticks for RETH price
    7. Initializes v3 pair pool (MOTE/RETH)
  • activateTradeWinds() payable onlyHBHContract

    This function enables trading on the Mementos token by adding all the initial liquidity to the pools.

    1. Converts the sent ETH to WETH
    2. Calls _setUpLiquidity to set up the liquidity positions
    3. Sets nextConsolidation and nextInjection to be 3 days in the future
    4. Renounces ownership of this contract
  • addToLiquidity(address) payable onlyHBHContract returns (uint256)

    1. Checks is coming from HBH Contract
    2. Calls _selectPool() to choose v2 or v3 pool, exiting if neither
    3. Use 20% of ETH to covert to RETH if more favorable MOTE pool
    4. Use the ETH or RETH to buy MOTE to replenish the rewards pool
    5. Convert any remaining ETH to WETH
  • replenishRewards(address) payable onlyHBHContract returns (uint256)

    1. Checks is coming from HBH Contract
    2. Calls _selectPool() to choose v2 or v3 pool, exiting if neither
    3. Works out if the V2 or V3 WETH/MOTE price will get more tokens
    4. Works out if the RETH pool will give more tokens than the selected WETH pool
      • If RETH, swaps ETH to RETH
    5. Calls Liquidity replenishRewards specifying whether to use WETH or RETH and to return the MOTE to the sender parameter returning the amount of Mementos
  • harvestAndRecycleFees() payable

    1. Checks is Mementos token calling from _afterTokenTransfer
    2. Iterates a single band collecting any liquidity fees if available; switching between each pool for each invocation
      • Any fees in RETH are kept in the LiquidityManager (e.g. no action)
      • Any fees in WETH are sent to the CertificateOfAuthenticity for distribution
      • Any fees in Mementos token are burnt

Notable private or internal functions on this contract

  • _selectPool()

    1. Works out if the V2 or V3 WETH/MOTE price will get more tokens
    2. Returns the price and version of pool
  • _setUpLiquidity(uint256) private

    1. Adds liquidity to the Uniswap v2 position (0.5 WETH); burning the LP tokens.
    2. Calls _setUpUniswapV3(uint256) passing the count of remaining WETH
  • _setUpUniswapV3(uint256) private

    1. Splits the WETH by Golden ratio (1.618) with larger fraction (61.8%) being allocated to RETH pool.
    2. Converts the initial WETH for RETH into RETH
    3. Sets up the Uniswap v3 position bands by calling _setUpPositions for each v3 pool and stores the returned floor position
    4. Burns any unallocated Memento tokens
  • _setUpPositions

    Called twice. Once for MOTE/WETH and once for MOTE/RETH pool; minting

    1. Queries v3 pool for the initial price
    2. Mints 32 Uniswap v3 liquidity positions (64 including both pools)
      • at precalculated ticks _wethTicks or _rethTicks, approximately Fibonacci tick positions (1.618), with 0.382 retracement widths
      • linear distribution of tokens per band, except in the initial 8 where it is reduced so someone cannot scoop up a large amount of supply with a very small buy
      • inserts them in the position array backwards; in order of high price to low price; so when removing positions (starting at lows) the length of the array can be reduced by one rather than shuffling up.
    3. Add a full range (start price to infinity) band at index 0 so it isn't considered for removal and there is liquidity between the main 32 positions.
    4. Add a support floor band below price that just contains the WETH and no tokens; for mined token liquidity.

    32 (regular) + 1 (full range) + 1 (floor) = 34 liquidity positions are minted per invocation. This makes 68 uniswap positions across the two pools.

  • _consolidateLiquidity(uint256[POSITIONS],uint256) private

    1. get the liquidity amount in the position
    2. call _removeBand(uint256,uint128) with the liquidity to remove and Uniswap's positionId
    3. burn any Memento's token received in liquidity fees
  • _removeBand(uint256,uint128) private

    1. Decrease the liquidity in the position to 0
    2. Collect any fees or tokens from the position
    3. Burn the Uniswap v3 position
  • _getIndexForPrice(uint160,int24[TICKS]) private view returns (uint256)

    • Given the current price, searches the tick array to find the nearest position index to price (either price in, or next above).
  • _injectLiquidity(IUniswapV3Pool,address,int24[TICKS],uint256[POSITIONS],uint256) private returns (bool)

    1. If price is far away from TWAP, early exit
    2. Find the liquidity position index below price
    3. If not enough pair token to inject early exit
    4. Find how much pair liquidity in position band above
    5. Cap the amount of liquidity injected at 1% of balance or the pair liquidity in higher band, whichever is smaller
    6. Split the liquidity into 3 bands below price: Near, Far, Support
      • 20% goes to the Support band
      • If bearish price action (price below TWAP); 60% to Far band, 20% to Near band
      • If bullish price action (price above TWAP); 40% to Far band, 40% to Near band
    7. Call _increaseLiquidity on each of the positions with the designated amount
    8. Emits DeployingMoreCapitalSteadyLads(address,uint256,uint256,uint256)

Tokens

TitleEnsAddress
HalfBakedHeroes
ERC721
hbhart.eth0x069220F5F85aE9B82371a29f5F9c70E0cBdcBf69
Certificate
ERC721
cert.hbhart.eth0x069376a7d55C202Aa79565B25E167B97016D9168
Mementos (MOTE)
ERC20
mementos.hbhart.eth0x069f85562F20e3c8120CbC8880cf67976992eA83

Liquidity

TitleEns or PairAddress
LiquidityManagerliquidity.hbhart.eth0x069D89AE50Da299e3Caa5BD6e8a777C59fB9BEe8
Uniswap v2MOTE/WETH0x86Ba23Ef6B157212e8Fc2436763415512c732830
Uniswap v3MOTE/WETH0x0aC9016a5e11ED450ff238e08480DEB7828D8cd3
Uniswap v3MOTE/RETH0xA3d4480D41Dd3661696fFb5e4A1f75b83DB3893E

Renderers

TitleAddress
HalfBakedHeroes Prereveal0x069C3583dbD7f9eF0Ec009c3ae71ab873d7a5AAb
HalfBakedHeroes Postreveal0x069b690361Ae7Ca502b0D585CD7726F95e511B33
Certificate0x069f37B130a5dA522e6BF858026E6B0dF26af5Dc

Data

TitleAddress
Companion Renderer 10x069b1828e959Bc2a7a691e2768C3e16350BAA757
Companion Renderer 20x069D1CDe655CaCF02119000DED2ad3c800e36E88
Companion Renderer 30x069F3226D56A252bb809759BC7C2f8cd9ad9dE1E
Companion Renderer 40x069EF1c2fF3E5d92D03B0Cf18eB127e0F9FE3E8D
Companion Renderer 50x069b3d533ad17D8Ce7C33761bb960F13f676b01F
Companion Renderer 60x069FA283E51Efb711CBBa1652e6961101B8Aa37E
Companion Renderer 70x069df9CfaA7F6BBF551232c3728f6da332E7C808
Companion Renderer 80x0696de31B2239c7bb0eBf63fdf2Ad336c9dA3538
Companion Renderer 90x069681cC7C7a233aD00085ac807500DD18cf696e
Valhalla 00x06990CBcE3aef7cf389951cf02017A52918d8385
Valhalla 10x069029377E91b118fb176963A21aDab329215d63
Valhalla 20x06927a77AbB09088A6971ab3536f1Ae3621f21E2
Valhalla 30x0695117B8706b1f8891577b6EF3aCb6CF3703Dde

Deployer

TitleEnsAddress
HBHDeployerdeployer.hbhart.eth0x35a782Af7355BC5fA4452831B15442d3DEFB1d77

Multi-sigs

TitleEnsAddress
HBHDeployervibes.hbhart.eth0xeDDcb711569d5d93ad0b4CCb689658eF38c7cA4c
HBHDeployermine.hbhart.eth0xCF598d75EA9194850EB8e429f43F109665196dFa
HBHDeployerdevs.hbhart.eth0x5fe156F51443AE995300efC719DDeAE1D2C76730
TitleAddress
G3VersePass0xD5cfc0d7EE0d53ba192E2521e2a2C387bACE19Bb
WETH0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
RETH0xae78736Cd615f374D3085123A210448E74Fc6393

Contents

Constants

Git Source

INITIAL_OWNER

address constant INITIAL_OWNER = 0x5cA1e1Ab50E1c9765F02B01FD2Ed340f394c5DDA;

HBH_DEPLOYER

address constant HBH_DEPLOYER = 0x35a782Af7355BC5fA4452831B15442d3DEFB1d77;

DEVS_HBH_MULTISIG

address constant DEVS_HBH_MULTISIG = 0x5fe156F51443AE995300efC719DDeAE1D2C76730;

MINE_HBH_MULTISIG

address constant MINE_HBH_MULTISIG = 0xCF598d75EA9194850EB8e429f43F109665196dFa;

VIBES_HBH_MULTISIG

address constant VIBES_HBH_MULTISIG = 0xeDDcb711569d5d93ad0b4CCb689658eF38c7cA4c;

HBHART

address payable constant HBHART = payable(0x069220F5F85aE9B82371a29f5F9c70E0cBdcBf69);

MEMENTOS

address constant MEMENTOS = 0x069f85562F20e3c8120CbC8880cf67976992eA83;

CERT_HBH

address payable constant CERT_HBH = payable(0x069376a7d55C202Aa79565B25E167B97016D9168);

LM_HBH

address payable constant LM_HBH = payable(0x069D89AE50Da299e3Caa5BD6e8a777C59fB9BEe8);

G3PASS

address constant G3PASS = 0xD5cfc0d7EE0d53ba192E2521e2a2C387bACE19Bb;

G3PASSID

uint256 constant G3PASSID = 1;

HBHART_SALT

bytes32 constant HBHART_SALT = bytes32(uint256(261411));

MEMENTOS_SALT

bytes32 constant MEMENTOS_SALT = bytes32(uint256(678014));

CERT_HBH_SALT

bytes32 constant CERT_HBH_SALT = bytes32(uint256(3077067));

LM_HBH_SALT

bytes32 constant LM_HBH_SALT = bytes32(uint256(2575142));

HBHART_CODE

string constant HBHART_CODE = "HalfBakedHeroes.sol:HalfBakedHeroes";

MEMENTOS_CODE

string constant MEMENTOS_CODE = "Mementos.sol:Mementos";

CERT_HBH_CODE

string constant CERT_HBH_CODE = "Certificate.sol:CertificateOfAuthenticity";

LM_HBH_CODE

string constant LM_HBH_CODE = "LiquidityManager.sol:LiquidityManager";

UNISWAPV3_RETH_WETH_500_POOL

address constant UNISWAPV3_RETH_WETH_500_POOL = 0xa4e0faA58465A2D369aa21B3e42d43374c6F9613;

UNISWAPV2FACTORY

address constant UNISWAPV2FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;

BURN_ADDRESS

address constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;

POOL_FACTORY

IUniswapV3Factory constant POOL_FACTORY = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984);

POSITION_MANAGER

address constant POSITION_MANAGER = 0xC36442b4a4522E871399CD717aBDD847Ab11FE88;

UNISWAPV2_ROUTER

address constant UNISWAPV2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;

UNISWAPV3ROUTER

address constant UNISWAPV3ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;

WETH9

address constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

ROCKET_POOL_STAKED_ETH

address constant ROCKET_POOL_STAKED_ETH = 0xae78736Cd615f374D3085123A210448E74Fc6393;

Format

Git Source

Functions

decimal

function decimal(uint256 value, uint256 decimals, uint256 displayDecimals)
    internal
    pure
    returns (string memory output);

decimal

function decimal(uint256 value, uint256 decimals, uint256 displayDecimals, bool commas)
    internal
    pure
    returns (string memory output);

decimal

function decimal(int24 value) internal pure returns (string memory output);

_formatZero

function _formatZero(uint256 displayDecimals) private pure returns (bytes memory output);

_format

function _format(uint256 value, uint256 decimals, uint256 displayDecimals, bool commas)
    private
    pure
    returns (bytes memory output);

ReplenishParam

Git Source

struct ReplenishParam {
    address token;
    address receiver;
    uint16 poolVersion;
    uint256 topUpEth;
    uint256 topUpReth;
}

Slot0

Git Source

struct Slot0 {
    uint160 sqrtPriceX96;
    int24 tick;
    uint16 observationIndex;
    uint16 observationCardinality;
    uint16 observationCardinalityNext;
    uint32 feeProtocol;
    bool unlocked;
}

IUniswapV3PoolSlot0

Git Source

Functions

slot0

function slot0() external view returns (Slot0 memory);

Liquidity

Git Source

Functions

replenishRewards

function replenishRewards(ReplenishParam memory params) internal returns (uint256 output);

getPrice

function getPrice(address pool) internal view returns (uint256 price);

getPriceV2

function getPriceV2(address pool, address tokenAddress) internal view returns (uint256 price);

tickToPrice

function tickToPrice(int24 tick) internal pure returns (uint256 price);

priceToTick

function priceToTick(uint256 price) internal pure returns (int24 tick);

sqrtPriceX96ToPrice

function sqrtPriceX96ToPrice(uint160 sqrtPrice) internal pure returns (uint256 price);

priceToSqrtPriceX96

function priceToSqrtPriceX96(uint256 price) internal pure returns (uint160 sqrtPriceX96);

getBpsDiff

function getBpsDiff(uint256 price1, uint256 price2) internal pure returns (uint256 diff);

_getPriceRevertOnTwap

function _getPriceRevertOnTwap(IUniswapV3Pool pool) internal view returns (uint256 currentPrice);

_getTwapPrice

function _getTwapPrice(IUniswapV3Pool pool) internal view returns (uint256 twapPrice, uint256 currentPrice);

_getSwapInfo

function _getSwapInfo() private view returns (SwapInfo memory swapInfo);

swapWethToReth

function swapWethToReth(uint256 amountIn, address recipient) internal returns (uint256 rethOut);

balancerSwap

Perform a swap via Balancer

function balancerSwap(uint256 amount, address recipient) private returns (uint256);

Parameters

NameTypeDescription
amountuint256Amount of ETH to swap
recipientaddressThe recipient of the output tokens

Structs

SwapInfo

struct SwapInfo {
    uint256 twapPrice;
    uint256 currentPriceUni100;
    uint256 currentPriceUni500;
    uint256 currentPricePancake500;
    uint256 triedFlags;
    address router;
    uint24 fee;
}

Constants

Git Source

WETH9

address constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

ROCKET_POOL_STAKED_ETH

address constant ROCKET_POOL_STAKED_ETH = 0xae78736Cd615f374D3085123A210448E74Fc6393;

UNISWAPV2_ROUTER

address constant UNISWAPV2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;

UNISWAPV3_ROUTER

address constant UNISWAPV3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;

PANCAKESWAPV3_ROUTER

address constant PANCAKESWAPV3_ROUTER = 0x1b81D678ffb9C0263b24A97847620C99d213eB14;

POOL_FEE_LPV3

uint24 constant POOL_FEE_LPV3 = 10_000;

POOL_FEE_RETH_500

uint24 constant POOL_FEE_RETH_500 = 500;

POOL_FEE_RETH_100

uint24 constant POOL_FEE_RETH_100 = 100;

MAX_TWAP_DIFF

uint24 constant MAX_TWAP_DIFF = 125;

SECONDS_AGO

int32 constant SECONDS_AGO = 120;

Q96

uint256 constant Q96 = 0x1000000000000000000000000;

RETH_PRICE_LIMIT

uint256 constant RETH_PRICE_LIMIT = 1.25 ether;

RETH_PRICE_SLIPPAGE

uint256 constant RETH_PRICE_SLIPPAGE = 1.3 ether;

PANCAKESWAP_RETH_500

address constant PANCAKESWAP_RETH_500 = 0x2201d2400d30BFD8172104B4ad046d019CA4E7bd;

UNISWAPV3_RETH_500

address constant UNISWAPV3_RETH_500 = 0xa4e0faA58465A2D369aa21B3e42d43374c6F9613;

UNISWAPV3_RETH_100

address constant UNISWAPV3_RETH_100 = 0x553e9C493678d8606d6a5ba284643dB2110Df823;

BALANCER_VAULT

IBalancerVault constant BALANCER_VAULT = IBalancerVault(0xBA12222222228d8Ba445958a75a0704d566BF2C8);

BALANCER_POOL_ID

bytes32 constant BALANCER_POOL_ID = 0x1e19cf2d73a72ef1332c882f20534b6519be0276000200000000000000000112;

UNISWAP_100_FLAG

uint256 constant UNISWAP_100_FLAG = 1;

UNISWAP_500_FLAG

uint256 constant UNISWAP_500_FLAG = 2;

PANCAKE_500_FLAG

uint256 constant PANCAKE_500_FLAG = 4;

ALL_FLAGS

uint256 constant ALL_FLAGS = UNISWAP_100_FLAG + UNISWAP_500_FLAG + PANCAKE_500_FLAG;

Nameable

Git Source

State Variables

ADDR_REVERSE_NODE

bytes32 private constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;

Functions

ensReverseRegistrar

function ensReverseRegistrar() private view returns (IEnsReverseRegistrar);

setName

function setName(string memory ensName) internal;

CertificateOfAuthenticity

Git Source

Inherits: ERC721, EIP712, ERC2981, Ownable, ICertificate

Author: Scale Labs Ltd.

Behold! Herein lies the essence of authenticity, each certificate a guardian of history, a beacon of truth in a realm of shadows. It stands as a bulwark against the tides of time, ensuring that the deeds and honor of each hero and their steadfast sidekick remain unaltered and celebrated through the ages.

This solemn tome serves as the immutable chronicle of provenance, where each folio within is a CertificateOfAuthenticity, an onchain artifact etched in the very ether itself. These certificates are not mere documents, but sacred vellum bound by code, depicting the valiant sidekicks of our heroes, alongside every trait and chronicle that composes their legend. In this sanctum, each certificate is a testament to the lineage and lore of its corresponding hero, a chain of custody unbroken and unassailable. The art, a tapestry of SVG, is conjured by the contract's arcane workings, a visual ode to the companions that journey alongside our champions.

State Variables

NAME

string private constant NAME = "Certificate of Authenticity - Half Baked Heroes";

SYMBOL

string private constant SYMBOL = "CAHBH";

ENS_NAME

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

ROYALTY_BPS

uint96 private constant ROYALTY_BPS = 500;

MAX_SUPPLY

uint256 private constant MAX_SUPPLY = 15_000;

nft

ICertifiedNft public immutable nft;

_renderer

IRenderer private _renderer = IRenderer(CERTIFICATERENDERER);

vibesDirection

address public vibesDirection = VIBES_HBH_MULTISIG;

_nextTokenId

uint256 private _nextTokenId = 1;

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;

name

Returns the name of the token.

function name() public pure virtual override returns (string memory);

symbol

Returns the symbol of the token.

function symbol() public pure virtual override returns (string memory);

maxSupply

maximum total supply.

function maxSupply() external pure returns (uint256);

supportsInterface

function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC2981) returns (bool result);

refreshMetadata

function refreshMetadata(uint256 certId) external onlyHBHContract;

setRenderer

function setRenderer(address renderingContract) external onlyOwner;

tokenURI

A distinct Uniform Resource Identifier (URI) for a given asset.

Throws if tokenId is not a valid NFT. URIs are defined in RFC 3986. The URI may point to a JSON file that conforms to the "ERC721 Metadata JSON Schema".

function tokenURI(uint256 tokenId) public view virtual override returns (string memory);

contractURI

function contractURI() external view returns (string memory);

exists

function exists(uint256 id) external view returns (bool);

notarize

function notarize(address to, uint16 heroId, uint80 ethSent) external onlyHBHContract returns (uint16);

receive

receive() external payable;

updateVibesDirection

Command the cosmic flow of "vibes", the royalties and trading fees, to a new beacon.

Through the sacred ritual of "updateVibesDirection", the "owner" invokes the ancient right to redirect these mystical currents from the hallowed halls of the multisig sanctum to the autonomous altars of future smart contracts. This solemn act is a testament to our evolving saga, a deliberate stride towards an ordained destiny where the "vibes" nourish the roots of a decentralized paradise. Emits a {VibesUpdate} event to herald this new epoch in vibes allocation.

function updateVibesDirection(address newGroove) external onlyOwner;

Parameters

NameTypeDescription
newGrooveaddressThe address of the new custodian of "vibes".

distributeEth

function distributeEth() external;

distributeToken

function distributeToken(address tokenAddress) external;

provenanceData

function provenanceData(uint256 id)
    external
    view
    returns (uint16 heroId, uint80 ethSent, ProvenanceTransferEvent[] memory provenance);

latestProvenanceData

function latestProvenanceData(uint256 id, uint256 maxCount)
    external
    view
    returns (uint16 heroId, uint80 ethSent, ProvenanceTransferEvent[] memory provenance, uint256 length);

isApprovedOrOwner

function isApprovedOrOwner(address account, uint256 id) public view virtual returns (bool);

_domainNameAndVersion

function _domainNameAndVersion() internal pure override returns (string memory tokenName, string memory version);

DOMAIN_SEPARATOR

function DOMAIN_SEPARATOR() external view returns (bytes32);

transferEthPassError

function transferEthPassError(address to, uint256 value) private;

_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

MetadataUpdate

This event emits when the metadata of a token is changed. So that the third-party platforms such as NFT market could timely update the images and related attributes of the NFT.

event MetadataUpdate(uint256 _tokenId);

BatchMetadataUpdate

This event emits when the metadata of a range of tokens is changed. So that the third-party platforms such as NFT market could timely update the images and related attributes of the NFTs.

event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);

VibesUpdate

This event emits when the vibesDirection address is changed.

event VibesUpdate(address indexed newGroove);

RecordEvent

Git Source

In the realm of Half Baked Heroes, the RecordEvent struct serves as a chronicle for the illustrious achievements of the mightiest among players. It's not just data; it's a narrative woven into the very fabric of this epic saga.

This struct is used to log the ascension of a player to the zenith of hero collection.

struct RecordEvent {
    address playerOne;
    uint80 dateTime;
    uint16 heroesCount;
}

AccountExtra

Git Source

type AccountExtra is uint224;

AccountExtraData

Git Source

Functions

set

function set(uint80 whenPlayerOne, uint16 heroesCount) internal pure returns (AccountExtra etc);

get

function get(AccountExtra etc) internal pure returns (uint80 whenPlayerOne, uint16 heroesCount);

HalfBakedHeroes

Git Source

Inherits: ERC721, EIP712, ERC2981, Ownable, ICertifiedNft, IHero

Author: Scale Labs Ltd.

Not all those who wander are lost - J.R.R. Tolkien

Embark upon a quest within the Half Baked Heroes ERC721 contract, the architectural essence of a saga where creativity meets destiny. This smart contract safeguards 15,000 unique art experiences, each representing a valiant personality navigating the intricate Web3 maze—a cosmos of challenges and serendipities. In this coded sanctuary, our heroes are immortalized, each art experience embodying the essence of an odyssey in the burgeoning realm of decentralization. Token holders are not just collectors but participants in an epic journey, wielding the essence of possibility, where the daring seek freedom, the prudent uncover wisdom, and the collective spirit of Web3 unfolds. This smart contract is not merely a ledger but a charter for the explorers of the virtual continuum, where the intrepid pursue enlightenment, expression, and the uncharted territories that Web3 unfolds.

State Variables

NAME

string private constant NAME = "Half Baked Heroes";

SYMBOL

string private constant SYMBOL = "HBH";

ENS_NAME

'ENS_NAME' holds the ENS domain for the project, facilitating a user-friendly way to interact with the contract's address. The name 'hbhart.eth' is derived from Half Baked Heroes Art, underlining the artistic core of the project while providing a simplified point of reference for network participants.

string public constant ENS_NAME = "hbhart.eth";

BPS_DIVISOR

uint256 private constant BPS_DIVISOR = 10_000;

OVERAGE_BPS

uint256 private constant OVERAGE_BPS = 5_000;

STIMMY_BPS

uint256 private constant STIMMY_BPS = 2_000;

DEV_BPS

uint256 private constant DEV_BPS = 300;

ROYALTY_BPS

uint96 private constant ROYALTY_BPS = 500;

MAX_SUPPLY

uint256 private constant MAX_SUPPLY = 15_000;

PROVENANCE_HASH

uint256 private constant PROVENANCE_HASH = 0;

_renderer

IRenderer private _renderer = IRenderer(HBHRENDERERHIDDEN);

_lastSkillChoice

uint256 private _lastSkillChoice;

lastMineBlock

'lastMineBlock' is the project's timekeeper, marking the passage of events within the blockchain's eternal chronicle. It is a beacon for the Half Baked Heroes, guiding them through the digital odyssey of Web3, illuminating the path tread by adventurers past.

uint256 public lastMineBlock;

mementos

'mementos' are the ERC20 tokens that represent the essence of experience and interaction within the Half Baked Heroes universe. Each token is a fragment of the shared journey, a collectible echo of the adventures and tales woven through the Web3 tapestry. This is an immutable reference to the Mementos ERC20 token contract, symbolizing the quantifiable interactions and shared experiences of the community, encapsulated in transferable token form.

Mementos public immutable mementos;

certificate

The 'certificate' is the ERC721 token that chronicles the lineage and lore of each hero, a scroll of provenance that is both shield and storyteller. It serves as a guardian of lineage, offering a verifiable chain of custody and on-chain image rendering, ensuring the legacy of each Hero is preserved.

CertificateOfAuthenticity public immutable certificate;

liquidityManager

'liquidityManager' is the custodian of flow within the Half Baked Heroes' realms, a conduit through which the lifeblood of interaction and exchange courses. It is the cornerstone of the community's interconnectedness, facilitating the seamless melding of paths in the Web3 labyrinth. It supports the dynamic interplay of the project's assets and the community's collaborative endeavors.

LiquidityManager public immutable liquidityManager;

_unexcavated

Manages the pool of unselected heroes in a dynamic and semi-randomized fashion.

Implements a variation of the Fisher-Yates shuffle algorithm in storage to facilitate random and fair selection of hero IDs for the excavation process. When a skill draw occurs, the algorithm checks if the value at the drawn index is zero, indicating an unselected hero. If non-zero, the stored value is used. Post-selection, the last value in the array is moved to the chosen index, and the array size is decreased to exclude the selected hero, thereby preparing for the next draw without needing pre-randomization at deployment. Indexed from 1 to MAX_SUPPLY inclusive, with a placeholder 0 index to ensure array length reflects the number of remaining heroes accurately.

uint16[MAX_SUPPLY + 1] private _unexcavated;

unexcavated

Tracks the number of heroes yet to be unearthed in the collection.

Holds the count of remaining heroes that have not been assigned to miners, decrementing with each excavation. This variable is crucial for understanding the progress of the collection's discovery and for the execution of the random selection algorithm which relies on the diminishing supply for its calculations. Initialized to MAX_SUPPLY and decreases as heroes are drawn from the _unexcavated pool.

uint256 public unexcavated = MAX_SUPPLY;

_provenance

Chronicles the epic journeys of heroes through time and space. In the realm of Half Baked Heroes, each hero's saga is etched in the annals of _provenance. This sacred ledger is a testament to the valor and honor of the heroes, bearing witness to their passage from one guardian to the next. The uint16 key, reminiscent of a hero's unique essence, unlocks an array of ProvenanceTransferEvent records - each a storied fragment of the hero's legacy. These records are not merely transactions; they are the whispered tales of bonds forged and destinies embraced, a private collection of moments that resonate with the echoes of time. Only the chosen chroniclers of the code may inscribe upon this hallowed scroll, ensuring that the legacy of each hero remains unblemished and true to the heart of their tale.

mapping(uint16 => ProvenanceTransferEvent[]) private _provenance;

currentRecord

In the Half Baked Heroes' ledger of legends, one record shines above all - the currentRecord. It is not just a tally or a statistic; it is a throne, a summit where the mightiest collector of heroes stands alone. This esteemed position is reserved for the one who, through cunning, strategy, and perhaps a touch of destiny, has amassed the greatest number of heroes under their banner. The currentRecord is a public declaration, a beacon for all challengers to behold and aspire to. It bears the address of the reigning champion, the count of heroes that fortify their dominion. As the saga unfolds and new players enter the game, this record may shift and sway, but it will always mark the heights of ambition for every participant in the Half Baked Heroes universe. Witness the currentRecord - a testament to triumph, a measure of mastery, and a challenge to all.

RecordEvent public currentRecord;

devsCoffeeAndInstantRamen

Tracks the outstanding amount apportioned to the developers for their foundational work on the project.

Holds the balance that is yet to be claimed by the development team, a testament to the late nights and diligent work poured into the Half Baked Heroes universe; as well as the creative problem-solving invested into the technical tapestry of this project.

uint256 public devsCoffeeAndInstantRamen;

Functions

onlyHeroes

onlyHeroes() is the gatekeeper ensuring that only those who have joined the illustrious ranks of Hero holders may pass. It's a tribute to the camaraderie and exclusivity of the Half Baked Heroes community, where holding a Hero is not just ownership — it's a membership, a badge of honor in the Web3 odyssey.

This modifier enforces the sacred rule that only addresses with at least one Hero in their keep may invoke the function it guards. It upholds the community's ethos, where privileges are reserved for those who have embarked on the journey through the maze, bearing their digital totems with pride. Should one fail to present such proof, the spirits of the contract shall deny passage with a decree: "Not a Hero".

modifier onlyHeroes();

constructor

constructor() payable;

name

Returns the name of the token.

function name() public pure virtual override returns (string memory);

symbol

Returns the symbol of the token.

function symbol() public pure virtual override returns (string memory);

maxSupply

maximum total supply.

function maxSupply() external pure returns (uint256);

totalSupply

total supply of the tokens.

function totalSupply() external view returns (uint256);

provenance

Chronicles the lineage of ownership for our Heroes, weaving the tale of each guardian who has held the torch of stewardship from the genesis of their journey. This historical ledger is not merely a list but a narrative of the changing hands that have shaped the Hero's saga in the realm of Web3.

Retrieves the provenance record for a given Hero, identified by heroId. This function compiles a historical account of all previous owners and the respective timestamps of their custodianship. It's a testament to the Hero's legacy and the chain of custody is an essential feature for transparency and authenticity.

function provenance(uint256 heroId) external view returns (ProvenanceTransferEvent[] memory events);

provenance

function provenance(uint256 heroId, uint256 index) external view returns (ProvenanceTransferEvent memory entry);

provenanceWindow

function provenanceWindow(uint256 heroId, uint256 offset, uint256 maxCount)
    external
    view
    returns (ProvenanceTransferEvent[] memory events, uint256 totalLength);

provenanceLatest

function provenanceLatest(uint256 heroId, uint256 maxCount)
    external
    view
    returns (ProvenanceTransferEvent[] memory events, uint256 totalLength);

provenanceLength

Tracks the number of provenance entries for Half Baked Heroes.

This state variable serves as a counter for the documented lineage of each hero, illustrating the journey they've undertaken through the Web3 realm. The length of the provenance is a direct reflection of the rich histories and stories that accompany each hero, detailing their passage from one custodian to the next within the community.

function provenanceLength(uint256 heroId) public view returns (uint256);

openMining

Initiates the Half Baked Heroes' quest, unlocking the creative odyssey within the Web3 labyrinth.

The openMining function is the clarion call in the grand narrative of Half Baked Heroes, marking the onset of a creative expedition. This function unlocks the portals to a realm where artistry is the quarry and ingenuity the pickaxe. The community of valiant explorers is beckoned to carve out their own saga within the intricate maze of Web3. Here, heroes are forged in the crucible of the shared zeal for discovery that is the cornerstone of the blockchain's vast, uncharted vistas.

function openMining() public payable onlyOwner;

getHoldingInfo

Retrieves the current holder and their holding duration for a specified hero.

Returns the custodian's address and duration of their tenure for a given hero, reflecting the bond and continuity in the Half Baked Heroes saga. Use this to assess the commitment of the current holder to their digital companion.

function getHoldingInfo(uint256 tokenId) external view returns (address holder, uint256 holdingTime);

Parameters

NameTypeDescription
tokenIduint256Identifier for a hero.

Returns

NameTypeDescription
holderaddressAddress of the hero's present custodian.
holdingTimeuint256Tenure length in seconds of the current holder.

supportsInterface

Determines if the contract implements the interface specified by interfaceId. This function checks for the support of multiple interface identifiers defined by EIP-721 (NFT standard) and EIP-2981 (Royalty standard), and also supports a custom interface for metadata updates.

function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC2981) returns (bool result);

Parameters

NameTypeDescription
interfaceIdbytes4The identifier of the interface to check for support.

Returns

NameTypeDescription
resultbooltrue if the interface is supported, false otherwise.

reveal

Serves as the grand unveil, transitioning our valiant avatars from the shadows of the unknown into the limelight of the Web3 world.

Like the final piece of a grand puzzle, this function is the moment of truth where each character is fully actualized, emerging from the digital chrysalis to display their unique traits and artistry. Called after all 15,000 heroes are mined to transition their metadata and images from a placeholder to the full revealed state. This function updates the renderer contract to point to the permanent, individualized metadata and images that represent each character's distinct journey and attributes.

function reveal(address renderer) external onlyOwner;

feedDevs

feedDevs() serves as a token of appreciation, a modest tribute from the ecosystem to its creators. It channels a small percentage of the mining fees to the developers, sustaining the artisans of code who laid the foundation for our Heroes' adventures in the Web3 realm.

Allows for the allocation of a predefined, minor share of the mining fees to the developers, ensuring they receive a fair compensation for their labor. This function, callable by anyone, is a nod to the symbiotic relationship between the community and its developers, promoting a sustainable and supportive environment.

function feedDevs() external;

cleanseThePalate

cleanseThePalate() acts as a rite of homage, channeling the predominant share of the art sale proceeds to the maestro of imagination whose foresight crafted the universe where our Heroes dwell. It's a tribute to the principal creative force, the name that stands foremost among the annals of our venture.

Redirects the primary segment of art sale revenues to the project's creative pioneer, in acknowledgment of their pivotal inspiration and sustained artistic leadership. This function represents a monetary salute to the figure whose vision has been paramount in shaping the narrative and aesthetic of the Half Baked Heroes.

function cleanseThePalate() external;

burnRemaining

The ceremonial extinguishing of unclaimed tokens, a decisive act to preserve the valor of our Heroes' realm by preventing undue market turbulence. This conflagration ensures the stability and rarity of the mementos that commemorate our collective journey in Web3.

Executes the irrevocable destruction of any mementos reward tokens that remain unmined, effectively removing them from circulation. This safeguard is designed to mitigate potential negative pressure and maintain the token's integrity and scarcity, upholding the economic balance of the Half Baked Heroes ecosystem.

function burnRemaining() external onlyHeroes;

errorsAndOmissionsExcepted

Acts as a safeguard, a vigilant sentinel ready to correct the course of our heroes' visual tales should any anomaly arise. It embodies our commitment to excellence and community trust, ensuring that the digital odyssey of each hero reflects their true essence, as intended by the artists and the community.

This function serves as an emergency measure to set a new renderer in the event of post-reveal discrepancies or errors in the artwork or traits. It's a contingency plan, empowering the community to address and rectify any inconsistencies discovered in the NFTs' representation, thus preserving the collection's integrity and value.

function errorsAndOmissionsExcepted(address renderer) external onlyOwner;

tokenURI

A distinct Uniform Resource Identifier (URI) for a given asset.

Throws if tokenId is not a valid NFT. URIs are defined in RFC 3986. The URI may point to a JSON file that conforms to the "ERC721 Metadata JSON Schema".

function tokenURI(uint256 heroId) public view virtual override returns (string memory uri);

Parameters

NameTypeDescription
heroIduint256The unique identifier for a hero within the collection.

Returns

NameTypeDescription
uristringA string URI pointing to a JSON file with the hero's metadata.

contractURI

Provides the metadata for the entire Half Baked Heroes contract. This metadata contains information about the collection's name, description, image, and external links - a consolidated view that 3rd party inventory listings can use to present users with details about the Half Baked Heroes project as a whole. It follows the OpenSea contract-level metadata standard, helping to ensure broad compatibility with various platforms.

function contractURI() external view returns (string memory uri);

Returns

NameTypeDescription
uristringA string URI pointing to a JSON file with the contract's metadata.

exists

Checks if a hero with the specified heroId exists within the collection. Existence of a hero is determined by the presence of associated data in the contract's storage. This function is useful for validating hero IDs before performing operations that require a valid and existing hero token.

function exists(uint256 heroId) public view virtual returns (bool);

Parameters

NameTypeDescription
heroIduint256The ID of the hero to check for existence.

Returns

NameTypeDescription
<none>boolTrue if the hero exists, false otherwise.

receive

In the adventurous world of Half Baked Heroes, this function serves as a secure conduit for heroes to channel Ether directly into the heart of the labyrinth. It empowers participants to invoke the arcane _excavate ritual without the need to connect their wallets to potentially perilous ports, fortifying their quest with an added layer of security. This direct engagement can be accomplished via the mystical identifier "hbhart.eth", bringing heroes to their destiny with the mere dispatch of Ether. By requiring a tribute that exceeds the minimum threshold, it filters out ill-prepared adventurers, while the ceiling prevents any single hero from overshadowing the collective quest. This range allows heroes to contribute what they can, upholding the spirit of communal progress in the Web3 adventure.

This receive function is critical for enhancing security as it allows the contract to accept ETH directly, bypassing the need for external web interfaces which may pose additional security risks. When Ether is sent to the contract's address or its ENS name "hbhart.eth", it excludes the sender from the potential vulnerabilities of connecting to unknown or insecure frontends. At the same time, it permits senders to choose any amount above this floor up to a maximum cap.

receive() external payable;

mine

function mine() public payable;

_excavate

_excavate() is the moment of alchemy where commitment meets creation, as patrons of the arts send forth ETH to unearth Heroes. This rite of passage bestows upon them a Hero, a certificate of their unique legacy, and rewards reflective of the ETH contributed, celebrating the patron's role in the artistic odyssey of Web3.

This function is the core of the minting operation, where the transaction's value is transformed into a tangible piece of the collection's lore. It awards a newly discovered Hero, authenticates their origin, and dispenses a fair distribution of reward tokens as a testament to the patron's generousity in the artistic journey, ensuring a harmonious link between contribution and reward.

function _excavate() private;

_mineHero

function _mineHero(uint256 unexcavatedCount, uint256 ethSent, uint256 mementosCount, uint256 extraBonus) private;

getExtraData

Retrieves supplementary data associated with a specific hero. This data includes the unique certificate ID, which serves as a proof of the hero's authenticity and its originality within the collection. Additionally, it provides the block gap since the prior mining event, offering insight into the temporal distribution of hero creation events. This function can be utilized to gain deeper knowledge about the provenance and rarity aspects of each hero, enriching the narrative and value of ownership in the Half Baked Heroes universe.

function getExtraData(uint256 heroId)
    public
    view
    returns (bool heldG3VrsePassAtMine, uint16 certificateId, uint24 blockGapSincePriorMine);

Parameters

NameTypeDescription
heroIduint256The unique identifier for a hero within the collection.

Returns

NameTypeDescription
heldG3VrsePassAtMineboolWhether a G3Vrse Pass was held by the mine when mining this hero
certificateIduint16The ID linked to the hero's certificate of authenticity.
blockGapSincePriorMineuint24The number of blocks mined since the previous hero was created.

getAux

Retrieves auxiliary data for an account, specifically the timestamp of when the account became the leading holder of heroes, referred to as 'Player One', and the count of heroes currently held by the account. This information is vital in understanding the account's standing within the community, reflecting both their prominence and the dynamic nature of hero ownership.

function getAux(address account) public view virtual returns (uint80 whenPlayerOne, uint16 heroesCount);

Parameters

NameTypeDescription
accountaddressThe address of the account to query.

Returns

NameTypeDescription
whenPlayerOneuint80The timestamp of when the account attained the position of 'Player One'.
heroesCountuint16The total number of heroes held by the account when they attained that position.

isApprovedOrOwner

Determines if an address is an approved operator or the owner of a given hero. This check is essential for actions that require permission to interact with a hero owned by another account. It encapsulates the core ownership verification needed for secure transfers and approvals within the ecosystem.

function isApprovedOrOwner(address account, uint256 heroId) public view virtual returns (bool);

Parameters

NameTypeDescription
accountaddressThe address to check for approval or ownership.
heroIduint256The unique identifier of the hero in question.

Returns

NameTypeDescription
<none>booltrue if the account is an approved operator or the owner of heroId; otherwise, false.

DOMAIN_SEPARATOR

Provides the domain separator used in the EIP-712 domain structure. This is a unique value that is used to prevent certain types of signature replay attacks, ensuring that signatures are valid only within the context of this contract. It's derived from the contract's address and other distinctive characteristics, which typically include the contract's name and version, as well as the chain Id.

function DOMAIN_SEPARATOR() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32The EIP-712 domain separator as a bytes32 value.

_beforeTokenTransfer

_beforeTokenTransfer() is invoked at the crossroads of change, a moment of contemplation and farewell. As a Hero embarks on a new chapter away from its original bearer, this function echoes the silent musings of parting - the introspections of giving away or the resolve in selling a cherished journeyman of the Web3 labyrinth.

Triggered as a prelude to each token transfer, this hook is akin to a ritualistic pause, a last embrace before the transfer of guardianship. It's a checkpoint ensuring that all conditions and rules are met before a Hero can venture forth into new hands, ensuring the sanctity of the passage is preserved.

function _beforeTokenTransfer(address, address, uint256) internal virtual override;

_afterTokenTransfer

_afterTokenTransfer() marks the dawn of a new allegiance as a Hero finds sanctuary in the embrace of a new custodian. With the change etched in the annals of _provenance, this function encapsulates the Hero's silent jubilation—a testament to their odyssey across the digital expanse to their destined haven.

The function records the transfer continuity, updating the _provenance ledger to reflect the latest guardianship. In the event that the receiving wallet ascends as the premier collector by size, it triggers a NewPlayerHasEnteredTheGame event, celebrating this milestone and acknowledging the new pacesetter in the realm of Half Baked Heroes.

function _afterTokenTransfer(address, address to, uint256 heroId) internal virtual override;

_skillDraw

Executes a pseudo-random skill draw from the pool of unexcavated heroes, which is efficient and sufficiently unpredictable for the purposes of the draw, as the heroes are unrevealed at this stage. The order in which heroes are mined is predetermined by a provenance hash, thus the draw does not need to be perfectly random. This method avoids the complexities and vulnerabilities of on-chain randomness. The draw operates by checking the value at a pseudo-random index within the unexcavated array. If the value is zero, the index itself is used as the heroId. If not, the non-zero value is used as the heroId. After a heroId is selected, the value from the end of the array is moved to the selected index, and the array size is reduced by one. This ensures that each hero is only drawn once and that the array shrinks as heroes are excavated.

function _skillDraw(uint256 unexcavatedCount, uint256 mementosCount, uint256 extraBonus)
    private
    returns (uint256 index);

Parameters

NameTypeDescription
unexcavatedCountuint256The current count of unexcavated heroes, which dictates the range of the draw.
mementosCountuint256
extraBonusuint256

Returns

NameTypeDescription
indexuint256The index of the drawn hero.

_setRenderer

Entrusts a new Grand Illustrator with the sacred duty of rendering heroes. This clandestine function weaves the fabric of heroism into visible forms, cloaking its workings in the contract’s veiled chambers. Only the contract's arcane architects may invoke this rite, updating the ethereal link to the Grand Illustrator whose arcane craft gives form to valor.

function _setRenderer(address renderer) private;

Parameters

NameTypeDescription
rendereraddressThe ethereal abode of the new Grand Illustrator.

_domainNameAndVersion

Returns the domain name and version for EIP-712 signing. This function is used internally for EIP-712 domain separation, which helps ensure that signatures are valid only for this contract and version, protecting against replay attacks. The function is pure, not modifying or reading blockchain state, and returns the contract's name and a hardcoded version number.

function _domainNameAndVersion() internal pure override returns (string memory _name, string memory version);

Returns

NameTypeDescription
_namestringThe name of the token contract, as defined by the ERC-721 name() function.
versionstringThe version of the contract, set to "1" for initial release.

_checkIsHero

A clandestine rite to discern if the caller is among the vaunted ranks of heroes. In the shadows, it invokes the ancient ledger's balanceOf, a tome of ownership inscribed with the deeds of those who command the allegiance of heroes. It demands proof of a bond with at least one hero, lest the caller face the harsh truth of their mortal standing. Should one fail to present such proof, the spirits of the contract shall deny passage with a decree: "Not a Hero".

function _checkIsHero() private view;

_checkIsStillEarlyBro

Ensures that certain functions are not invoked prematurely during the early stage of the smart contract's life cycle. This sentinel function guards the nascent period where the narrative of heroes is still unwritten, and the landscape of the realm remains veiled in mystique. If the 'unexcavated' count is not yet diminished to zero, it signifies that the dawn of discovery still breaks, and the sentinel upholds the sanctity of this era by asserting: "Still Early Bro"

function _checkIsStillEarlyBro() private view;

_brutalized

For the culture 🫠 if you know you know

dead code that will be removed from the bytecode

function _brutalized(address a) private view returns (address result);

transferEthPassError

Attempts to transfer Ether (value) to the address to, reverting the transaction with the provided error message if the transfer fails. This function uses a low-level call to transfer Ether, which provides all available gas by default and returns data that can potentially include a revert reason. The function is marked internal, meaning it can only be called from within this contract or its derivatives.

function transferEthPassError(address to, uint256 value) internal;

Parameters

NameTypeDescription
toaddressThe recipient address to which Ether is being sent.
valueuint256The amount of Ether (in wei) to be transferred.

Events

HeroFullyCooked

Emitted for each Hero that emerges triumphantly from the depths of creation, signaling the end of their mining journey with a unique heroId and certificateId, along with the measure of mementos bestowed upon their discoverer.

Proclaims the completion of a Hero's mining process, etching their entry into the ledger with their identifiers and the number of mementos rewarded. This event encapsulates the decentralized spirit of the collection, underlining that The Revolution Will Not Be Centralized.

event HeroFullyCooked(uint256 indexed heroId, uint256 indexed certificateId, uint256 mementosCount);

NewPlayerHasEnteredTheGame

Casts a spotlight on a new leading collector in the community, marking the entrance of a challenger with a record-breaking number of Heroes.

Emitted when a wallet ascends to become the top holder of Heroes, surpassing the previous record. It symbolizes a shift in the leaderboard, akin to an ancient witch, residing in her enigmatic abode, who acknowledges the arrival of a worthy individual by offering to impart the art of Diplomacy for her own inscrutable purposes.

event NewPlayerHasEnteredTheGame(address indexed challenger, uint256 heroesCount);

MetadataUpdate

This event emits when the metadata of a token is changed. So that the third-party platforms such as NFT market could timely update the images and related attributes of the NFT.

event MetadataUpdate(uint256 _tokenId);

BatchMetadataUpdate

This event emits when the metadata of a range of tokens is changed. So that the third-party platforms such as NFT market could timely update the images and related attributes of the NFTs.

event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);

Constants

Git Source

MIN_VIBES

Represents the minimum 'VIBES' (value) required to mine a hero from the maze. This constant sets the floor for participation in the mining process, ensuring that all heroes can be mined with at least this minimum contribution. Sending more than this minimum can result in higher recognition, reflecting the sender's greater commitment to the Half Baked Heroes' journey. It's a threshold ensuring fair entry while allowing for the acknowledgment of more significant contributions.

uint256 constant MIN_VIBES = 0.5 ether;

HalfBakedHeroesDeployer

Git Source

Inherits: Ownable

State Variables

ENS_NAME

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

Functions

constructor

constructor() payable;

create3

function create3(bytes32 salt, bytes memory creationCode) external payable onlyOwner returns (address addr);

addressOf

function addressOf(bytes32 salt) external view returns (address);

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);

Constants

Git Source

PHI_TESSERACTED

uint256 constant PHI_TESSERACTED = 6_854_101_966_249_684_544;

PHI

uint256 constant PHI = 1_618_033_988_749_894_848;

positionManager

INonfungiblePositionManager constant positionManager = INonfungiblePositionManager(POSITION_MANAGER);

swapRouter

ISwapRouter constant swapRouter = ISwapRouter(UNISWAPV3_ROUTER);

_token

IERC20Minimal constant _token = IERC20Minimal(MEMENTOS);

POSITIONS

uint16 constant POSITIONS = 33;

TICKS

uint16 constant TICKS = 64;

PROTOCOL_LIQUIDITY_PERCENT

uint256 constant PROTOCOL_LIQUIDITY_PERCENT = 25;

LIQUIDITY_PRODUCT

uint256 constant LIQUIDITY_PRODUCT = V2_LIQUIDITY_SUPPLY * V2_LIQUIDITY_ETH;

TICK_SPACING

int24 constant TICK_SPACING = 200;

MAX_TICK_ROUNDED

int24 constant MAX_TICK_ROUNDED = TickMath.MAX_TICK - (TickMath.MAX_TICK % TICK_SPACING);

Mementos

Git Source

Inherits: ERC20, Ownable

State Variables

NAME

string private constant NAME = "Mementos";

SYMBOL

string private constant SYMBOL = "MOTE";

ENS_NAME

'ENS_NAME' is a public constant that encapsulates the Ethereum Name Service domain, signifying an easily recognizable entry point for interacting with the contract. The prefix 'mementos' signifies the collectible nature of the NFTs, each a token of progress in the evolving narrative of Web3, attached to the 'hbhart' indicating the Half Baked Heroes Art collection.

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

POOL_FEE_RETH_500

uint24 private constant POOL_FEE_RETH_500 = 500;

HALF_BAKED_HEROES

IERC721NonFungibleToken private constant HALF_BAKED_HEROES = IERC721NonFungibleToken(HBHART);

LIQUIDITY_MANAGER

ILiquidityManager private constant LIQUIDITY_MANAGER = ILiquidityManager(LM_HBH);

skipLiquitiyPositionEvaluation

This public mapping records addresses that should be excluded from liquidity position evaluation.

If an address is set to true in this mapping, transfers to and from this address will not initiate the process of fee collection iterations steps from the liquidity positions. There are no token taxes/fees; is entirely liquidity provising fees which anyone can also claim by providing liquidity. The checks are avoided on mining and liquidity pool interaction to reduce gas as these are already higher gas events.

mapping(address => bool) public skipLiquitiyPositionEvaluation;

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();

onlyHeroes

onlyHeroes() is the gatekeeper ensuring that only those who have joined the illustrious ranks of Hero holders may pass. It's a tribute to the camaraderie and exclusivity of the Half Baked Heroes community, where holding a Hero is not just ownership — it's a membership, a badge of honor in the Web3 odyssey.

This modifier enforces the sacred rule that only addresses with at least one Hero in their keep may invoke the function it guards. It upholds the community's ethos, where privileges are reserved for those who have embarked on the journey through the maze, bearing their digital totems with pride.

modifier onlyHeroes();

constructor

Initiates the Memento token contract in alignment with fair launch principles.

Mints the total supply at launch with no presales, no allocations to the team, no insiders, or tokens reserved for future minting. "If I knew what the picture was going to be like, I wouldn’t make it" — Cindy Sherman

constructor();

name

Returns the name of the token.

function name() public view virtual override returns (string memory);

symbol

Returns the symbol of the token.

function symbol() public view virtual override returns (string memory);

decimals

Returns the decimals places of the token.

function decimals() public view virtual override returns (uint8);

maxSupply

maximum total supply.

function maxSupply() public pure returns (uint256);

addPools

Adds an array of pool addresses to the skip list for liquidity position evaluation.

Marks each pool address as true in the skipLiquidityPositionEvaluation mapping to prevent unnecessary fee collection iteration and reduce gas.

function addPools(address[] calldata pools) external onlyHBHContract;

Parameters

NameTypeDescription
poolsaddress[]An array of addresses representing the pool contracts to be added. Requires that the caller is an authorized HBH contract to ensure proper access control.

bonAppetit

Transfers ownership of the contract to the zero address, effectively making it ownerless.

This is a permanent action that renounces the control of the contract by setting its owner to the zero address. Requires that the caller is an authorized HBH contract to ensure it happens in the proper sequence.

function bonAppetit() external onlyHBHContract;

sacrificeDonatedTokens

When called, the function calculates 10% of the donated tokens' value and returns it to the caller, converting rest to WETH and sending to Liquiduty Manager.

Allows a hero to sacrifice tokens donated by others in exchange for a portion of their value. If the token is Mementos 100% will be burnt, if WETH or rETH 100% will be sent to liquidity manager.

function sacrificeDonatedTokens(address donatedTokenAddress) external onlyHeroes returns (uint256 lootDrop);

Parameters

NameTypeDescription
donatedTokenAddressaddressThe address of the token being sacrificed.

Returns

NameTypeDescription
lootDropuint256uint256 A sumptuous slice of the salvaged tokens, chosen by the very hands of the HalfBaked spirit, as a tribute to your deeds. Your share is not merely a reward, but a manifestation of the recycled energy of forgotten battles, now fuelling your journey in the mystical lands of Half Baked Heroes. May this bounty empower your adventures, and remind all heroes of the cycles of loss and gain, abandonment and rediscovery, within our universe.

_lootDropToHero

Embarks on the clandestine ritual of the Half Baked Heroes, invoking the spirits of the Web3 world to bestow upon the brave a portion of the collected spoils. This sacred ceremony transmutes the donated balance into a loot drop, a treasure that fuels the hero's further adventures in the cryptic labyrinth.

function _lootDropToHero(uint256 donatedBalance) private returns (uint256 lootDrop);

Parameters

NameTypeDescription
donatedBalanceuint256The total amount of the donation gathered by the hero's valiant exploits.

Returns

NameTypeDescription
lootDropuint256A treasure trove, calculated as a fraction of the donated balance, awarded to the noble hero.

_brutalized

For the culture 🫠

dead code that will be removed from the bytecode

function _brutalized(address a) private view returns (address result);

_afterTokenTransfer

function _afterTokenTransfer(address from, address to, uint256) internal override;

_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;

_checkIsHero

A clandestine rite to discern if the caller is among the vaunted ranks of heroes. In the shadows, it invokes the ancient ledger's balanceOf, a tome of ownership inscribed with the deeds of those who command the allegiance of heroes. It demands proof of a bond with at least one hero, lest the caller face the harsh truth of their mortal standing. Should one fail to present such proof, the spirits of the contract shall deny passage with a decree: "Not a Hero".

function _checkIsHero() private view;

Constants

Git Source

DECIMALS

uint256 constant DECIMALS = 18;

MAX_SUPPLY

uint256 constant MAX_SUPPLY = 2_718_281_828_459_045_235_360_287_471_352;

MINABLE_RESERVES

uint256 constant MINABLE_RESERVES = 1_679_990_560_988_901_160_611_699_557_940;

INITIAL_BURN

uint256 constant INITIAL_BURN = 1;

INITIAL_LIQUIDITY_SUPPLY

uint256 constant INITIAL_LIQUIDITY_SUPPLY = MAX_SUPPLY - MINABLE_RESERVES - INITIAL_BURN;

V2_LIQUIDITY_ETH

uint256 constant V2_LIQUIDITY_ETH = 0.5 ether;

LIQUIDITY_ETH

uint256 constant LIQUIDITY_ETH = 5 ether;

V2_LIQUIDITY_SUPPLY

uint256 constant V2_LIQUIDITY_SUPPLY = INITIAL_LIQUIDITY_SUPPLY * V2_LIQUIDITY_ETH / LIQUIDITY_ETH;

SCARIFICE_BPS

uint256 constant SCARIFICE_BPS = 1000;

BPS_DIVISOR

uint256 constant BPS_DIVISOR = 10_000;

RETH_PRICE_SLIPPAGE

uint256 constant RETH_PRICE_SLIPPAGE = 1.3 ether;