Skip to content
This repository was archived by the owner on Mar 10, 2026. It is now read-only.

TriplePanicLabs/grindurus-protocol

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

338 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

GrindURUS Protocol ๐Ÿš€

Automated Market Taker Protocol ๐Ÿค–

Onchain yield harvesting and strategy trade protocol. ๐Ÿ“ˆ

Use Cases (whole protocol) ๐ŸŒŸ

  1. Automated Onchain Trading: Implements a fully automated trading strategy based on mathematical and market-driven rules by one button "GRIND". ๐Ÿ“Š
  2. Capital Optimization: Maximizes efficiency of liquidity by dynamically adjusting liquidity. ๐Ÿ’ฐ

Architecture TLDR: ๐Ÿ—๏ธ

Architecture:

  1. PoolsNFT ๐ŸŽด - Enumerates all strategy pools. The gateway to the standardized interaction with strategy pools.
  2. PoolsNFTLens ๐Ÿ” - Lens contract that retrieves data from PoolsNFT and Strategies.
  3. URUS โš™๏ธ - Implements all URUS algorithm logic. Core of liquidity micromanagement
  4. Registry ๐Ÿ“š - Storage of quote tokens, base tokens, and oracles, grAI crosschain info.
  5. GRETH ๐Ÿช™ - ERC20 token that stands as incentivization for grind and implements the index of collected profit.
  6. Strategy ๐Ÿ“ˆ - Logic that utilizes URUS + interaction with onchain protocols like AAVE and Uniswap.
  7. StrategyFactory ๐Ÿญ - Factory that deploys ERC1967Proxy of Strategy as isolated smart contract with liquidity.
  8. GRAI ๐Ÿช™ - ERC20 token that tokenizes grinds on intent.
  9. GrinderAI ๐Ÿค– - Gateway for AI agent to interact with PoolsNFT and GRAI.

PoolsNFT ๐ŸŽด

PoolsNFT is a gateway that facilitates the creation of strategy pools and links represented by NFTs. It supports royalty mechanisms upon strategy profits, deposits, withdrawals, and strategy grinding.

Key Features โœจ

  • Pool Ownership: Each NFT represents ownership of a strategy pool. ๐Ÿฆ
  • Royalties: Configurable royalty system with shares for pool owners, grinders, and reserve funds on grETH token. ๐Ÿ’Ž
  • Deposits & Withdrawals: Supports token deposits and withdrawals while enforcing caps and minimum limits to trusted actors. ๐Ÿ’ณ
  • Profit Sharing: Distributes profits between participants of the strategy pool. ๐Ÿ“ค๐Ÿ“ฅ
  • Rebalancing: Enables efficient pool balancing across different strategies. โš–๏ธ
  • Royalty Trading: Allows users to buy royalty on strategy profits. ๐Ÿ›’

Core Functionalities ๐Ÿ› ๏ธ

  • Minting: Deploys a strategy pool and mints its NFT representation. ๐Ÿ–จ๏ธ
  • Grind Mechanism: Rewards users with grETH for maintaining pool strategies. ๐Ÿ…
  • Management: Flexible configuration of deposits, royalty shares, and pool limits. ๐Ÿ”ง

Roles ๐Ÿ›ก๏ธ

Owner Role ๐Ÿ‘‘

The owner has the highest level of authority in the contract and is responsible for administrative operations and configuration. ๐Ÿ› ๏ธ

Agent Role ๐Ÿค

The agent acts as a delegate for the pool owner, authorized to perform configuration of strategy parameters in URUS and rebalancing strategy pools owned by ownerOf. ๐Ÿ”„

Royalty Price Parameters ๐Ÿ’Ž

  • royaltyPriceInitNumerator: Determines the initial royalty price as a percentage of the deposited quote token. ๐Ÿ“Š
  • royaltyPriceCompensationShareNumerator: Share of the royalty price allocated as compensation to the previous owner. ๐Ÿ’ฐ
  • royaltyPriceReserveShareNumerator: Share allocated to the reserve. ๐Ÿฆ
  • royaltyPricePoolOwnerShareNumerator: Share allocated to the pool owner. ๐Ÿ 
  • royaltyPriceGrinderShareNumerator: Share allocated to the last grinder. ๐Ÿ…

grethShare Parameters ๐Ÿช™

  • grethGrinderShareNumerator: Share of the grinder reward allocated to the grinder (e.g., 80%). ๐Ÿ†
  • grethReserveShareNumerator: Share allocated to the reserve (e.g., 10%). ๐Ÿฆ
  • grethPoolOwnerShareNumerator: Share allocated to the pool owner (e.g., 5%). ๐Ÿ 
  • grethRoyaltyReceiverShareNumerator: Share allocated to the royalty receiver (e.g., 5%). ๐Ÿ’Ž

