Skip to main content

State Variables

  • balances - User token balances keyed by hash of (user, token)
  • verifiedMarket - Markets authorized to debit/credit user accounts

Core Functions

initialize

One-time initialization of the MarginAccount contract.
Sets contract owner, router, fee collector, and trusted forwarder addresses. Can only be called once.

User Operations

deposit

Deposit tokens into margin account.
Deposits tokens for a specified user. If _token is native (address(0)), requires msg.value. For ERC20 tokens, transfers from caller to contract.

withdraw

Withdraw tokens from margin account.
Withdraws tokens from sender’s balance. Supports both ERC20 and native transfers.

batchWithdrawMaxTokens

Withdraw all balances for multiple tokens.
Convenience function to withdraw entire balances for multiple tokens in one transaction.

getBalance

Query user balance for a token.
Returns the current balance for a user’s token account.

Market Operations

debitUser

Debit user balance for trades.
Called by verified markets to consume user balances. Reverts if insufficient balance.

creditUser

Credit user balance for trades.
Called by verified markets to credit user balances. If _useMargin is false, transfers tokens directly to user. If true, updates balance mapping.

creditUsersEncoded

Batch credit multiple users.
Batch version of creditUser for gas efficiency. Encoded data contains array of (user, token, amount, useMargin) tuples.

creditFee

Credit protocol fees to fee collector.
Called by verified markets to credit collected fees. Updates fee collector’s balances for both assets.

Router Operations

updateMarkets

Register a verified market.
Called by router to authorize a new market to debit/credit user accounts.

Administrative Functions

toggleProtocolState

Pause or resume protocol operations.
Sets global pause state. When paused, all user and market operations are disabled except withdrawals.

setFeeCollector

Update fee collector address.
Changes where protocol fees are credited.

Events

Deposit

Emitted when tokens are deposited into the margin account.

Withdrawal

Emitted when tokens are withdrawn from the margin account. Emitted both for single and batch withdrawals.

ProtocolStateUpdated

Emitted when protocol pause state changes.

FeeCollectorUpdated

Emitted when fee collector address is updated.