### PMRM Setup and Margin Source: https://context7.com/derivexyz/v2-core/llms.txt Illustrates the setup of the Portfolio Margin Risk Manager (PMRM) and how to retrieve margin and mark-to-market values under different scenarios. ```APIDOC ## PMRM — Portfolio Margin Risk Manager `PMRM` uses a SPAN-like scenario-based methodology, stress-testing the portfolio across a configurable grid of spot and volatility scenarios to derive margin requirements. It is used for sophisticated traders who hold mixed options/perp portfolios and need cross-margining. ### Constructor-Level Wiring - **PMRM(address[] subAccounts, address cashAsset, address optionAsset, address perpAsset, address baseAsset, address dutchAuction, IPMRM.Feeds memory feeds, address pmrmViewer, address pmrmLib)**: Constructor for the PMRM contract. ### Scenario Configuration (Owner-Only) - **setScenarios(IPMRM.Scenario[] memory scenarios)**: Sets the stress scenarios for margin calculation. ### Reading Margin - **getMarginAndMarkToMarket(uint accountId, bool isInitial, uint scenarioId)**: Retrieves margin and mark-to-market value for an account under a specific scenario. `scenarioId == 0` queries the worst-case over all registered scenarios. ``` -------------------------------- ### Core Contracts Deployment Output Example Source: https://github.com/derivexyz/v2-core/blob/master/scripts/README.md This is an example of the output you might see after successfully deploying the core contracts. It includes addresses for various components. ```json { "auction": "0x6772299e3b0C7FF1AC8728F942A252e72CA1b521", "cash": "0x41d847D2dF78b27c0Bc730F773993EfE247c3f78", "rateModel": "0x1d61223Caea948f97d657aB3189e23F48888b6b0", "securityModule": "0x59E8b474a8061BCaEF705c7B93a903dE161FD149", "srm": "0xfe3e0ACFA9f4165DD733FCF6912c9d90c3aC0008", "srmViewer": "0xDb1791026c3824441FAe8A105b08E40dD02e1469", "stableFeed": "0xb77efe3e7c049933853e2C845a1412bCd36a2899", "subAccounts": "0x1dC3c8f65529E32626bbbb901cb743d373a7193e" } ``` -------------------------------- ### StandardManager Setup and Margin Source: https://context7.com/derivexyz/v2-core/llms.txt Demonstrates how to set up a market, whitelist assets, configure margin requirements, and read margin values using the StandardManager. ```APIDOC ## StandardManager — Isolated-margin risk checks `StandardManager` (SRM) is a simple per-market isolated risk manager. It supports perps, options, and base assets and is the default manager for most markets. The owner registers markets, assigns oracles, and sets margin parameters. ### Market Setup (Owner-Only) - **createMarket(string memory name)**: Creates a new market. - **whitelistAsset(IAsset asset, uint marketId, IStandardManager.AssetType type)**: Whitelists an asset for a specific market and type. - **setOraclesForMarket(uint marketId, address spotFeed, address forwardFeed, address volFeed)**: Sets the oracle feeds for a market. - **setPerpMarginRequirements(uint marketId, uint maintenance, uint initial)**: Sets initial and maintenance margin requirements for perpetuals. - **setBaseAssetMarginFactor(uint marketId, uint marginFactor, uint initialMarginScale)**: Sets margin factor and initial margin scale for base assets. - **setOptionMarginParams(uint marketId, IStandardManager.OptionMarginParams memory params)**: Sets margin parameters for options. - **setBorrowingEnabled(bool enabled)**: Enables or disables borrowing. ### Reading Margin - **getMargin(uint accountId, bool isInitial)**: Retrieves initial or maintenance margin for an account. - **getIsolatedMargin(uint marketId, int strike, uint expiry, bool isCall, int balance, bool isInitial)**: Retrieves isolated margin for a specific option. - **getMarginAndMarkToMarket(uint accountId, bool isInitial, int balance)**: Retrieves margin and mark-to-market value for an account. ### Settlement - **settleOptions(IOptionAsset asset, uint accountId)**: Settles all expired options in an account. - **settlePerpsWithIndex(uint accountId)**: Settles all perp unrealized PNL at the index price. ``` -------------------------------- ### Environment Variable Setup Source: https://github.com/derivexyz/v2-core/blob/master/scripts/README.md Configure required environment variables by creating an .env file and sourcing it. Ensure your RPC network is added to foundry.toml for alias usage. ```python # required PRIVATE_KEY= ``` ```bash source .env ``` ```toml [rpc_endpoints] sepolia = https://sepolia.infura.io/v3/26251a7744c548a3adbc17880fc70764 ``` -------------------------------- ### Initialize PMRM Portfolio Margin Risk Manager Source: https://context7.com/derivexyz/v2-core/llms.txt Construct a PMRM instance, wiring necessary sub-accounts, assets, feeds, and utility libraries. This is a constructor-level setup. ```solidity // ── Constructor-level wiring ────────────────────────────────────────────────── PMRM pmrm = new PMRM( subAccounts, cashAsset, optionAsset, perpAsset, baseAsset, dutchAuction, IPMRM.Feeds({ spotFeed: spotFeed, stableFeed: stableFeed, forwardFeed: forwardFeed, interestRateFeed: rateFeed, volFeed: volFeed }), pmrmViewer, pmrmLib ); ``` -------------------------------- ### Install Foundry Dependencies (Shell) Source: https://context7.com/derivexyz/v2-core/llms.txt Install project dependencies using Foundry. This command fetches necessary packages without relying on git submodules, using the foundry.lock file for versioning. ```shell # Install Foundry dependencies (no git submodules — uses foundry.lock) forge install ``` -------------------------------- ### Single Market Deployment Output Example Source: https://github.com/derivexyz/v2-core/blob/master/scripts/README.md This JSON output details the addresses of contracts deployed for a specific market, including base, option, and various feed contracts. ```json { "base": "0xF79FFb054429fb2b261c0896490f392fc8Ab998d", "forwardFeed": "0x48326634Ad484F086A9939cCF162960d8b3ce1D0", "iapFeed": "0x31de1F10347f8CBa52242A95dC7934FA98E70975", "ibpFeed": "0x45eC148853607f0969c5aB053fd10d59FA340B0A", "option": "0xc8FE03d1183053c1F3187c76A8A003323B9C5314", "perp": "0xAFf5ae727AecAf8aD4B03518248B5AD073edd99d", "perpFeed": "0xBbfb755C9B7A5DDEBc67651bAA15C659d001baD1", "pmrm": "0x105E635F61676E3a71bFAE7C02D17acd81A9b1D0", "pmrmLib": "0x991f05b9b450333347d266Fe362CFE19973FA70A", "pmrmViewer": "0x9F21BFA6607Eb71372B2654dfd528505896cB90B", "pricing": "0xD9d8d903707e03A7Cb1D8c9e3338F4E1Cc5Ec136", "rateFeed": "0x95721653d1E1C77Ac5cE09c93f7FF11dd5D87190", "spotFeed": "0x8a4A11BBE33C25F03a8b11EaC32312E2360858aD", "volFeed": "0xc97d681A8e58e4581F7456C2E5bC9F4CF26b236a" } ``` -------------------------------- ### Build Project with Forge Source: https://github.com/derivexyz/v2-core/blob/master/README.md Compiles the project contracts using Forge. Ensure all dependencies are installed before running this command. ```shell forge build ``` -------------------------------- ### Install Git Dependencies with Forge Source: https://github.com/derivexyz/v2-core/blob/master/README.md Installs git dependencies pinned in foundry.toml into the local ./lib directory. This command is used to manage external project dependencies. ```shell forge install ``` -------------------------------- ### Perform Static Analysis with Slither Source: https://github.com/derivexyz/v2-core/blob/master/README.md Runs static analysis on the project's smart contracts using Slither. Ensure Slither is installed separately before executing this command. ```shell slither src ``` -------------------------------- ### DutchAuction - Start Auction Source: https://context7.com/derivexyz/v2-core/llms.txt Initiates a Dutch Auction for an account that has fallen below its maintenance margin. This function is permissionless. ```APIDOC ## startAuction ### Description Initiates a Dutch Auction for a given account. ### Method `dutchAuction.startAuction(accountId, scenarioId)` ### Parameters - **accountId** (uint) - The ID of the account to start the auction for. - **scenarioId** (uint) - Used by PMRM to pick the worst stress scenario; pass 0 for SRM. ``` -------------------------------- ### Start Dutch Auction Source: https://context7.com/derivexyz/v2-core/llms.txt Initiates a Dutch Auction for a given account. The scenarioId is used by PMRM to select the worst stress scenario; pass 0 for SRM. ```Solidity // ── Start auction (permissionless) ─────────────────────────────────────────── // scenarioId is used by PMRM to pick the worst stress scenario; pass 0 for SRM dutchAuction.startAuction(accountId, 0 /* scenarioId */); ``` -------------------------------- ### Read StandardManager Margin Information Source: https://context7.com/derivexyz/v2-core/llms.txt Retrieve initial or maintenance margin for an account, or isolated margin and mark-to-market for a specific option. Can also get both margin and mark-to-market in one call. ```solidity // ── Reading margin ──────────────────────────────────────────────────────────── // Initial margin (true) or maintenance margin (false) int im = srm.getMargin(accountId, true); int mm = srm.getMargin(accountId, false); // Isolated margin for a single option (int margin, int mtm) = srm.getIsolatedMargin( marketId, 2000e18, // strike expiry, true, // isCall -5e18, // balance (short 5) true // isInitial ); // Full margin + mark-to-market in one call (int margin, int markToMarket) = srm.getMarginAndMarkToMarket(accountId, true, 0); ``` -------------------------------- ### Get Perpetual Futures Market Data Source: https://context7.com/derivexyz/v2-core/llms.txt Retrieve live market data for perpetual futures, including the current mark price, oracle confidence, index price, impact prices, funding rate, and unsettled cash for an account. ```solidity // Current perp mark price and oracle confidence (0–1e18) (uint perpPrice, uint confidence) = perpAsset.getPerpPrice(); // Current index (spot) price used for funding (uint indexPrice,) = perpAsset.getIndexPrice(); // Current bid / ask impact prices used in funding premium calculation (uint impactBid, uint impactAsk) = perpAsset.getImpactPrices(); // Hourly funding rate (negative = longs pay shorts) int fundingRate = perpAsset.getFundingRate(); // Unsettled cash for an account (unrealized PNL + pending funding + settled PNL in storage) int unsettledCash = perpAsset.getUnsettledAndUnrealizedCash(accountId); ``` -------------------------------- ### Get Perpetual Futures Position Details Source: https://context7.com/derivexyz/v2-core/llms.txt Retrieve the raw position size for a perpetual futures contract for a given account. Positive values indicate a long position, and negative values indicate a short position. ```solidity // Raw position size (positive = long, negative = short, 18-decimal) int positionSize = subAccounts.getBalance(accountId, IAsset(address(perpAsset)), 0); ``` -------------------------------- ### Query Dutch Auction State Source: https://context7.com/derivexyz/v2-core/llms.txt Retrieves the current state and status of a Dutch Auction for an account, including whether it's ongoing, insolvent, start time, and bid price. ```Solidity // ── Query auction state ──────────────────────────────────────────────────────── IDutchAuction.Auction memory info = dutchAuction.getAuction(accountId); // info.insolvent → bool // info.ongoing → bool // info.startTime → uint // info.cachedMM → uint (insolvent auctions only) (bool canTerminate, int mtm, int mm, int bm) = dutchAuction.getAuctionStatus(accountId); int bidPrice = dutchAuction.getCurrentBidPrice(accountId); uint maxProportion = dutchAuction.getMaxProportion(accountId, 0); ``` -------------------------------- ### Deploy Mock ERC20 Contracts Source: https://github.com/derivexyz/v2-core/blob/master/scripts/README.md Run this command to deploy mock USDC, WBTC, and WETH contracts and generate a configuration file for the specified network. Replace 'sepolia' with your target network alias. ```bash # where the config will live mkdir scripts/input/999 # deploy mocks and write (or override) config. # Note: Replace sepolia with other network alias if needed forge script scripts/deploy-erc20s.s.sol --rpc-url sepolia --broadcast ``` -------------------------------- ### Configure StandardManager Market Parameters Source: https://context7.com/derivexyz/v2-core/llms.txt Set up a new market, whitelist assets, configure oracles, and define margin requirements for perpetuals, base assets, and options. Enables borrowing. ```solidity // ── Market setup (owner-only) ───────────────────────────────────────────────── uint marketId = srm.createMarket("ETH"); srm.whitelistAsset(IAsset(address(ethPerpAsset)), marketId, IStandardManager.AssetType.Perpetual); srm.whitelistAsset(IAsset(address(ethOptionAsset)), marketId, IStandardManager.AssetType.Option); srm.whitelistAsset(IAsset(address(wethAsset)), marketId, IStandardManager.AssetType.Base); srm.setOraclesForMarket(marketId, spotFeed, forwardFeed, volFeed); // Perp margin: 3% maintenance, 5% initial srm.setPerpMarginRequirements(marketId, 0.03e18, 0.05e18); // Base discount: 90% of spot counts as margin, IM scale = 80% srm.setBaseAssetMarginFactor(marketId, 0.9e18, 0.8e18); // Option margin params srm.setOptionMarginParams(marketId, IStandardManager.OptionMarginParams({ maxSpotReq: 0.15e18, minSpotReq: 0.10e18, mmCallSpotReq: 0.05e18, mmPutSpotReq: 0.05e18, MMPutMtMReq: 0.10e18, unpairedMMScale: 1.2e18, unpairedIMScale: 1.5e18, mmOffsetScale: 1.3e18 })); // Enable borrowing (negative cash balance allowed) srm.setBorrowingEnabled(true); ``` -------------------------------- ### Run Test Suite with Foundry (Shell) Source: https://context7.com/derivexyz/v2-core/llms.txt Execute the complete test suite for the project using Foundry. ```shell # Run the full test suite forge test ``` -------------------------------- ### Build and Sign EIP-712 Permit for SubAccounts Source: https://context7.com/derivexyz/v2-core/llms.txt Constructs an EIP-712 permit struct off-chain and signs it with the account owner's private key. This allows for gasless allowance delegation. ```solidity ISubAccounts.PermitAllowance memory permitData = ISubAccounts.PermitAllowance({ accountId: accountId, delegate: traderBot, nonce: 42, // any unspent bit in nonceBitmap deadline: block.timestamp + 1 hours, assetAllowances: assetAllowances, // same type as setAssetAllowances subIdAllowances: new ISubAccounts.SubIdAllowance[](0) }); bytes32 structHash = PermitAllowanceLib.hash(permitData); bytes32 digest = _hashTypedDataV4(structHash); // domainSeparator + structHash (uint8 v, bytes32 r, bytes32 s) = vm.sign(ownerPrivKey, digest); bytes memory sig = abi.encodePacked(r, s, v); ``` -------------------------------- ### Deploy New Market with Forge Script Source: https://context7.com/derivexyz/v2-core/llms.txt Use this command to deploy a new market, such as ETH, using Forge scripts. Ensure your PRIVATE_KEY is set and specify the correct RPC URL for the network. ```bash PRIVATE_KEY= forge script scripts/deploy-market.s.sol \ --rpc-url lyra_mainnet --broadcast ``` -------------------------------- ### Deploy Core Contracts Source: https://github.com/derivexyz/v2-core/blob/master/scripts/README.md Execute this script to deploy the core contracts to the specified network. Ensure the 'deployments' directory for the network ID exists. ```bash # create folder to store deployed addresses mkdir deployments/999 forge script scripts/deploy-core.s.sol --rpc-url sepolia --broadcast ``` -------------------------------- ### Perform Static Analysis with Slither (Shell) Source: https://context7.com/derivexyz/v2-core/llms.txt Run Slither, a static analysis framework for Solidity, on the project's source code. ```shell # Static analysis slither src ``` -------------------------------- ### Deploy Single Market Source: https://github.com/derivexyz/v2-core/blob/master/scripts/README.md Deploy a new market for a specified asset by setting the MARKET_NAME environment variable. Default parameters can be updated in 'scripts/config-mainnet.sol'. ```bash MARKET_NAME=weth forge script scripts/deploy-market.s.sol --rpc-url sepolia --broadcast ``` -------------------------------- ### Create Account with SubAccounts Source: https://context7.com/derivexyz/v2-core/llms.txt Use `createAccount` to create a plain account for an owner managed by a standard manager. Use `createAccountWithApproval` to simultaneously grant ERC-721 approval, useful for protocols creating accounts on behalf of users. ```Solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.18; import {ISubAccounts} from "src/interfaces/ISubAccounts.sol"; import {IManager} from "src/interfaces/IManager.sol"; // ── Account Creation ───────────────────────────────────────────────────────── // Create a plain account for `owner` managed by `standardManager` uint accountId = subAccounts.createAccount(owner, IManager(address(standardManager))); // Create an account AND give `spender` ERC-721 approval in one call // (useful for protocols that create accounts on behalf of users) uint accountId = subAccounts.createAccountWithApproval(owner, spender, IManager(address(standardManager))); ``` -------------------------------- ### Generate Coverage Report Source: https://github.com/derivexyz/v2-core/blob/master/test/README.md Generate lcov.info and then create an HTML coverage report using brew-installed lcov. Ensure the lcov_branch_coverage is enabled. ```shell # Generate lcov.info forge coverage --report lcov # Create a html report brew install lcov genhtml lcov.info -out coverage/ --rc lcov_branch_coverage=1 --keep-going --include "src/" ``` -------------------------------- ### Configure Mock Contract Deployment Source: https://github.com/derivexyz/v2-core/blob/master/scripts/README.md Use this JSON configuration for deploying mock contracts. Set 'useMockedFeed' to false if you are using existing contract addresses. ```json { "usdc": "0xe80F2a02398BBf1ab2C9cc52caD1978159c215BD", "useMockedFeed": false, "wbtc": "0xF1493F3602Ab0fC576375a20D7E4B4714DB4422d", "weth": "0x3a34565D81156cF0B1b9bC5f14FD00333bcf6B93" } ``` -------------------------------- ### Compile Contracts with Foundry (Shell) Source: https://context7.com/derivexyz/v2-core/llms.txt Compile all Solidity contracts using Foundry. This process uses Solidity version 0.8.27 and enables the optimizer with 100 runs. ```shell # Compile all contracts (Solidity 0.8.27, optimizer 100 runs) forge build ``` -------------------------------- ### Configure and Read Lyra Oracle Feeds (Solidity) Source: https://context7.com/derivexyz/v2-core/llms.txt Set up signers, required thresholds, and heartbeats for oracle feeds. Read spot prices, forward prices, and volatility with confidence values. ```solidity // ── Signer setup (owner-only) ───────────────────────────────────────────────── spotFeed.addSigner(trustedBackend, true); spotFeed.setRequiredSigners(2); // require 2-of-N multisig spotFeed.setHeartbeat(60); // data older than 60 s is stale // ── Reading prices ──────────────────────────────────────────────────────────── (uint spot, uint confidence) = spotFeed.getSpot(); // spot → 18-decimal price (e.g. 2000e18 for $2000 ETH) // confidence → 18-decimal value in [0, 1e18]; used for oracle contingency margin (uint fwdPrice, uint fwdConf) = forwardFeed.getForwardPrice(uint64(expiry)); (uint vol, uint volConf) = volFeed.getVol(uint128(strike), uint64(expiry)); ``` -------------------------------- ### Run Only Unit Tests Source: https://github.com/derivexyz/v2-core/blob/master/test/README.md Execute unit tests by matching contract names prefixed with 'UNIT_'. Use -vvv for verbose output. ```shell forge test --match-contract="UNIT_" -vvv ``` -------------------------------- ### Run Only Integration Tests Source: https://github.com/derivexyz/v2-core/blob/master/test/README.md Execute integration tests by matching contract names prefixed with 'INTEGRATION_'. Use -vvv for verbose output. ```shell forge test --match-contract="INTEGRATION_" -vvv ``` -------------------------------- ### Run Gas Metric Tests Source: https://github.com/derivexyz/v2-core/blob/master/test/README.md Execute tests specifically for gas metrics by matching contract names prefixed with 'GAS_'. Use -vvv for verbose output. ```shell forge test --match-contract=GAS_ -vvv ``` -------------------------------- ### Read PMRM Margin and Mark-to-Market Source: https://context7.com/derivexyz/v2-core/llms.txt Retrieve the worst-case margin (initial or maintenance) and mark-to-market value for an account across all configured scenarios. ```solidity // ── Reading margin ──────────────────────────────────────────────────────────── // scenarioId == 0 → worst-case over all registered scenarios (int mm, int mtm) = pmrm.getMarginAndMarkToMarket(accountId, false, 0); (int im, int mtm) = pmrm.getMarginAndMarkToMarket(accountId, true, 0); ``` -------------------------------- ### Submit EIP-712 Permit On-Chain Source: https://context7.com/derivexyz/v2-core/llms.txt Submits a pre-signed EIP-712 permit to the SubAccounts contract. This can be done by any party, enabling gasless allowance grants. ```solidity subAccounts.permit(permitData, sig); ``` -------------------------------- ### Deploy Core Contracts to Lyra Mainnet (Shell) Source: https://context7.com/derivexyz/v2-core/llms.txt Deploy the core contracts to Lyra Mainnet using Foundry's scripting capabilities. Requires a private key and the Lyra Mainnet RPC URL. Includes broadcasting and verification. ```shell # Deploy core contracts to Lyra mainnet PRIVATE_KEY= forge script scripts/deploy-core.s.sol \ --rpc-url lyra_mainnet --broadcast --verify ``` -------------------------------- ### Deposit USDC and Create New Account Source: https://context7.com/derivexyz/v2-core/llms.txt Deposits USDC and simultaneously creates a new account for a specified recipient, managed by a given manager. The amount is in USDC's native decimals. ```solidity uint newAccountId = cashAsset.depositToNewAccount(recipient, 1000e6, IManager(address(srm))); ``` -------------------------------- ### Run Project Tests with Forge Source: https://github.com/derivexyz/v2-core/blob/master/README.md Executes all tests defined within the project using Forge. For more detailed test execution options, refer to the ./test folder. ```shell forge test ``` -------------------------------- ### Read Account Balances with SubAccounts Source: https://context7.com/derivexyz/v2-core/llms.txt Read the spot balance of a single asset for a specific account and subId using `getBalance`. Retrieve a full portfolio snapshot of all non-zero balances for an account using `getAccountBalances`. ```Solidity // ── Reading state ──────────────────────────────────────────────────────────── // Spot-read a single balance int cashBalance = subAccounts.getBalance(accountId, IAsset(address(cashAsset)), 0); // Full portfolio snapshot (all non-zero balances) ISubAccounts.AssetBalance[] memory portfolio = subAccounts.getAccountBalances(accountId); for (uint i; i < portfolio.length; i++) { // portfolio[i].asset → IAsset // portfolio[i].subId → uint (encodes strike/expiry for options) // portfolio[i].balance→ int (negative = short / debt) } ``` -------------------------------- ### OptionAsset Interface Source: https://context7.com/derivexyz/v2-core/llms.txt Provides functionalities for encoding and decoding option subIds, calculating settlement values, and initiating trades via SubAccounts. ```APIDOC ## OptionAsset ### Description Options are identified by a packed `uint96 subId` encoding expiry (unix), strike (18-dec), and call/put flag. `OptionAsset` is purely a balance ledger with hooks; actual P&L is settled through the manager. ### Functions #### getSubId Encodes expiry, strike price, and call/put flag into a `uint96 subId`. - **expiry** (uint) - Unix timestamp for expiry. - **strike** (uint) - Strike price with 18-decimal precision. - **isCall** (bool) - True for call options, false for put options. #### getOptionDetails Decodes a `subId` back into human-readable expiry, strike, and call/put flag. - **subId** (uint96) - The packed option identifier. - Returns: (uint expiry, uint strike, bool isCall) #### calcSettlementValue Calculates the payout for holding a specified balance of contracts for a given `subId`. - **subId** (uint) - The option identifier. - **balance** (int) - The number of contracts held (positive for long, negative for short). - Returns: (int payout, bool settled) - Payout amount and a flag indicating if settlement price is locked. ### Trading via SubAccounts #### submitTransfers Initiates an option trade by submitting asset transfers through the `SubAccounts` contract. - **transfers** (ISubAccounts.AssetTransfer[]) - An array of asset transfers, including the option and cash legs. - **managerData** (bytes) - Encoded data for the manager, potentially including oracle updates. ``` -------------------------------- ### SecurityModule - Pay Insolvency Source: https://context7.com/derivexyz/v2-core/llms.txt Allows for the repayment of insolvency using the cash held by the Security Module. This function is permissionless. ```APIDOC ## payCashInsolvency ### Description Repays insolvency using the Security Module's cash balance. This is a permissionless operation. ### Method `securityModule.payCashInsolvency()` ### Notes Burns SM cash balance up to the insolvent amount. ``` -------------------------------- ### Set Asset Allowances for SubAccounts Source: https://context7.com/derivexyz/v2-core/llms.txt Grant a delegate specific rights to move assets in or out of an account by setting asset allowances. `positive` controls the amount the delegate can receive, and `negative` controls the amount they can spend. ```Solidity // ── Allowances ─────────────────────────────────────────────────────────────── // Grant a delegate the right to move up to 5000 USDC of cash out of accountId ISubAccounts.AssetAllowance[] memory assetAllowances = new ISubAccounts.AssetAllowance[](1); assetAllowances[0] = ISubAccounts.AssetAllowance({ asset: IAsset(address(cashAsset)), positive: 0, // delegate cannot receive cash on my behalf negative: 5000e18 // delegate can spend up to 5000 cash from my account }); subAccounts.setAssetAllowances(accountId, delegate, assetAllowances); ``` -------------------------------- ### Settle Options and Perps with StandardManager Source: https://context7.com/derivexyz/v2-core/llms.txt Settle all expired options within an account or settle all perpetual unrealized PNL using the current index price. ```solidity // ── Settlement ──────────────────────────────────────────────────────────────── // Settle all expired options in an account srm.settleOptions(IOptionAsset(address(ethOptionAsset)), accountId); // Settle all perp unrealized PNL at index price srm.settlePerpsWithIndex(accountId); ``` -------------------------------- ### SubAccounts - EIP-712 Permit Source: https://context7.com/derivexyz/v2-core/llms.txt Allows account owners to sign off-chain allowance grants that can be submitted on-chain by anyone, using Uniswap Permit2-style nonces. This enables gasless allowance delegation. ```APIDOC ## SubAccounts - EIP-712 Permit ### Description Allows account owners to sign off-chain allowance grants and let anyone submit them on-chain, following Uniswap Permit2-style unordered nonces. ### Method `permit` ### Parameters #### Request Body - **permitData** (ISubAccounts.PermitAllowance) - Required - The permit allowance data struct. - **sig** (bytes) - Required - The signature for the permit. ### Request Example ```solidity // Build the permit struct off-chain and sign it with the account owner's key ISubAccounts.PermitAllowance memory permitData = ISubAccounts.PermitAllowance({ accountId: accountId, delegate: traderBot, nonce: 42, // any unspent bit in nonceBitmap deadline: block.timestamp + 1 hours, assetAllowances: assetAllowances, // same type as setAssetAllowances subIdAllowances: new ISubAccounts.SubIdAllowance[](0) }); bytes32 structHash = PermitAllowanceLib.hash(permitData); bytes32 digest = _hashTypedDataV4(structHash); // domainSeparator + structHash (uint8 v, bytes32 r, bytes32 s) = vm.sign(ownerPrivKey, digest); bytes memory sig = abi.encodePacked(r, s, v); // Anyone can now submit this on-chain subAccounts.permit(permitData, sig); ``` ## permitAndSubmitTransfer ### Description Combines a permit operation with an atomic transfer, preventing front-running. ### Method `permitAndSubmitTransfer` ### Parameters #### Request Body - **transfer** (Transfer) - Required - The transfer details. - **managerData** (ManagerData) - Required - Manager-specific data. - **permitData** (ISubAccounts.PermitAllowance) - Required - The permit allowance data struct. - **sig** (bytes) - Required - The signature for the permit. ### Request Example ```solidity // Or combine permit + transfer atomically (prevents front-run) subAccounts.permitAndSubmitTransfer(transfer, managerData, permitData, sig); ``` ## invalidateUnorderedNonces ### Description Invalidates a nonce manually to cancel a pending permit. ### Method `invalidateUnorderedNonces` ### Parameters #### Path Parameters - **wordPos** (uint256) - Required - The word position of the nonce. - **mask** (uint256) - Required - The mask for the nonce. ### Request Example ```solidity // Invalidate a nonce manually to cancel a pending permit // wordPos = nonce >> 8, bitPos = nonce & 0xFF → mask = 1 << bitPos subAccounts.invalidateUnorderedNonces(0 // wordPos, 1 << 42 // mask for nonce 42 ); ``` ``` -------------------------------- ### SecurityModule - Whitelist Module Source: https://context7.com/derivexyz/v2-core/llms.txt Allows the owner of the Security Module to whitelist other modules, such as DutchAuction, enabling them to request payouts. ```APIDOC ## setWhitelistModule ### Description Whitelists or de-whitelists a module to interact with the Security Module. ### Method `securityModule.setWhitelistModule(moduleAddress, isWhitelisted)` ### Parameters - **moduleAddress** (address) - The address of the module to whitelist. - **isWhitelisted** (bool) - True to whitelist, false to de-whitelist. ``` -------------------------------- ### PerpAsset Interface Source: https://context7.com/derivexyz/v2-core/llms.txt Manages perpetual futures positions, including tracking funding rates, PNL, and enabling permissionless settlement. ```APIDOC ## PerpAsset ### Description `PerpAsset` tracks perpetual positions and accumulates funding (`aggregatedFunding`) and mark-to-market PNL per account. Settlement is manager-driven; `realizeAccountPNL` can be called by anyone. ### Reading Live Data #### getPerpPrice Retrieves the current perpetual futures mark price and oracle confidence. - Returns: (uint perpPrice, uint confidence) - The mark price and oracle confidence (0-1e18). #### getIndexPrice Retrieves the current index (spot) price used for funding calculations. - Returns: (uint indexPrice, uint) - The index price. #### getImpactPrices Retrieves the current bid and ask impact prices used in funding premium calculations. - Returns: (uint impactBid, uint impactAsk) - The impact bid and ask prices. #### getFundingRate Retrieves the current hourly funding rate. - Returns: int - The funding rate (negative means longs pay shorts). #### getUnsettledAndUnrealizedCash Retrieves the unsettled cash for a given account, including unrealized PNL, pending funding, and settled PNL. - **accountId** (address) - The account identifier. - Returns: int - The unsettled cash amount. ### Settlement #### realizeAccountPNL Allows anyone to settle the PNL and funding for a given account. - **accountId** (address) - The account identifier. ### Position Detail #### getBalance Retrieves the raw position size for an account in the PerpAsset. - **accountId** (address) - The account identifier. - **asset** (IAsset) - The PerpAsset contract address. - **subId** (uint) - Should be 0 for PerpAsset. - Returns: int - The position size (positive for long, negative for short, 18-decimal). ### Trading via SubAccounts #### submitTransfers Executes a perpetual futures trade by submitting asset transfers through the `SubAccounts` contract. - **transfers** (ISubAccounts.AssetTransfer[]) - An array of asset transfers, including the perpetual futures leg and the cash leg. - **managerData** (bytes) - Encoded data for the manager, typically including oracle updates for margin checking. ``` -------------------------------- ### Manage Security Module Whitelist Source: https://context7.com/derivexyz/v2-core/llms.txt Allows the owner to whitelist or de-whitelist modules, such as DutchAuction, that can request payouts from the Security Module. ```Solidity // ── Owner management ────────────────────────────────────────────────────────── securityModule.setWhitelistModule(address(dutchAuction), true); securityModule.withdraw(5000e6, treasuryAddress); // partial withdrawal by owner ``` -------------------------------- ### Read Security Module Balance Source: https://context7.com/derivexyz/v2-core/llms.txt Reads the current insurance balance held by the Security Module in USDC. ```Solidity // ── Read current insurance balance ──────────────────────────────────────────── int smCash = subAccounts.getBalance( securityModule.accountId(), IAsset(address(cashAsset)), 0 ); // 18-decimal ``` -------------------------------- ### Repay Insolvency Source: https://context7.com/derivexyz/v2-core/llms.txt Allows anyone to repay insolvency by burning cash from the Security Module's balance, up to the insolvent amount. ```Solidity // ── Repay insolvency (permissionless) ───────────────────────────────────────── securityModule.payCashInsolvency(); // burns SM cash balance up to insolvent amount ``` -------------------------------- ### Settle Perpetual Futures PNL and Funding Source: https://context7.com/derivexyz/v2-core/llms.txt Settle PNL and funding for a perpetual futures account by calling realizeAccountPNL. This operation is permissionless and can be called by anyone. ```solidity perpAsset.realizeAccountPNL(accountId); ``` -------------------------------- ### SecurityModule - Read Balance Source: https://context7.com/derivexyz/v2-core/llms.txt Retrieves the current cash balance of the Security Module. ```APIDOC ## getBalance (via subAccounts) ### Description Reads the current cash balance held by the Security Module. ### Method `subAccounts.getBalance(securityModule.accountId(), IAsset(address(cashAsset)), 0)` ### Returns - **smCash** (int) - The Security Module's cash balance in 18-decimal format. ``` -------------------------------- ### Deposit USDC into Existing Account Source: https://context7.com/derivexyz/v2-core/llms.txt Deposits a specified amount of USDC into an existing account managed by CashAsset. The amount should be in USDC's native decimals. ```solidity cashAsset.deposit(accountId, 1000e6); // `stableAmount` in USDC's native decimals ``` -------------------------------- ### Submit Single and Batched Transfers with SubAccounts Source: https://context7.com/derivexyz/v2-core/llms.txt Submit a single asset transfer between accounts using `submitTransfer`. For atomic operations, use `submitTransfers` to batch multiple transfers, ensuring the manager hook is called only once per account. ```Solidity // ── Transfers ──────────────────────────────────────────────────────────────── // Move 100 USDC (cash asset, subId=0) from account 1 to account 2 ISubAccounts.AssetTransfer memory transfer = ISubAccounts.AssetTransfer({ fromAcc: 1, toAcc: 2, asset: IAsset(address(cashAsset)), subId: 0, amount: 100e18, // 18-decimal fixed-point assetData: "" }); uint tradeId = subAccounts.submitTransfer(transfer, ""); // Batch multiple transfers atomically (manager hook called once per account) ISubAccounts.AssetTransfer[] memory batch = new ISubAccounts.AssetTransfer[](2); batch[0] = ISubAccounts.AssetTransfer({ fromAcc:1, toAcc:2, asset:IAsset(address(perpAsset)), subId:0, amount:10e18, assetData:"" }); batch[1] = ISubAccounts.AssetTransfer({ fromAcc:2, toAcc:1, asset:IAsset(address(cashAsset)), subId:0, amount:500e18, assetData:"" }); subAccounts.submitTransfers(batch, abi.encode(oracleUpdates)); ``` -------------------------------- ### Lyra Mainnet Deployment Addresses (JSON) Source: https://context7.com/derivexyz/v2-core/llms.txt Provides the contract addresses for core Lyra components on the Lyra Mainnet (chain 957). Per-market addresses are located in separate JSON files. ```json { "subAccounts": "0xE7603DF191D699d8BD9891b821347dbAb889E5a5", "cash": "0x57B03E14d409ADC7fAb6CFc44b5886CAD2D5f02b", "srm": "0x28c9ddF9A3B29c2E6a561c1BC520954e5A33de5D", "auction": "0x141919f1FA90F99A3fbafFb0b111e4f84AB5aB52", "securityModule": "0x8dC92fB0e1C1F1Def6e424E50aaA66dbB124eb54", "dataSubmitter": "0xd8d46a044f62d97733707176D6791b0a73cd7f6C", "optionSettlementHelper": "0xbE9DBda519e15a1c0d238cEa0b3daD47a484A6Ff", "perpSettlementHelper": "0xBd282333710B9C7e33E8a37d027885A7C079Ae23", "stableFeed": "0x9C61888497D716f5bBd93D5e13d443cC375f1424", "rateModel": "0x989656625954b5359b4095c34ac8532a7fed4899" } ``` -------------------------------- ### SecurityModule - Donate Source: https://context7.com/derivexyz/v2-core/llms.txt Allows users to donate USDC to the insurance fund managed by the Security Module. ```APIDOC ## donate ### Description Donates USDC to the Security Module's insurance fund. ### Method `securityModule.donate(stableAmount)` ### Parameters - **stableAmount** (uint) - The amount of USDC to donate, in USDC's native decimal places. ``` -------------------------------- ### Submit Signed Oracle Data to Lyra Feeds (Solidity) Source: https://context7.com/derivexyz/v2-core/llms.txt Submit EIP-712 signed off-chain data packets to Lyra oracle feeds. Data is verified against a whitelist of signers and a minimum signer threshold. ```solidity // ── Submitting signed price data ────────────────────────────────────────────── // FeedData struct is ABI-encoded and signed off-chain by a whitelisted signer IBaseLyraFeed.FeedData memory fd = IBaseLyraFeed.FeedData({ data: abi.encode(uint96(2000e18), uint64(0.99e18)), // price + confidence deadline: block.timestamp + 30, timestamp: uint64(block.timestamp), signers: [signerAddress], signatures: [ecdsaSignature] }); spotFeed.acceptData(abi.encode(fd)); ``` -------------------------------- ### Batch Oracle Updates with Trades (Solidity) Source: https://context7.com/derivexyz/v2-core/llms.txt Route multiple manager data updates to respective feeds' acceptData() functions using OracleDataSubmitter. This allows batch oracle updates in the same transaction as a trade. ```solidity // ── Batch oracle updates in the same tx as a trade ──────────────────────────── // OracleDataSubmitter routes ManagerData[] to each feed's acceptData() IBaseManager.ManagerData[] memory oracleUpdates = new IBaseManager.ManagerData[](2); oracleUpdates[0] = IBaseManager.ManagerData({ receiver: address(spotFeed), data: encodedSpotFd }); oracleUpdates[1] = IBaseManager.ManagerData({ receiver: address(volFeed), data: encodedVolFd }); oracleDataSubmitter.submitData(abi.encode(oracleUpdates)); // Or pass the same encoded array directly as `managerData` in submitTransfers() subAccounts.submitTransfers(transfers, abi.encode(oracleUpdates)); ``` -------------------------------- ### Combine Permit and Transfer Atomically Source: https://context7.com/derivexyz/v2-core/llms.txt Executes a permit and a transfer in a single atomic transaction to prevent front-running vulnerabilities. ```solidity subAccounts.permitAndSubmitTransfer(transfer, managerData, permitData, sig); ``` -------------------------------- ### Read Cash-to-Stable Exchange Rate Source: https://context7.com/derivexyz/v2-core/llms.txt Retrieves the current exchange rate between the internal cash balance and the underlying stablecoin. A rate less than 1e18 indicates insolvency. ```solidity uint exchangeRate = cashAsset.getCashToStableExchangeRate(); ``` -------------------------------- ### Configure PMRM Stress Scenarios Source: https://context7.com/derivexyz/v2-core/llms.txt Define stress scenarios for PMRM by specifying spot shocks and volatility directions. Scenarios are used for stress-testing portfolios. ```solidity // ── Scenario configuration (owner-only) ────────────────────────────────────── // Add a stress scenario: +20% spot move, vol scaled by 1.2× IPMRM.Scenario[] memory scenarios = new IPMRM.Scenario[](1); scenarios[0] = IPMRM.Scenario({ spotShock: 1.2e18, volShock: IPMRM.VolShockDirection.Up }); pmrm.setScenarios(scenarios); ``` -------------------------------- ### Place Bid in Dutch Auction Source: https://context7.com/derivexyz/v2-core/llms.txt Places a bid in a Dutch Auction. For solvent auctions, the bidder pays cash and receives a percentage of the portfolio. For insolvent auctions, the bidder receives cash from the Security Module to take on the portfolio. Ensure `priceLimit` is set to 0 for no limit. ```Solidity // ── Place a bid ─────────────────────────────────────────────────────────────── // Solvent auction: bidder pays `cashFromBidder` and receives `percentOfAccount` of positions // Insolvent auction: bidder receives `cashToBidder` from SM to take on the portfolio ( uint finalPercentage, uint cashFromBidder, uint cashToBidder ) = dutchAuction.bid( accountId, // liquidated account bidderId, // bidder's account (must be owned by msg.sender, same manager) 0.5e18, // bid on 50% of the current portfolio int(1000e18), // priceLimit: revert if cash paid exceeds this (0 = no limit) 0 // expectedLastTradeId: 0 = no front-run protection ); ``` -------------------------------- ### Donate Balance to Restore Solvency Source: https://context7.com/derivexyz/v2-core/llms.txt Allows an account to voluntarily burn its cash balance to help restore solvency. The amount burned is capped by the insolvent amount. ```solidity uint burnt = cashAsset.donateBalance(accountId, amountToBurn); ```