Royalty Parameters ๐Ÿ’ฐ

  • royaltyNumerator: Total royalty share of the profits (e.g., 20%). ๐Ÿ“ˆ
  • poolOwnerShareNumerator: Share of profits allocated to the pool owner (e.g., 80%). ๐Ÿ 
  • royaltyReceiverShareNumerator: Share of the royalty allocated to the royalty receiver (e.g., 10%). ๐Ÿ’Ž
  • royaltyReserveShareNumerator: Share allocated to the reserve on GRETH (e.g., 5%). ๐Ÿฆ
  • royaltyOwnerShareNumerator: Share allocated to the owner of the protocol (e.g., 5%). ๐Ÿ‘‘

Parameter Changes ๐Ÿ› ๏ธ

Owner-only functions ๐Ÿ‘‘

  • setPoolsNFTLens(address _poolsNFTLens) ๐Ÿ–ผ๏ธ: Set the PoolsNFTLens address.
  • setRoyaltyPriceInitNumerator(uint16 _royaltyPriceInitNumerator) ๐Ÿ’Ž: Set the royalty price initial numerator.
  • setRoyaltyPriceShares(...) ๐Ÿ“Š: Adjust royalty price shares.
  • setGRETHShares(...) ๐Ÿช™: Adjust GRETH share distributions.
  • setRoyaltyShares(...) ๐Ÿ’Ž: Adjust royalty distribution shares.
  • transferOwnership(address payable newOwner) ๐Ÿ”„: Transfer ownership to newOwner. Requires newOwner to call this function with the same parameter.
  • setStrategyFactory(address _strategyFactory) ๐Ÿญ: Set the strategy factory. Internally instantiates strategyFactoryId.
  • setStrategyStopped(uint16 strategyId, bool _isStrategyStopped) โ›”: Stop or resume the deployment of a strategy.
  • execute(address target, uint256 value, bytes memory data) ๐Ÿš€: Execute any transaction.

Mint Process ๐Ÿ–จ๏ธ

  • Use mint or mintTo to create a new isolated strategy pool:
    1. Specify strategyId, quoteToken, baseToken, and the initial amount of quoteToken. ๐Ÿช™
    2. Call the StrategyFactory, which deploys an ERC1967Proxy with the implementation of Strategy. ๐Ÿ—๏ธ
    3. Mint the corresponding NFT bound to the deployed ERC1967Proxy. ๐ŸŽด
    4. Transfer quoteToken from msg.sender to PoolsNFT. ๐Ÿ’ณ
    5. Call deposit on Strategy as a gateway. ๐Ÿ”‘

Deposit Process ๐Ÿ’ณ

  • Deposit quoteToken to a strategy pool with poolId:
    1. Check that msg.sender is the depositor of poolId. ๐Ÿ›ก๏ธ
    2. Ensure that quoteTokenAmount is within the bounds of minDeposit < quoteTokenAmount < maxDeposit. ๐Ÿ“
    3. Transfer quoteToken from msg.sender to PoolsNFT. ๐Ÿ’ฐ
    4. Call deposit on Strategy as a gateway. ๐Ÿ”‘

Deposit2 Process ๐Ÿ’ณ

  • Deposits baseToken with specified baseTokenPrice to strategy pool with poolId ๐Ÿฆ
    1. Checks that msg.sender is agent of poolId โœ…
    2. baseToken transfers from msg.sender to PoolsNFT ๐Ÿ”„
    3. Call deposit2 on Strategy as gateway ๐Ÿ”‘

Withdraw Process ๐Ÿง

  • Withdraw quoteToken from strategy pool with poolId ๐Ÿ’ต
    1. Checks that msg.sender is agent of poolId โœ…
    2. Call withdraw on Strategy as gateway ๐Ÿ”‘

Exit Process ๐Ÿšช

  • Withdraw all liquidity of quoteToken and baseToken from strategy pool with poolId ๐Ÿ’ธ
    1. Checks that msg.sender is agent of poolId โœ…
    2. Call exit on Strategy as gateway ๐Ÿ”‘

Set Agent Process ๐Ÿค

  • Sets agent of poolId ๐Ÿ› ๏ธ

