- Home
- Skills
- Web3 & Crypto
- Defi Margin Liquidation & Accounting
Works with the AI Agents you already use
Defi Margin Liquidation & Accounting
Precise DeFi margin accounting and liquidation logic to prevent double-counting, insolvent liquidations, and trapped funds.
Free
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
- Implement the
updatePnLfunction to refreshunrealizedPnlfrom a mark price oracle before health checks. - Integrate the
lockMarginandreleaseMarginatomic state modifiers. - Add a
liquidationPriceview function that derives the price wheremarginHealthequalsMAINTENANCE_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
- Initialize accounting by deploying the
collateralBalancesandlockedMarginmapping structures. - Execute margin locks during trade entry or order placement to move funds from free to locked status.
- Monitor health using the provided health factor equation that solves for the maintenance margin ratio.
- 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.
Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for Web3 & Crypto.
Does not cover inverse perpetuals. Requires external authorized oracle for mark prices. Focuses on linear margin accounting logic.
How to use
- 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
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before buying a skill.
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 to use
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