Skip to main content
This guide walks through the complete margin account lifecycle: creating an account, depositing collateral, borrowing, deploying capital to external protocols (Blend, Aquarius), repaying, and closing.

Account Lifecycle


Prerequisites


Step 1: Create a Margin Account

If the user already has a closed account, create_account() will reuse it. The same Registry call will return the reactivated address.

Step 2: Check Health Factor Before Any Operation

Always check health factor before borrows and withdrawals:
Liquidation threshold: HF < 1.1

Step 3: Deposit Collateral


Step 4: Borrow

The RiskEngine runs a health check before the borrow. If the transaction would drop HF below 1.1×, it panics and the transaction fails. Check current health factor and available borrow capacity before calling. Maximum borrow capacity:

Step 5: Atomic Deposit + Borrow

For better UX, combine deposit and borrow in a single transaction:

Step 6: Deploy to External Protocols

After borrowing, the SmartAccount holds the borrowed assets. Route them to Blend or Aquarius via AccountManager.execute().
The execute() function routes through AccountManager → SmartAccount → external protocol. This is how the protocol tracks external positions via TrackingTokens.

Deploy to Blend (Earn Yield on Borrowed XLM)

Add Liquidity to Aquarius


Step 7: Read Outstanding Debt


Step 8: Repay


Step 9: Withdraw Collateral

The RiskEngine validates the withdrawal. If it would drop HF below 1.1×, the transaction fails.

Step 10: Close Account

Panics if: the account still has outstanding debt. Repay all debt first.

Common Pitfalls

Health factor check: always read the current HF before borrows and withdrawals. Transactions that would violate the 1.1× threshold will panic and you’ll lose gas.