Rebalance of Pools Process โš–๏ธ

  • Rebalance funds of two different strategy pools poolId0 and poolId1 with portions rebalance0 + rebalance1 ๐Ÿ”„
    1. Checks that owners of poolId0 and poolId1 are equal โœ…
    2. Checks that msg.sender is agent of poolId0 and poolId1. Owner of pool can be agent ๐Ÿค
    3. Call beforeRebalance on pools with poolId0 and poolId1 ๐Ÿ”ง
    4. PoolsNFT receives baseToken from poolId0 and poolId1 ๐Ÿ“ฅ
    5. Rebalance funds โš–๏ธ
    6. PoolsNFT approves transfer of baseToken โœ…
    7. Call afterRebalance on pools with poolId0 and poolId1 ๐Ÿ”ง

Grind Process ๐Ÿ› ๏ธ

  • Grind strategy with poolId:
    1. โœ… Checks that poolId has sufficient balance of quoteToken + baseToken.
    2. ๐Ÿ”„ Call grind on Strategy.
    3. ๐Ÿ… If the call is successful, the grinder earns grETH, equal to the spent transaction fee.

Buy Royalty Process ๐Ÿ’Ž

  • Buy royalty of poolId:
    1. ๐Ÿ“Š Calculate royalty shares.
    2. ๐Ÿ’ฐ msg.sender pays for the royalty.
    3. ๐Ÿ“ค PoolsNFT distributes shares.
    4. ๐Ÿ‘‘ msg.sender becomes the royalty receiver of poolId.

URUS โš™๏ธ

URUS is the core logic of the URUS trading algorithm. It is designed to handle automated trading, hedging, and rebalancing liqudity from quoteToken to baseToken and vise versa.

Key Features โœจ

  • Position Management: Supports long and hedge positions with configurable parameters. ๐Ÿ“ˆ๐Ÿ“‰
  • Profits Accountability: Tracks and distributes yield and trade profits for quoteToken and baseToken. ๐Ÿ’ต
  • Investment & Rebalancing: Handles liquidity management, token swaps, and holding through lending/liquidity protocols. ๐Ÿ”„

1. HelperData ๐Ÿงฐ

The HelperData struct contains metadata and dynamic parameters essential for the functionality of the URUS algorithm:

  • Token Decimals: Stores decimals for baseToken, quoteToken, and feeToken. ๐Ÿ”ข
  • Oracle Decimals: Stores decimals and multipliers for price oracles. ๐Ÿ“Š
  • Coefficient Multipliers: Constants for fee and percentage calculations. โš™๏ธ

2. Fee Token ๐Ÿช™

The feeToken is a utility token used to pay transaction fees during URUS operations. For most EVM chains, the fee token equals WETH (wrapped ETH). ๐ŸŒ

3. Quote Token ๐Ÿ’ต

The quoteToken is the primary unit of account and settlement for trades. It is used to:

  • Define the value of other tokens. ๐Ÿ“Š
  • Record liquidity and calculate profitability in terms of quoteToken. ๐Ÿ’ฐ

4. Base Token ๐Ÿช™

The baseToken is the asset being traded within the URUS strategy. For example, in an ETH/USDT trading pair:

  • baseToken: ETH ๐Ÿ› ๏ธ
  • quoteToken: USDT ๐Ÿ’ต

5.1 FeeConfig โš™๏ธ

The FeeConfig structure in the URUS contract defines parameters for calculating fees applied during trading operations. Unlike a fixed percentage, the fee coefficients (feeCoef) are multipliers applied to the sum of transaction fees, allowing dynamic scaling of fees for different operations. ๐Ÿ“ˆ

Definition:

struct FeeConfig {
    uint256 longSellFeeCoef;   // Fee coeficient for selling in a long position.
    uint256 hedgeSellFeeCoef;  // Fee coeficient for selling in a hedge position.
    uint256 hedgeRebuyFeeCoef; // Fee coeficient for rebuying during a hedge operation.
}

1. Fee Config: longSellFeeCoef ๐Ÿ’ฐ

  • Description: Coefficient used to calculate the fee for a long_sell operation. ๐Ÿ›’
  • Purpose: Covers additional protocol fees for selling a long position. ๐Ÿฆ
  • How It Works:
    • Multiplies the base transaction fee (feeQty) by longSellFeeCoef. ๐Ÿ”„
  • Example:
    • If feeQty = 50 (in feeToken) and longSellFeeCoef = 1_50: [ \text{Total Fee} = \frac{50 \times 1.50}{100} = 75 , \text{feeToken}. ] ๐Ÿงฎ

