Works with the AI Agents you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIMuseMuseDotsDots+21 more

    Defi Margin Liquidation & Accounting

    1

    Precise DeFi margin accounting and liquidation logic to prevent double-counting, insolvent liquidations, and trapped funds.

    Free

    Security scanned
    Defi Margin Liquidation & Accounting

    Defi Margin Liquidation & Accounting

    Example session with this skill installed

    Show me how to implement cross-margin health factor accounting that includes free collateral and prevents the double-counting trap.

    • Read your context and instructions
    • Compiled the defi margin liquidation

    This implementation provides a cross-margin health factor calculation. It correctly treats collateralBalances as a net value, avoiding the common error of subtracting locked margin twice, and includes unrealized PnL in the equity calculation.

    Cross-Margin Health Implementation

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    
    contract MarginAccounting {
        struct Position {
            bool isOpen;
            uint256 size;
            uint256 margin;
            uint256 entryPrice;
            bool isLong;
            int256 unrealizedPnl;
        }
    
        mapping(address => uint256) public collateralBalances; // Free margin
        mapping(address => uint256) public lockedMargin;       // Reserved margin
        mapping(address => Position) public positions;
    
        uint256 public constant MAINTENANCE_MARGIN_RATIO = 0.05e18; // 5%
        uint256 public constant LEVERAGE_PRECISION = 1e18;
    
        /**
         * @notice Calculates health factor. 1e18 = 100% (breakeven/maintenance)
         * @dev Includes free collateral to support cross-margin accounts.
         */
        function marginHealth(address t) public view returns (uint256) {
            Position memory p = positions[t];
            if (!p.isOpen || p.size == 0) return type(uint256).max;
    
            // equity = (locked margin + free margin) + PnL
            // The trap: do NOT subtract lockedMargin here; collateralBalances is already net.
            int256 equity = int256(p.margin + collateralBalances[t]) + p.unrealizedPnl;
            
            if (equity <= 0) return 0;
    
            // health = (equity * leverage) / size
            return (uint256(equity) * LEVERAGE_PRECISION) / p.size;
        }
    
        /**
         * @dev Invariant: sum(collateralBalances) + sum(lockedMargin) == totalDeposits + PnL
         */
        function checkInvariants(address t, uint256 totalDeposited, int256 settledPnl) external view returns (bool) {
            return (collateralBalances[t] + lockedMargin[t]) == uint256(int256(totalDeposited) + settledPnl);
        }
    }
    

    Next steps

    1. Implement the updatePnL function to refresh unrealizedPnl from a mark price oracle before health checks.
    2. Integrate the lockMargin and releaseMargin atomic state modifiers.
    3. Add a liquidationPrice view function that derives the price where marginHealth equals MAINTENANCE_MARGIN_RATIO.

    Connects securely to your tools. The creator never sees your data.

    About this skill

    Implementing margin accounting in DeFi is a high-stakes task where a single double-counting error or inconsistent health factor calculation leads to insolvency or trapped user funds. This skill provides the precise logic required to manage free versus locked collateral, cross-margin health triggers, and liquidation flows that respect resting orders.

    What it does

    • Balance tracking manages free collateral and locked margin atomically to prevent double-counting and withdrawal exploits.
    • Cross-margin modeling calculates account health by correctly integrating free collateral with unrealized PnL.
    • Liquidation safety ensures that liquidating a position only releases that specific position's margin, preserving funds for resting orders.
    • PnL calculation handles directional perp accounting for longs and shorts using standard 8-decimal price feeds.
    • Market isolation implements per-market position keying to prevent global state collisions in multi-market protocols.

    How it works

    1. Initialize accounting by deploying the collateralBalances and lockedMargin mapping structures.
    2. Execute margin locks during trade entry or order placement to move funds from free to locked status.
    3. Monitor health using the provided health factor equation that solves for the maintenance margin ratio.
    4. Trigger liquidations when equity falls below the threshold, utilizing the safe margin forfeiture logic.

    Frameworks & tools

    This skill is designed for Solidity developers building on EVM-compatible chains. It assumes familiarity with fixed-point math and standard DeFi patterns found in lending and perpetual swap protocols.

    Why this beats prompting it yourself

    Generic AI prompts often fail to distinguish between isolated and cross margin, leading to critical health factor bugs. This skill provides the specific atomic state updates and invariant checks needed to pass professional security audits.

    Use cases

    • Building a perpetual swap exchange with a shared collateral vault.
    • Developing a lending protocol that requires accurate liquidation triggers.
    • Auditing existing margin systems for double-counting or resting-order traps.
    • Architecting multi-market trading platforms with per-user position isolation.

    Known limitations

    This skill focuses on USDC-margined or linear perps and does not cover inverse perpetuals. It assumes mark prices are provided by an external authorized oracle.

    Does not cover inverse perpetuals. Requires external authorized oracle for mark prices. Focuses on linear margin accounting logic.

    How to use

    1. 1

      Connect your agent to the Agensi MCP

      Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup

    2. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 3

      Ask for what you need

      Your agent loads this skill and uses it on your task. It always asks before any payment.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill goes through the trust checks below.

    Security scanned

    Checked by our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    Free forever

    No account required to browse

    Trust & safety

    Security scan

    Security scan passed 19 days ago

    • Free with an Agensi account

    Permissions

    No special permissions declared or detected

    Listed19 days ago
    Updated17 days ago

    What's inside

    Frequently Asked Questions

    This skill provides battle-tested Solidity logic for managing collateral states, health factor calculations, and liquidation triggers, specifically preventing common vulnerabilities like double-counting and insolvent liquidations.

    The skill is designed for AI agents capable of generating and auditing Solidity code, and it is fully compatible with any EVM-based blockchain such as Ethereum, Arbitrum, or Polygon.

    You will receive a set of modular smart contract templates, standardized accounting interfaces, and precise mathematical formulas for cross-margin health checks and PnL calculations.

    While highly versatile for linear perps and lending, this skill focuses on USDC/stablecoin-margined accounting and does not currently support inverse perpetual or non-linear payout structures.

    Updates are released periodically to address emerging DeFi attack vectors and gas optimization techniques; buyers will have access to the latest version via their marketplace dashboard.

    Integration is straightforward for developers familiar with fixed-point math, as it provides a structured blueprint for initializing balance mappings and defining margin-lock state transitions.

    New in Web3 & Crypto