### Adapter Integration Example with CreditManagerV3 Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Demonstrates how an adapter can be integrated to perform actions on behalf of a credit account using CreditFacade's multicall. The adapter must be allowlisted. ```solidity /// @notice Example adapter pattern — adapter calls creditManager.execute() internally /// @dev This is called via CreditFacade's multicall dispatch to the adapter interface IExampleAdapter { /// @notice Swaps all account's tokenIn for tokenOut via target DEX function swapAllBalance(address tokenIn, address tokenOut, uint256 minOut) external; } // Usage in multicall (adapter must be allowlisted via CreditConfiguratorV3.allowAdapter) MultiCall[] memory calls = new MultiCall[](1); calls[0] = MultiCall({ target: allowedAdapter, // address of the registered adapter callData: abi.encodeCall(IExampleAdapter.swapAllBalance, (weth, usdc, minOut)) }); facade.multicall(creditAccount, calls); // Internally: CreditFacade → CreditManager.setActiveCreditAccount(creditAccount) // → adapter calls creditManager.execute(swapCalldata) // → creditAccount.execute(targetDex, swapCalldata) ``` -------------------------------- ### executeMulticall Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Executes a multicall to interact with DeFi protocols, manage debt, or update quota allocations atomically. This example demonstrates withdrawing WETH collateral, swapping on Curve, and updating quota. ```APIDOC ## executeMulticall ### Description Allows the account owner to interact with DeFi protocols through whitelisted adapters, manage debt, or update quota allocations — all atomically. ### Method `executeMulticall` ### Parameters - `facade` (ICreditFacadeV3) - The CreditFacadeV3 contract instance. - `creditAccount` (address) - The address of the credit account. - `curveAdapter` (address) - The address of the Curve adapter. - `wethToken` (address) - The address of the WETH token. ### Request Example ```solidity // Example usage within a contract or script // Assume facade, creditAccount, curveAdapter, wethToken are already defined // ICreditFacadeV3 facade = ...; // address creditAccount = ...; // address curveAdapter = ...; // address wethToken = ...; // executeMulticall(facade, creditAccount, curveAdapter, wethToken); ``` ### Response Emits `StartMultiCall`, `Execute`, and `FinishMultiCall` events upon successful execution. ``` -------------------------------- ### Get PoolV3 Statistics Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Retrieves pool utilization ratio, available liquidity, and borrowable amounts for a specific credit manager. Utilization is calculated as borrowed amount over expected liquidity. ```Solidity /// @notice Returns pool utilization ratio and borrowable amounts function getPoolStats(IPoolV3 pool, address creditManager) external view returns ( uint256 utilizationBps, uint256 available, uint256 managerBorrowable ) { uint256 expected = pool.expectedLiquidity(); // total deposits + accrued interest uint256 avail = pool.availableLiquidity(); // not currently borrowed uint256 borrowed = pool.totalBorrowed(); // Utilization = borrowed / expected (in bps) utilizationBps = expected > 0 ? (borrowed * 10_000) / expected : 0; available = avail; // How much this credit manager can still borrow managerBorrowable = pool.creditManagerBorrowable(creditManager); // = min(totalDebtLimit - totalBorrowed, managerDebtLimit - managerBorrowed) } ``` -------------------------------- ### Convert Token Amounts with PriceOracleV3 Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Utilize the protocol's price oracle to get token prices in USD, safe prices, and perform conversions between different token amounts and USD values. Requires an initialized PriceOracleV3 contract. ```Solidity import {IPriceOracleV3} from "@gearbox-protocol/core-v3/contracts/interfaces/IPriceOracleV3.sol"; /// @notice Convert token amounts using the protocol price oracle function getPrices(IPriceOracleV3 oracle, address wethToken, address usdcToken) external view { // Get USD price (in WAD, 1e18 = $1) uint256 wethPriceUSD = oracle.getPrice(wethToken); // e.g., 3500e18 = $3,500 uint256 safePrice = oracle.getSafePrice(wethToken); // min(main, reserve feed) // Convert 1 WETH to USDC uint256 wethInUSDC = oracle.convert(1e18, wethToken, usdcToken); // Convert WETH amount to USD (returns value in USD with 8 decimals) uint256 valueUSD = oracle.convertToUSD(2e18, wethToken); // 2 WETH in USD // Convert USD back to WETH uint256 wethAmount = oracle.convertFromUSD(7_000e8, wethToken); // $7,000 in WETH } ``` -------------------------------- ### Get Account Health Factor with CreditManagerV3 Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Calculates an account's health factor by reading its debt and collateral state. Requires importing ICreditManagerV3 and related structs/tasks. Handles zero debt cases. ```solidity import {ICreditManagerV3, CollateralDebtData, CollateralCalcTask} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditManagerV3.sol"; /// @notice Reads full debt/collateral state of a credit account function getAccountHealth(ICreditManagerV3 creditManager, address creditAccount) external view returns (bool isHealthy, uint256 healthFactor) { CollateralDebtData memory cdd = creditManager.calcDebtAndCollateral( creditAccount, CollateralCalcTask.DEBT_COLLATERAL // returns full collateral + debt info ); // Total debt = principal + accrued base interest + accrued quota interest + fees uint256 totalDebt = cdd.debt + cdd.accruedInterest + cdd.accruedFees; // Health factor = twvUSD / totalDebtUSD (in USD terms, RAY precision) if (cdd.totalDebtUSD > 0) { healthFactor = cdd.twvUSD * 10_000 / cdd.totalDebtUSD; // in bps, 10_000 = 100% isHealthy = healthFactor >= 10_000; } else { isHealthy = true; healthFactor = type(uint256).max; } } ``` -------------------------------- ### Pack and Unpack Quota/LT with CollateralLogic Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Demonstrates packing and unpacking quota and liquidation threshold (LT) into a single storage word using CollateralLogic. Useful for efficient storage. ```Solidity import {CollateralLogic} from "@gearbox-protocol/core-v3/contracts/libraries/CollateralLogic.sol"; /// @notice Pack/unpack quota and LT into a single storage word function packUnpackExample() external pure returns (uint256 quota, uint16 lt) { // Pack 50,000 USDC quota with 85% LT (8500 bps) uint256 packed = CollateralLogic.packQuota(50_000e6, 8500); // Unpack (quota, lt) = CollateralLogic.unpackQuota(packed); // quota = 50_000e6, lt = 8500 } ``` -------------------------------- ### Configure Collateral Tokens with CreditConfiguratorV3 Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Add new collateral tokens, set their liquidation thresholds (with optional ramp-up periods), allow specific DEX adapters, and adjust borrowing limits. Requires an initialized CreditConfiguratorV3 contract. ```Solidity import {ICreditConfiguratorV3} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditConfiguratorV3.sol"; /// @notice Add a new collateral token and configure its liquidation threshold with a ramp function configureCollateral( ICreditConfiguratorV3 configurator, address wbtcToken, address newAdapter, address targetDex ) external { // Add WBTC as recognized collateral with LT = 85% (8500 bps) configurator.addCollateralToken(wbtcToken, 8500); // emits AddCollateralToken(wbtcToken), SetTokenLiquidationThreshold(wbtcToken, 8500) // Schedule LT ramp: from 85% to 80% over 30 days starting now configurator.rampLiquidationThreshold( wbtcToken, 8000, // ltFinal (80%) uint40(block.timestamp), // rampStart uint24(30 days) // rampDuration ); // emits ScheduleTokenLiquidationThresholdRamp(...) // Whitelist a new adapter for a DEX configurator.allowAdapter(newAdapter); // emits AllowAdapter(targetDex, newAdapter) // Update debt limits: min 1,000 USDC, max 1,000,000 USDC configurator.setDebtLimits(1_000e6, 1_000_000e6); // emits SetBorrowingLimits(1_000e6, 1_000_000e6) } ``` -------------------------------- ### Demonstrate Bitmask Operations for Token Management Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Showcases BitMask library utilities for enabling, disabling, and counting tokens represented by a uint256 bitmask. Useful for managing token sets efficiently. ```Solidity import {BitMask} from "@gearbox-protocol/core-v3/contracts/libraries/BitMask.sol"; /// @notice Demonstrate bitmask operations for token management function bitmaskDemo() external pure returns (uint256) { uint256 enabledTokens = 0; // Token masks: token0=1, token1=2, token2=4 uint256 token0Mask = 1 << 0; // = 1 uint256 token1Mask = 1 << 1; // = 2 uint256 token2Mask = 1 << 2; // = 4 // Enable token0 and token1 enabledTokens = BitMask.enable(enabledTokens, token0Mask); enabledTokens = BitMask.enable(enabledTokens, token1Mask); // enabledTokens = 0b011 = 3 // Count enabled tokens uint256 count = BitMask.calcEnabledTokens(enabledTokens); // = 2 // Enable token2, disable token0 in one step enabledTokens = BitMask.enableDisable(enabledTokens, token2Mask, token0Mask); // enabledTokens = 0b110 = 6 // Iterate using LSB uint256 lsb = BitMask.lsbMask(enabledTokens); // = 2 (token1) enabledTokens = BitMask.disable(enabledTokens, lsb); // remove token1 // enabledTokens = 0b100 = 4 (only token2) return enabledTokens; } ``` -------------------------------- ### Open a Credit Account with Multicalls Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Use `openCreditAccount` to create a new Credit Account. The `calls` parameter allows for atomic execution of operations like adding collateral and borrowing funds immediately after account creation. ```Solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.17; import {ICreditFacadeV3} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditFacadeV3.sol"; import {ICreditFacadeV3Multicall} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditFacadeV3Multicall.sol"; import {MultiCall} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditFacadeV3.sol"; contract OpenAccountExample { ICreditFacadeV3 public immutable facade; constructor(address _facade) { facade = ICreditFacadeV3(_facade); } /// @notice Opens a credit account, borrows 10,000 USDC, adds 1,000 USDC collateral function openLeveragedPosition(address usdcToken, uint256 collateralAmount) external { // Build multicall: add collateral then increase debt MultiCall[] memory calls = new MultiCall[](2); // Step 1: Add 1,000 USDC as collateral (caller must approve creditManager first) calls[0] = MultiCall({ target: address(facade), callData: abi.encodeCall(ICreditFacadeV3Multicall.addCollateral, (usdcToken, collateralAmount)) }); // Step 2: Borrow 10,000 USDC from the pool calls[1] = MultiCall({ target: address(facade), callData: abi.encodeCall(ICreditFacadeV3Multicall.increaseDebt, (10_000e6)) }); // Open account — emits OpenCreditAccount(creditAccount, onBehalfOf, caller, referralCode) address creditAccount = facade.openCreditAccount( msg.sender, // onBehalfOf calls, 0 // referralCode ); // creditAccount now holds 11,000 USDC (1,000 own + 10,000 borrowed) } } ``` -------------------------------- ### CollateralLogic - packUnpackExample Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Demonstrates the usage of `packQuota` and `unpackQuota` functions from the CollateralLogic library. These functions are used to efficiently store and retrieve collateral quota and liquidation threshold (LT) values. ```APIDOC ## CollateralLogic Library — Collateral Value Calculation `CollateralLogic` computes USD-denominated total value and threshold-weighted value (TWV) of a credit account's token holdings, used directly during collateral checks. ### Function: packUnpackExample #### Description This example function demonstrates how to pack collateral quota and liquidation threshold (LT) into a single `uint256` storage word using `CollateralLogic.packQuota`, and then unpack them back using `CollateralLogic.unpackQuota`. #### Returns - `quota` (uint256) - The unpacked collateral quota value. - `lt` (uint16) - The unpacked liquidation threshold value. #### Example Usage Packing a 50,000 USDC quota with an 85% LT (represented as 8500 bps). ```solidity // Pack 50,000 USDC quota with 85% LT (8500 bps) // uint256 packed = CollateralLogic.packQuota(50_000e6, 8500); // Unpack the values // (uint256 quota, uint16 lt) = CollateralLogic.unpackQuota(packed); // Expected: quota = 50_000e6, lt = 8500 ``` ``` -------------------------------- ### BotListV3 - manageBotAccess Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Demonstrates how to manage bot access and permissions for a credit account using the BotListV3 contract. It includes checking bot status, handling forbidden bots, and setting specific permissions. ```APIDOC ## BotListV3 — Automated Bot Permissions `BotListV3` is a permissioned registry that maps bots to the credit accounts they are authorized to manage, with a bitmask encoding the specific operations allowed. ### Function: manageBotAccess #### Description This function demonstrates checking and managing bot authorization for a credit account. It retrieves the bot's current permissions and forbidden status, reverts if the bot is globally forbidden, and shows how to set new permissions. #### Parameters - `botList` (IBotListV3) - The BotListV3 contract instance. - `creditAccount` (address) - The credit account address. - `myBot` (address) - The bot address. #### Logic 1. Retrieves permissions and forbidden status using `botList.getBotStatus(myBot, creditAccount)`. 2. Reverts if `isForbidden` is true. 3. Lists active bots for the account using `botList.activeBots(creditAccount)`. 4. Sets new permissions (e.g., ADD_COLLATERAL_PERMISSION | DECREASE_DEBT_PERMISSION) using `botList.setBotPermissions` (commented out in example, typically called via multicall). #### Example Usage (Conceptual) ```solidity // Assuming botList, creditAccount, and myBot are defined // (permissions, isForbidden) = botList.getBotStatus(myBot, creditAccount); // if (!isForbidden) { // uint192 newPermissions = (1 << 0) | (1 << 2); // Example permissions // // botList.setBotPermissions(myBot, creditAccount, newPermissions); // } ``` ``` -------------------------------- ### Read IRM Parameters and Calculate Borrow Rate Source: https://context7.com/gearbox-protocol/core-v3/llms.txt This snippet demonstrates how to query model parameters and compute the borrow rate using the ILinearInterestRateModelV3 interface. Ensure the ILinearInterestRateModelV3 contract is correctly imported and instantiated. ```solidity import {ILinearInterestRateModelV3} from "@gearbox-protocol/core-v3/contracts/interfaces/ILinearInterestRateModelV3.sol"; /// @notice Query borrow rate and model parameters function readIRM(ILinearInterestRateModelV3 irm) external view { // Read model parameters (all in bps) ( uint16 U_1, // first optimal utilization point, e.g., 7000 = 70% uint16 U_2, // second optimal utilization point, e.g., 9000 = 90% uint16 R_base, // base rate at 0% utilization uint16 R_slope1, // rate slope from 0 to U_1 uint16 R_slope2, // rate slope from U_1 to U_2 uint16 R_slope3 // steep slope above U_2 ) = irm.getModelParameters(); // Compute borrow rate at 80% utilization // expectedLiquidity = 100e18, availableLiquidity = 20e18 → utilization = 80% uint256 rate = irm.calcBorrowRate( 100e18, // expectedLiquidity 20e18, // availableLiquidity false // checkOptimalBorrowing (revert if above U2 when true) ); // Returns rate in RAY (1e27), e.g. 5e25 = 5% APR } ``` -------------------------------- ### Manage Bot Access with BotListV3 Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Check and manage bot authorization for a credit account. Ensure the bot is not globally forbidden before setting permissions. ```Solidity import {IBotListV3} from "@gearbox-protocol/core-v3/contracts/interfaces/IBotListV3.sol"; /// @notice Check and manage bot authorization for a credit account function manageBotAccess( IBotListV3 botList, address creditAccount, address myBot ) external { // Check current permissions and forbidden status (uint192 permissions, bool isForbidden) = botList.getBotStatus(myBot, creditAccount); // permissions is a bitmask: bit 0 = ADD_COLLATERAL, bit 2 = DECREASE_DEBT, etc. if (isForbidden) revert("Bot is globally forbidden"); // List all active bots for this account address[] memory bots = botList.activeBots(creditAccount); // Grant bot specific permissions (called by account owner via facade.multicall) // permissions: ADD_COLLATERAL_PERMISSION | DECREASE_DEBT_PERMISSION uint192 newPermissions = (1 << 0) | (1 << 2); // This is called internally by CreditFacadeV3 when setBotPermissions is in a multicall // uint256 remaining = botList.setBotPermissions(myBot, creditAccount, newPermissions); } ``` -------------------------------- ### PoolV3 — Liquidity and Debt Queries Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Provides functions to query the pool's utilization ratio, available liquidity, and borrow limits for credit managers. ```APIDOC ## PoolV3 — Liquidity and Debt Queries Key read functions expose pool utilization, available liquidity, and per-credit-manager borrow limits. ### Function Signature ```solidity function getPoolStats(IPoolV3 pool, address creditManager) external view returns (uint256 utilizationBps, uint256 available, uint256 managerBorrowable) ``` ### Description Retrieves statistics about the pool's current state, including utilization, available liquidity, and the amount a specific credit manager can still borrow. ### Parameters - **pool** (IPoolV3) - The PoolV3 contract instance. - **creditManager** (address) - The address of the credit manager to query borrow limits for. ### Returns - **utilizationBps** (uint256) - The pool utilization ratio in basis points (bps). - **available** (uint256) - The amount of liquidity currently available in the pool. - **managerBorrowable** (uint256) - The amount the specified credit manager can still borrow. ``` -------------------------------- ### Simulate Accrued Interest with CreditLogic Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Off-chain simulation of accrued interest calculation using debt principal and cumulative interest indexes. Useful for estimating debt growth. ```Solidity import {CreditLogic} from "@gearbox-protocol/core-v3/contracts/libraries/CreditLogic.sol"; import {CollateralDebtData} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditManagerV3.sol"; /// @notice Off-chain simulation of accrued interest and liquidation payout function simulateAccruedInterest( uint256 debtPrincipal, uint256 cumulativeIndexAtOpen, // e.g., 1.05e27 uint256 cumulativeIndexNow // e.g., 1.08e27 ) external pure returns (uint256 accrued) { // accrued = debt * (indexNow / indexAtOpen) - debt accrued = CreditLogic.calcAccruedInterest(debtPrincipal, cumulativeIndexAtOpen, cumulativeIndexNow); // For 10,000 USDC debt: accrued = 10000e6 * 1.08e27 / 1.05e27 - 10000e6 ≈ 285.7 USDC } ``` -------------------------------- ### Vote for WETH Quota Rate in GaugeV3 Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Demonstrates how to read quota rate voting parameters and current effective rates for WETH. Votes are cast via GearStakingV3, not directly to GaugeV3. ```Solidity import {IGaugeV3} from "@gearbox-protocol/core-v3/contracts/interfaces/IGaugeV3.sol"; /// @notice Cast votes to set WETH quota rate (called via GearStakingV3.multivote) /// @dev Votes are submitted through GearStakingV3, not directly to GaugeV3 function voteForWethRate( IGaugeV3 gauge, address wethToken ) external view { // Read current vote distribution for WETH (uint16 minRate, uint16 maxRate, uint96 totalVotesLp, uint96 totalVotesCa) = gauge.quotaRateParams(wethToken); // minRate / maxRate are in bps (e.g., 100 = 1%) // Get current computed rates for multiple tokens address[] memory tokens = new address[](1); tokens[0] = wethToken; uint16[] memory rates = gauge.getRates(tokens); // rates[0] = current effective quota rate for WETH in bps // Read an individual user's votes (uint96 votesLpSide, uint96 votesCaSide) = gauge.userTokenVotes(msg.sender, wethToken); } ``` -------------------------------- ### CreditConfiguratorV3 — Configure Collateral Tokens Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Manages risk parameters for collateral tokens, including adding new tokens, setting liquidation thresholds with optional ramps, and whitelisting adapters. ```APIDOC ## CreditConfiguratorV3 — Configure Collateral Tokens `CreditConfiguratorV3` is the governance interface for risk management: adding collateral tokens, setting liquidation thresholds (with optional ramping), enabling adapters, and adjusting fee parameters. ### Function: `configureCollateral` #### Description Adds a new collateral token, configures its liquidation threshold with an optional ramp, whitelists a new adapter for a DEX, and updates debt limits. #### Parameters - `configurator` (ICreditConfiguratorV3): The credit configurator contract instance. - `wbtcToken` (address): The address of the WBTC token. - `newAdapter` (address): The address of the new adapter to whitelist. - `targetDex` (address): The address of the target DEX. #### Example Usage ```solidity // Add WBTC as recognized collateral with LT = 85% (8500 bps) configurator.addCollateralToken(wbtcToken, 8500); // Schedule LT ramp: from 85% to 80% over 30 days starting now configurator.rampLiquidationThreshold( wbtcToken, 8000, // ltFinal (80%) uint40(block.timestamp), // rampStart uint24(30 days) // rampDuration ); // Whitelist a new adapter for a DEX configurator.allowAdapter(newAdapter); // Update debt limits: min 1,000 USDC, max 1,000,000 USDC configurator.setDebtLimits(1_000e6, 1_000_000e6); ``` #### Events Emitted - `AddCollateralToken(wbtcToken)` - `SetTokenLiquidationThreshold(wbtcToken, 8500)` - `ScheduleTokenLiquidationThresholdRamp(...)` - `AllowAdapter(targetDex, newAdapter)` - `SetBorrowingLimits(1_000e6, 1_000_000e6)` ``` -------------------------------- ### Open a Credit Account Source: https://context7.com/gearbox-protocol/core-v3/llms.txt The `openCreditAccount` function creates a new leveraged Credit Account. It supports an atomic multicall array (`calls`) that can be used to perform immediate actions like borrowing funds, adding collateral, and executing other DeFi operations in a single transaction. ```APIDOC ## CreditFacadeV3 - openCreditAccount ### Description Creates a new leveraged Credit Account and optionally executes a series of predefined calls immediately after. ### Method `openCreditAccount(address onBehalfOf, MultiCall[] memory calls, uint16 referralCode)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **onBehalfOf** (address) - The address that will own the credit account. - **calls** (MultiCall[]) - An array of `MultiCall` structs, each containing a `target` address and `callData` for an atomic operation to be executed after account creation. - **referralCode** (uint16) - A referral code for tracking. ### Request Example ```solidity // Example usage within a contract address creditAccount = facade.openCreditAccount(msg.sender, calls, 0); ``` ### Response #### Success Response (200) - **creditAccount** (address) - The address of the newly created credit account. #### Response Example (No explicit response example provided in source, but the function returns the credit account address.) ### Errors (No specific error handling documented in source.) ``` -------------------------------- ### BitMask - bitmaskDemo Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Illustrates various operations provided by the BitMask library for managing sets of enabled tokens using a `uint256` bitmask. Operations include enabling, disabling, counting, and iterating through enabled tokens. ```APIDOC ## BitMask Library — Token Set Operations `BitMask` provides efficient bit-manipulation utilities for managing sets of enabled tokens on credit accounts using a `uint256` bitmask. ### Function: bitmaskDemo #### Description This function demonstrates common operations using the `BitMask` library, including enabling tokens, disabling tokens, counting the number of enabled tokens, and iterating through enabled tokens using the least significant bit (LSB). #### Returns - `enabledTokens` (uint256) - The final state of the bitmask after all operations. #### Operations Demonstrated 1. **Initialization**: `uint256 enabledTokens = 0;` 2. **Token Masks**: Defining masks for individual tokens (e.g., `token0Mask = 1 << 0`). 3. **Enable**: `BitMask.enable(enabledTokens, tokenMask)` to add tokens to the set. 4. **Count**: `BitMask.calcEnabledTokens(enabledTokens)` to get the number of set bits. 5. **Enable/Disable**: `BitMask.enableDisable(enabledTokens, enableMask, disableMask)` for combined operations. 6. **LSB Iteration**: Using `BitMask.lsbMask(enabledTokens)` to find the least significant bit and `BitMask.disable(enabledTokens, lsbMask)` to remove it. #### Example Walkthrough - Start with `enabledTokens = 0`. - Enable token0 (mask 1) and token1 (mask 2), resulting in `enabledTokens = 3` (binary `0b11`). - Count enabled tokens: `calcEnabledTokens(3)` returns 2. - Enable token2 (mask 4) and disable token0 (mask 1) simultaneously: `enableDisable(3, 4, 1)` results in `enabledTokens = 6` (binary `0b110`). - Find LSB (token1, mask 2), remove it: `lsbMask(6)` returns 2, `disable(6, 2)` results in `enabledTokens = 4` (binary `0b100`). ```solidity // uint256 enabledTokens = bitmaskDemo(); // Returns the final state of enabledTokens, which is 4 in the example. ``` ``` -------------------------------- ### Execute Multicall on Existing Account Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Use this function to atomically perform multiple operations like withdrawing collateral, swapping tokens via adapters, and updating account parameters. Ensure the facade and credit account are correctly initialized. ```solidity function executeMulticall( ICreditFacadeV3 facade, address creditAccount, address curveAdapter, address wethToken ) external { MultiCall[] memory calls = new MultiCall[](3); // Update quota for WETH (enable it as collateral by allocating 5,000 USD of quota) calls[0] = MultiCall({ target: address(facade), callData: abi.encodeCall(ICreditFacadeV3Multicall.updateQuota, (wethToken, int96(5_000e6), 0)) }); // Set health-factor floor at 110% (10_000 bps = 100%) calls[1] = MultiCall({ target: address(facade), callData: abi.encodeCall( ICreditFacadeV3Multicall.setFullCheckParams, (new uint256[](0), 11_000) // minHealthFactor in bps ) }); // Call Curve adapter — swap 1 ETH to stETH calls[2] = MultiCall({ target: curveAdapter, callData: abi.encodeWithSignature("exchange(int128,int128,uint256,uint256)", 0, 1, 1e18, 0) }); // Execute — emits StartMultiCall, Execute, FinishMultiCall facade.multicall(creditAccount, calls); } ``` -------------------------------- ### GearStakingV3 — Stake GEAR and Vote Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Allows users to deposit GEAR tokens to gain voting power and simultaneously vote for specific quota rates on LP sides. It also demonstrates scheduling withdrawals and claiming them. ```APIDOC ## GearStakingV3 — Stake GEAR and Vote `GearStakingV3` is the governance staking contract where users lock GEAR tokens to gain voting power over quota rates in `GaugeV3` and other voting contracts. ### Function: `stakeAndVote` #### Description Deposits GEAR tokens and immediately votes for a specified quota rate. It also demonstrates scheduling a withdrawal and claiming it. #### Parameters - `staking` (IGearStakingV3): The staking contract instance. - `gaugeAddress` (address): The address of the gauge contract. - `wethToken` (address): The address of the WETH token. - `gearAmount` (uint96): The amount of GEAR tokens to deposit and withdraw. #### Example Usage ```solidity // Build vote: direct 500 GEAR to LP side (higher rates) for WETH MultiVote[] memory votes = new MultiVote[](1); votes[0] = MultiVote({ votingContract: gaugeAddress, voteAmount: 500e18, isIncrease: true, extraData: abi.encode(wethToken, true) // token, lpSide=true }); // Deposit 1,000 GEAR and apply votes atomically staking.deposit(gearAmount, votes); // Schedule withdrawal (subject to EPOCHS_TO_WITHDRAW delay) staking.withdraw(gearAmount, msg.sender, new MultiVote[](0)); // After enough epochs, claim: staking.claimWithdrawals(msg.sender); ``` #### Events Emitted - `DepositGear(user, gearAmount)` - `Vote(user, wethToken, 500e18, true)` - `ScheduleGearWithdrawal(user, gearAmount)` - `ClaimGearWithdrawal(user, to, amount)` ``` -------------------------------- ### CreditConfiguratorV3 — Fee Configuration Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Configures various fee parameters related to liquidations and interest collection, and allows for emergency borrowing restrictions. ```APIDOC ## CreditConfiguratorV3 — Fee Configuration Fee parameters control the economics of liquidation and interest collection across the credit market. ### Function: `updateFees` #### Description Updates protocol fee parameters, allows for emergency pausing of borrowing, and setting a custom loss policy contract. #### Parameters - `configurator` (ICreditConfiguratorV3): The credit configurator contract instance. #### Example Usage ```solidity configurator.setFees( 200, // feeLiquidation: 2% fee on collateral taken by DAO on liquidation 500, // liquidationPremium: 5% bonus for liquidators 100, // feeLiquidationExpired: 1% fee on expired credit account liquidation 200 // liquidationPremiumExpired: 2% liquidator bonus for expired accounts ); // Block any new borrowing (emergency pause of debt increases) configurator.forbidBorrowing(); // Set a custom loss policy contract to handle bad debt scenarios configurator.setLossPolicy(0xNewLossPolicyAddress); ``` #### Events Emitted - `UpdateFees(200, 500, 100, 200)` - `SetLossPolicy(0xNewLossPolicyAddress)` ``` -------------------------------- ### Grant Bot Permissions with CreditFacadeV3Multicall Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Grants a bot specific permissions (ADD_COLLATERAL, DECREASE_DEBT) to manage an account via multicall. Ensure the facade is correctly initialized and the bot is whitelisted. ```solidity /// @notice Grants a bot permission to add collateral and decrease debt on an account function grantBotPermissions( ICreditFacadeV3 facade, address creditAccount, address bot ) external { // Permission bitmask: ADD_COLLATERAL (1<<0) | DECREASE_DEBT (1<<2) uint192 permissions = (1 << 0) | (1 << 2); MultiCall[] memory calls = new MultiCall[](1); calls[0] = MultiCall({ target: address(facade), callData: abi.encodeCall(ICreditFacadeV3Multicall.setBotPermissions, (bot, permissions)) }); facade.multicall(creditAccount, calls); // Bot can now call facade.botMulticall(creditAccount, ...) with ADD_COLLATERAL + DECREASE_DEBT ops } ``` -------------------------------- ### addCollateralWithPermit Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Adds tokens to a credit account using a gasless EIP-2612 permit signature, eliminating the need for a prior `approve` call. ```APIDOC ## addCollateralWithPermit ### Description Adds collateral to a credit account using an EIP-2612 permit, allowing for gasless approvals. ### Method `addCollateralWithPermit` ### Parameters - `facade` (ICreditFacadeV3) - The CreditFacadeV3 contract instance. - `creditAccount` (address) - The address of the credit account. - `usdcToken` (address) - The address of the USDC token to add as collateral. - `amount` (uint256) - The amount of tokens to add. - `deadline` (uint256) - The EIP-2612 permit deadline. - `v` (uint8) - The ECDSA recovery byte `v`. - `r` (bytes32) - The ECDSA recovery byte `r`. - `s` (bytes32) - The ECDSA recovery byte `s`. ### Request Example ```solidity // Example usage within a contract or script // Assume facade, creditAccount, usdcToken are defined // ICreditFacadeV3 facade = ...; // address creditAccount = ...; // address usdcToken = ...; // uint256 amount = 1000e6; // 1,000 USDC // uint256 deadline = block.timestamp + 3600; // Permit valid for 1 hour // uint8 v, bytes32 r, bytes32 s; // Obtain v, r, s from a signed permit message // addCollateralPermit(facade, creditAccount, usdcToken, amount, deadline, v, r, s); ``` ### Response Emits `AddCollateral` event with parameters `creditAccount`, `usdcToken`, and `amount`. ``` -------------------------------- ### Stake GEAR and Vote with GearStakingV3 Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Deposit GEAR tokens to gain voting power and simultaneously vote on quota rates. This function also schedules a withdrawal and claims pending withdrawals. ```Solidity import {IGearStakingV3, MultiVote} from "@gearbox-protocol/core-v3/contracts/interfaces/IGearStakingV3.sol"; /// @notice Deposit GEAR and immediately vote for WETH quota rate on LP side function stakeAndVote( IGearStakingV3 staking, address gaugeAddress, address wethToken, uint96 gearAmount ) external { // Build vote: direct 500 GEAR to LP side (higher rates) for WETH MultiVote[] memory votes = new MultiVote[](1); votes[0] = MultiVote({ votingContract: gaugeAddress, voteAmount: 500e18, isIncrease: true, extraData: abi.encode(wethToken, true) // token, lpSide=true }); // Deposit 1,000 GEAR and apply votes atomically // emits DepositGear(user, gearAmount), Vote(user, wethToken, 500e18, true) staking.deposit(gearAmount, votes); // Schedule withdrawal (subject to EPOCHS_TO_WITHDRAW delay) staking.withdraw(gearAmount, msg.sender, new MultiVote[](0)); // emits ScheduleGearWithdrawal(user, gearAmount) // After enough epochs, claim: staking.claimWithdrawals(msg.sender); // emits ClaimGearWithdrawal(user, to, amount) } ``` -------------------------------- ### Add Collateral with EIP-2612 Permit Source: https://context7.com/gearbox-protocol/core-v3/llms.txt This function allows adding collateral to a credit account using an EIP-2612 permit signature, avoiding the need for a prior `approve` transaction. Ensure the permit details (deadline, v, r, s) are valid. ```solidity function addCollateralPermit( ICreditFacadeV3 facade, address creditAccount, address usdcToken, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { MultiCall[] memory calls = new MultiCall[](1); calls[0] = MultiCall({ target: address(facade), callData: abi.encodeCall( ICreditFacadeV3Multicall.addCollateralWithPermit, (usdcToken, amount, deadline, v, r, s) ) }); // Execute in existing account's multicall facade.multicall(creditAccount, calls); // emits AddCollateral(creditAccount, usdcToken, amount) } ``` -------------------------------- ### Update Fee Parameters with CreditConfiguratorV3 Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Adjust protocol fee parameters including liquidation fees, liquidator bonuses, and expired account fees. This function can also be used to forbid borrowing or set a custom loss policy contract. ```Solidity /// @notice Update protocol fee parameters function updateFees(ICreditConfiguratorV3 configurator) external { configurator.setFees( 200, // feeLiquidation: 2% fee on collateral taken by DAO on liquidation 500, // liquidationPremium: 5% bonus for liquidators 100, // feeLiquidationExpired: 1% fee on expired credit account liquidation 200 // liquidationPremiumExpired: 2% liquidator bonus for expired accounts ); // emits UpdateFees(200, 500, 100, 200) // Block any new borrowing (emergency pause of debt increases) configurator.forbidBorrowing(); // Set a custom loss policy contract to handle bad debt scenarios configurator.setLossPolicy(0xNewLossPolicyAddress); // emits SetLossPolicy(0xNewLossPolicyAddress) } ``` -------------------------------- ### CreditLogic - simulateAccruedInterest Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Provides an off-chain simulation for calculating accrued interest on a debt. This function uses the CreditLogic library to compute the interest based on principal, initial, and current cumulative interest indexes. ```APIDOC ## CreditLogic Library — Accrued Interest Calculation `CreditLogic` is the core math library for computing debt growth, interest accrual, and liquidation payment splits. ### Function: simulateAccruedInterest #### Description This function simulates the accrued interest on a given debt principal. It takes the principal amount and the cumulative interest indexes at the time of opening and the current time to calculate the interest accrued. #### Parameters - `debtPrincipal` (uint256) - The principal amount of the debt. - `cumulativeIndexAtOpen` (uint256) - The cumulative interest index when the debt was opened (e.g., 1.05e27). - `cumulativeIndexNow` (uint256) - The current cumulative interest index (e.g., 1.08e27). #### Returns - `accrued` (uint256) - The calculated accrued interest. #### Example Calculation For a debt of 10,000 USDC with `cumulativeIndexAtOpen` = 1.05e27 and `cumulativeIndexNow` = 1.08e27, the accrued interest is approximately 285.7 USDC. ```solidity // Example call: // uint256 accruedInterest = CreditLogic.calcAccruedInterest(10000e6, 1.05e27, 1.08e27); ``` ``` -------------------------------- ### Simulate Debt Increase with CreditLogic Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Simulate the new cumulative index after increasing debt. This function recalculates the cumulative index to preserve previously accrued interest. ```Solidity import {CreditLogic} from "@gearbox-protocol/core-v3/contracts/libraries/CreditLogic.sol"; import {CollateralDebtData} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditManagerV3.sol"; /// @notice Simulate new cumulative index after increasing debt function simulateIncrease( uint256 addAmount, uint256 currentDebt, uint256 cumulativeIndexNow, uint256 cumulativeIndexLastUpdate ) external pure returns (uint256 newDebt, uint256 newCumulativeIndex) { (newDebt, newCumulativeIndex) = CreditLogic.calcIncrease( addAmount, currentDebt, cumulativeIndexNow, cumulativeIndexLastUpdate ); // newCumulativeIndex is recalculated so that previously accrued interest is preserved } ``` -------------------------------- ### CreditLogic - simulateIncrease Source: https://context7.com/gearbox-protocol/core-v3/llms.txt Simulates the effect of increasing a debt on the new debt amount and the cumulative interest index. This is useful for understanding how new borrowings affect the overall debt and interest accrual. ```APIDOC ### Function: simulateIncrease #### Description This function simulates the calculation of a new debt amount and a new cumulative index after an additional amount is added to the current debt. It ensures that previously accrued interest is preserved in the calculation. #### Parameters - `addAmount` (uint256) - The amount to add to the current debt. - `currentDebt` (uint256) - The current total debt amount. - `cumulativeIndexNow` (uint256) - The current cumulative interest index. - `cumulativeIndexLastUpdate` (uint256) - The cumulative interest index at the last update. #### Returns - `newDebt` (uint256) - The new total debt amount after adding `addAmount`. - `newCumulativeIndex` (uint256) - The updated cumulative interest index. ```solidity // Example call: // (uint256 newDebt, uint256 newCumulativeIndex) = CreditLogic.calcIncrease(addAmount, currentDebt, cumulativeIndexNow, cumulativeIndexLastUpdate); ``` ```