2. Fee Config: hedgeSellFeeCoef ๐Ÿ“‰

  • Description: Coefficient used to calculate the fee for a hedge_sell operation. ๐Ÿ”ง
  • Purpose: Ensures coverage of costs and rewards for selling during a hedge position. ๐Ÿ›ก๏ธ
  • How It Works:
    • Multiplies the base transaction fee (feeQty) by hedgeSellFeeCoef. ๐Ÿ”„
  • Example:
    • If feeQty = 30 (in feeToken) and hedgeSellFeeCoef = 2_00: [ \text{Total Fee} = \frac{30 \times 2.00}{100} = 60 , \text{feeToken}. ] ๐Ÿงฎ

3. Fee Config: hedgeRebuyFeeCoef ๐Ÿ”„

  • Description: Coefficient used to calculate the fee for a hedge_rebuy operation. ๐Ÿ’ต
  • Purpose: Covers costs associated with rebuying assets during a hedge position. ๐Ÿ› ๏ธ
  • How It Works:
    • Multiplies the base transaction fee (feeQty) by hedgeRebuyFeeCoef. ๐Ÿ”„
  • Example:
    • If feeQty = 40 (in feeToken) and hedgeRebuyFeeCoef = 1_75: [ \text{Total Fee} = \frac{40 \times 1.75}{100} = 70 , \text{feeToken}. ] ๐Ÿงฎ

Fee Calculation Process ๐Ÿงพ

Fees are calculated as follows:

  1. Determine the transaction fee (feeQty) in feeToken. This can include:
    • Gas costs in feeToken. โ›ฝ
    • Additional operational expenses. โš™๏ธ
  2. Apply the corresponding fee coefficient (feeCoef): ๐Ÿ”ข [ \text{Total Fee} = \frac{\text{feeQty} \times \text{feeCoef}}{\text{helper.coefMultiplier}} ] ๐Ÿงฎ

5.2 Config โš™๏ธ

The Config structure in the URUS contract defines critical parameters for the operation of the URUS algorithm. These parameters control the behavior of positions, thresholds, and profit margins during trading. Adjusting these values allows authorized roles to optimize the strategy for specific market conditions. ๐Ÿ“Š

Structure of Config ๐Ÿ—๏ธ

The Config structure contains the following parameters:

1. longNumberMax ๐Ÿ”ข

  • Description: The maximum number of buys that can be executed. ๐Ÿ›’
  • Purpose: Limits the exposure to long positions, ensuring controlled investment levels. ๐Ÿ›ก๏ธ
  • Example:
    • If longNumberMax = 4, a maximum of 4 sequential buys can be executed. ๐Ÿ”„
    • Scenario: Assume the following conditions:
      • Initial investment: 100 USDT ๐Ÿ’ต
      • extraCoef = 2_00 (x2.00) ๐Ÿ”ง
      • Long Number Max: 4 ๐Ÿ”ข
      • The investments would be:
        1. Buy amount on iteration 1: 100 USDT ๐Ÿ’ฐ
          Total investment: 100 USDT ๐Ÿ’ต
        2. Buy amount on iteration 2: 100 * 2.00 = 200 USDT ๐Ÿ’ฐ
          Total investment: 100 + 200 = 300 USDT ๐Ÿ’ต
        3. Buy amount on iteration 3: 300 * 2.00 = 600 USDT ๐Ÿ’ฐ
          Total investment: 300 + 600 = 900 USDT ๐Ÿ’ต
        4. Buy amount on iteration 4: 900 * 2.00 = 1800 USDT ๐Ÿ’ฐ
          Total investment: 900 + 1800 = 2700 USDT ๐Ÿ’ต

2. hedgeNumberMax ๐Ÿ›ก๏ธ

  • Description: The maximum number of hedge level grids. ๐Ÿ“‰
  • Purpose: Defines the depth level of hedging during adverse market movements. โš–๏ธ
  • Example:
    • If hedgeNumberMax = 3, the hedge process will stop after 3 iterations. โ›”
    • Scenario:
      • Total baseToken holdings: 16 units ๐Ÿช™
      • Hedge process splits positions:
        1. Hedge 1: 4 units ๐Ÿ›’
          Total sold: 4 units ๐Ÿ“ค
        2. Hedge 2: 4 units ๐Ÿ›’
          Total sold: 4 + 4 = 8 units ๐Ÿ“ค
        3. Hedge 3: 8 units ๐Ÿ›’
          Total sold: 8 + 8 = 16 units ๐Ÿ“ค
      • No further hedging will occur after 3 steps. The position is closed. ๐Ÿšช

3. extraCoef ๐Ÿ”„

  • Description: Multiplier used to calculate the additional liquidity required for subsequent long positions. ๐Ÿ“ˆ
  • Purpose: Ensures exponential growth of investments in long positions while maintaining proportional risk. โš™๏ธ

4. priceVolatilityPercent ๐ŸŒŠ

  • Description: The allowed price volatility percentage for position thresholds. ๐Ÿ“‰๐Ÿ“ˆ
  • Purpose: Helps define the acceptable range of price movements before triggering operations. ๐ŸŽฏ
  • Example:
    • If priceVolatilityPercent = 1_00 (1%): ๐Ÿ“Š
      • Long position threshold: If price drops by 1%, a buy order is triggered. ๐Ÿ›’
      • Scenario:
        • baseToken price: 1000 quoteToken/baseToken ๐Ÿ’ต
        • Volatility: 1% ๐ŸŒช๏ธ
        • Trigger price: 990 quoteToken/baseToken ๐Ÿ””

5. returnPercentLongSell ๐Ÿ’ฐ

  • Description: The required return percentage to execute a profitable long_sell. ๐Ÿ“ˆ
  • Purpose: Ensures that long positions are sold only when a certain profit margin is achieved. ๐Ÿฆ
  • Example:
    • If returnPercentLongSell = 100_50 (100.5%): ๐Ÿ“Š
      • A long_sell will only execute if the return is 0.5% or more above the initial investment. ๐Ÿ›๏ธ
      • Scenario:
        • Initial investment: $1,000 ๐Ÿ’ต
        • Required return: $1,005 (0.5% profit) ๐Ÿ†

7. returnPercentHedgeSell ๐Ÿ›ก๏ธ

  • Description: The required return percentage to execute a profitable hedge_sell. ๐Ÿ“‰
  • Purpose: Protects hedge positions by ensuring a minimum profit margin before selling. โš–๏ธ
  • Example:
    • If returnPercentHedgeSell = 100_50 (100.5%): ๐Ÿ“Š
      • A hedge_sell will only execute if the return is 0.5% or more above the investment. ๐Ÿ›’

8. returnPercentHedgeRebuy ๐Ÿ”„

  • Description: The required return percentage to execute a profitable hedge_rebuy. ๐Ÿ’ต
  • Purpose: Ensures that hedge positions are repurchased only when a certain profit margin is achievable. ๐Ÿฆ
  • Example:
    • If returnPercentHedgeRebuy = 100_50 (100.5%): ๐Ÿ“Š
      • A hedge_rebuy will only execute if the return is 0.5% or more. ๐Ÿ›๏ธ

Adjusting Config ๐Ÿ› ๏ธ

Changes to the Config structure can only be made by authorized roles, defined in Strategy:

  • setConfig(Config memory conf) ๐Ÿ› ๏ธ: Sets the entire configuration.
  • setLongNumberMax(uint8 longNumberMax) ๐Ÿ”ข: Sets the maximum number of long positions.
  • setHedgeNumberMax(uint8 hedgeNumberMax) ๐Ÿ›ก๏ธ: Sets the maximum number of levels of hedge positions.
  • setExtraCoef(uint256 extraCoef) ๐Ÿ”„: Sets the multiplier for liquidity calculations.
  • setPriceVolatilityPercent(uint256 priceVolatilityPercent) ๐ŸŒŠ: Sets the allowed price volatility.
  • setOpReturnPercent(uint8 op, uint256 returnPercent) ๐Ÿ“ˆ: Sets the return percentage for specific operations.

6. Long Position ๐Ÿ“ˆ

The long position tracks data related to buying and holding baseToken:

  • number ๐Ÿ”ข: Current long buys count.
  • numberMax ๐Ÿš€: Maximum allowed long buys.
  • priceMin ๐Ÿ“‰: Minimum allowable threshold price for baseToken purchases.
  • liquidity ๐Ÿ’ฐ: Quote token liquidity in the position.
  • qty ๐Ÿช™: Quantity of baseToken held.
  • price โš–๏ธ: Weighted average cost price.
  • feeQty ๐Ÿ’ต: Total fee quantity accrued in feeToken.
  • feePrice ๐Ÿ“Š: Fee price in terms of quoteToken.

7. Hedge Position ๐Ÿ›ก๏ธ

The hedge position tracks data for hedging against price declines:

  • number ๐Ÿ”ข: Current hedge position count.
  • numberMax ๐Ÿ›‘: Maximum allowed hedge positions.
  • priceMin ๐Ÿ“‰: Minimum price at which the hedge was initialized.
  • liquidity ๐Ÿ’ฐ: Quote token liquidity used in the hedge.
  • qty ๐Ÿช™: Quantity of baseToken hedged.
  • price โš–๏ธ: Hedge price.
  • feeQty ๐Ÿ’ต: Total fee quantity accrued in feeToken.
  • feePrice ๐Ÿ“Š: Fee price in terms of quoteToken.

8. How Deposit Works ๐Ÿ’ณ

  • Action: Deposit quoteToken into the strategy pool.
  • Steps:
    1. ๐Ÿ•’ Instantiate start timestamp.
    2. ๐Ÿ’ฐ quoteToken is transferred from the gateway.
    3. ๐Ÿ”„ Make an investment (calculate initialLiquidity).
    4. ๐Ÿฆ Put quoteToken into the lending protocol.

9. How Deposit2 Works ๐Ÿ’ณ

  • Action: Deposit baseToken with specified baseTokenPrice into the strategy pool.
  • Steps:
    1. โœ… Check that the long position is not bought or has used all liquidity.
    2. โœ… Check that liquidity is not hedged.
    3. ๐Ÿ’ฐ baseToken is transferred from the gateway.
    4. ๐Ÿฆ Put baseToken into the lending protocol.
    5. ๐Ÿ”„ Recalculate all position-related parameters.

10. How Deposit3 Works ๐Ÿ’ณ

  • Action: Deposit quoteToken into the strategy pool. ๐Ÿฆ
  • Steps:
  1. โœ… Check that the long position used all liquidity.
  2. ๐Ÿ›ก๏ธ Check that liquidity is not hedged.
  3. ๐Ÿ’ฐ quoteToken is transferred from the gateway.
  4. ๐Ÿ”„ Swap quoteToken to baseToken.
  5. ๐Ÿ—๏ธ Make an investment (recalculate initialLiquidity).
  6. ๐Ÿฆ Put baseToken into the lending protocol.
  7. ๐Ÿ“Š Recalculate all position-related parameters.

11. How Withdraw Works ๐Ÿง

  • Action: Withdraw quoteToken from the pool. ๐Ÿ’ต
  • Steps:
  1. โœ… Check that no liquidity is used.
  2. ๐Ÿ’ฐ Take quoteTokenAmount.
  3. ๐Ÿ“ค Transfer quoteTokenAmount to the withdrawer.

12. How Exit Works ๐Ÿšช

  • Action: Exit all positions and withdraw all assets. ๐Ÿ’ธ
  • Steps:
  1. ๐Ÿฆ Fetch all baseToken and quoteToken from lending protocols or fund storage.
  2. ๐Ÿ“ค Transfer tokens to the owner's address.
  3. ๐Ÿ”„ Reset long and hedge positions to their initial state.

13. How long_buy Works ๐Ÿ›’

  • Action: Executes a buy operation for baseToken in a long position. ๐Ÿ“ˆ
  • Steps:
  1. ๐Ÿงฎ Calculate the amount of quoteToken required.
  2. ๐Ÿ’ฐ Fetch quoteToken from lending protocols.
  3. ๐Ÿ”„ Swap quoteToken for baseToken on a DEX.
  4. ๐Ÿ“Š Update the long position with the new baseToken quantity and average price.

14. How long_sell Works ๐Ÿ›๏ธ

  • Action: Sells all baseToken from a long position. ๐Ÿ“‰
  • Steps:
  1. ๐Ÿฆ Fetch all baseToken from lending protocols.
  2. ๐Ÿ”„ Swap baseToken for quoteToken.
  3. โœ… Verify profitability based on thresholds.
  4. ๐Ÿ’ต Distribute profits and reset the long position.

15. How hedge_sell Works ๐Ÿ›ก๏ธ

  • Action: Sells baseToken to hedge against price declines. ๐Ÿ“‰
  • Steps:
    1. ๐Ÿงฎ Calculates the baseToken quantity to sell.
    2. ๐Ÿฆ Fetches baseToken from lending protocols.
    3. ๐Ÿ”„ Swaps baseToken for quoteToken on a DEX.
    4. ๐Ÿ“Š Updates the hedge position and adjusts the long position.

14. How hedge_rebuy Works ๐Ÿ”„

  • Action: Rebuys baseToken during a hedge position. ๐Ÿ“ˆ
  • Steps:
    1. ๐Ÿ’ฐ Uses quoteToken liquidity from the hedge position.
    2. ๐Ÿ”„ Swaps quoteToken for baseToken on a DEX.
    3. ๐Ÿ“Š Updates the long position with the re-bought quantity.
    4. ๐Ÿ› ๏ธ Resets the hedge position.

15. How grind Works ๐Ÿ”

  • Action: Executes the appropriate trading operation based on the current state. โš™๏ธ
  • Steps:
    1. ๐Ÿ›’ Calls long_buy if no positions exist.
    2. ๐Ÿ”„ Calls long_sell or long_buy if a long position is active.
    3. ๐Ÿ›ก๏ธ Calls hedge_sell or hedge_rebuy if hedging is active.

16. How beforeRebalance and afterRebalance Works โš–๏ธ

beforeRebalance:

  • Action: Prepares the strategy for rebalancing. ๐Ÿ› ๏ธ
  • Steps:
    1. ๐Ÿฆ Fetches all baseToken from lending protocols.
    2. ๐Ÿ”„ Transfers tokens to the rebalancing contract (gateway).
    3. ๐Ÿ“Š Adjusts the long position accordingly.

afterRebalance:

  • Action: Updates the strategy after rebalancing. ๐Ÿ”ง
  • Steps:
    1. ๐Ÿฆ Fetches rebalanced baseToken from the rebalancing contract.
    2. ๐Ÿ“Š Updates the long position with the new price and quantity.

grETH ๐Ÿช™

grETH is the yield index token, representing profits accumulated in strategy pools.

Share Calculation ๐Ÿ“Š

  • The share function calculates the proportional value of a specified amount of grETH in terms of a chosen asset (native or ERC-20 token). ๐Ÿ”„
  • Formula: (Liquidity * grETH Amount) / Total grETH Supply ๐Ÿงฎ

All ETH transfers to grETH are converted to WETH. ๐ŸŒ


๐Ÿ“š Registry Contract

The Registry contract is the metadata and configuration hub for the GrindURUS protocol. It maintains mappings between quote/base tokens, price oracles, strategy factories, and GRAI token configurations across chains. It also tracks token coherence for analytical and routing purposes.

๐Ÿง  Core Responsibilities

  • Stores oracle connections between token pairs.
  • Tracks all available quote and base tokens.
  • Registers strategies and LayerZero endpoint information for GRAI tokens.
  • Computes token coherence (used for assessing oracle coverage).
  • Delegates ownership rights dynamically to the PoolsNFT contract's owner.

โš™๏ธ Function Reference

๐Ÿ” Ownership & Access

  • owner() โ†’ Returns the current protocol owner via PoolsNFT.
  • _onlyOwner() โ†’ Reverts if caller is not owner.

๐Ÿงฉ Configuration

  • setPoolsNFT(address _poolsNFT)
    Set the reference address for the PoolsNFT contract.

  • setOracle(address quoteToken, address baseToken, address oracle)
    Set an oracle for a token pair and automatically deploy the inverse oracle.

  • unsetOracle(address quoteToken, address baseToken, address oracle)
    Remove an existing oracle mapping and clean up coherence tracking.

  • setStrategyInfo(uint16 strategyId, address factory, string description)
    Register a strategy with its factory and metadata.

  • setGRAIInfo(uint32 endpointId, address grai, string description)
    Register a GRAI token for a specific LayerZero endpoint.

๐Ÿงฎ Token Coherence

Token Coherence is a metric used in the Registry contract to quantify how well-connected a token is within the oracle graph of the GrindURUS protocol.

Each token is either a quote token or base token in an oracle pair. A token's coherence is defined as:

coherence(token) = number of oracle connections (excluding self-pairs)

For example, if token A has oracles with B, C, and D, then: coherence(A) = 3 (assuming A โ‰  B, C, D)


๐Ÿ” View Functions

๐Ÿ“ˆ Oracle Management

  • getOracle(address quoteToken, address baseToken)
    Get oracle for a given token pair. Returns PriceOracleSelf if quote == base.

  • hasOracle(address quoteToken, address baseToken)
    Returns true if oracle exists between the given pair.

๐Ÿช™ Token Lists

  • getQuoteTokens()
    Returns the list of all known quote tokens.

  • getBaseTokens()
    Returns the list of all known base tokens.

  • getQuoteTokensBy(uint256[] quoteTokenIds)
    Returns selected quote tokens by index.

  • getBaseTokensBy(uint256[] baseTokenIds)
    Returns selected base tokens by index.

๐Ÿง  Strategy Info

  • getStrategyInfosBy(uint16[] strategyIds)
    Batch query for StrategyInfo by IDs.

  • getGRAIInfosBy(uint32[] endpointIds)
    Batch query for GRAIInfo by endpoint IDs.


GRAI ๐Ÿช™

GRAI is the utility token of the GrindURUS protocol, burned when a grind is executed via GrinderAI. It is implemented as an Omnichain Fungible Token (OFT) using LayerZero and supports cross-chain usage.

GrinderAI-only Functions ๐Ÿค–

  • setMultiplierNumerator(uint256) โ€” Sets the multiplier for LayerZero fee estimation.
  • setNativeBridgeFee(uint256) โ€” Sets additional LayerZero bridge fee percentage.
  • setPeer(uint32, bytes32) โ€” Registers peer endpoint for cross-chain messaging.
  • mint(address, uint256) โ€” Mints GRAI tokens when grinds are purchased.

Bridging GRAI ๐ŸŒ‰

GRAI uses LayerZero infrastructure for bridging. ๐Ÿš€

How to Bridge ๐Ÿ›ค๏ธ

  1. Earn Estimation of Fee ๐Ÿงฎ
function getTotalFeesForBridgeTo(uint32 dstChainId, bytes32 toAddress, uint256 amount) external view returns (uint256 nativeFee, uint256 nativeBridgeFee, uint256 totalNativeFee);
  • This function calculates the total fees required for bridging, including native fees and bridge fees. ๐Ÿ’ต
  1. Call bridgeTo Function ๐Ÿ”„ Use the bridgeTo function with the value totalNativeFee obtained in step 1:
function bridgeTo(uint32 dstChainId, bytes32 toAddress, uint256 amount) external payable;

Parameters:

  1. dstChainId: Defined in graiInfos on the Registry. ๐ŸŒ
  2. toAddress: Encoded as a bytes32 address of the receiver. The peer is stored as a bytes32 to support non-EVM chains. ๐Ÿ“ฌ
  3. amount: The amount of GRAI to bridge. ๐Ÿช™

GrinderAI ๐Ÿค–

GrinderAI is the autonomous agent contract for the GrindURUS protocol. It enables gas-efficient, transparent automation of grind operations on strategy pools using the grAI utility token. It supports minting, payment processing, GRAI token management, and simulation of operations on pools.

๐Ÿ›  Configuration Functions

  • setRatePerGRAI(token, rate) โ€” Set price per grAI for a token.

๐ŸŒ grAI Cross-Chain Configuration Support

  • setLzReceivOptions(endpointId, gasLimit, value) โ€” Set LayerZero options.
  • setMultiplierNumerator(n) โ€” Adjust gas multiplier for fees.
  • setArtificialFeeNumerator(endpointId, n) โ€” Set additional bridge fee.
  • setPeer(eid, peer) โ€” Set remote peer for OFT sync.

๐Ÿ’ธ grAI Minting

  • mint(token, amount) โ€” Mint grAI to sender.
  • mintTo(token, to, amount) โ€” Mint grAI to another user.
  • ETH or tokens are accepted depending on ratePerGRAI.

โš™๏ธ Grinding

  • grind(poolId) โ€” Executes macro+micro grind on a pool.
  • grindOp(poolId, op) โ€” Executes a specific operation (buy, sell, etc).
  • batchGrind(poolIds[]) โ€” Batch of grind pools.
  • batchGrindOp(poolIds[], ops[]) โ€” Batch of granular grind ops.
  • microOp(poolId, op) / macroOp(poolId, op) โ€” Simulate operations.

๐Ÿ” View Functions

  • calcPayment(token, amount) โ€” Get payment needed to mint grAI.
  • getIntentOf(account) โ€” Return how many grinds the user has and pool ownership.
  • isPaymentToken(token) โ€” Check if token is valid for payment.
  • owner() โ€” Get dynamic owner (forwarded from PoolsNFT).

๐Ÿ“ฅ ETH Handling

When ETH is received: all ETH go to owner

Build

Initialize firstly .env

$ cp .env.example .env
$ forge build --sizes

Run Tests

$ forge test

Deployment

The deployment is implemented in scripts and handled by foundry framework.

Testing workablity of deployment

$ forge script script/DeployArbitrum.s.sol:DeployArbitrumScript

Apply .env

$ source .env

Arbitrum mainnet deployment

$ forge script script/DeployArbitrum.s.sol:DeployArbitrumScript --slow --broadcast --verify --verifier-url "https://api.arbiscan.io/api" --etherscan-api-key $ARBITRUMSCAN_API_KEY 

๐Ÿ“œ License

BUSL-1.1

About

cryptocurrency yield harvesting and trade protocol on EVM

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors