> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kuru.io/llms.txt
> Use this file to discover all available pages before exploring further.

# MarginAccount Contract

> Central margin account managing user balances across all markets, supporting deposits, withdrawals, and trading credits.

## State Variables

```solidity theme={null}
mapping(bytes32 => uint256) public balances;
mapping(address => bool) public verifiedMarket;
```

* `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.

```solidity theme={null}
function initialize(
    address _owner,
    address _router,
    address _feeCollector,
    address _trustedForwarder
) public initializer
```

Sets contract owner, router, fee collector, and trusted forwarder addresses. Can only be called once.

### User Operations

#### deposit

Deposit tokens into margin account.

```solidity theme={null}
function deposit(address _user, address _token, uint256 _amount) external payable
```

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.

```solidity theme={null}
function withdraw(uint256 _amount, address _token) external
```

Withdraws tokens from sender's balance. Supports both ERC20 and native transfers.

#### batchWithdrawMaxTokens

Withdraw all balances for multiple tokens.

```solidity theme={null}
function batchWithdrawMaxTokens(address[] calldata _tokens) external
```

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

#### getBalance

Query user balance for a token.

```solidity theme={null}
function getBalance(address _user, address _token) external view returns (uint256)
```

Returns the current balance for a user's token account.

### Market Operations

#### debitUser

Debit user balance for trades.

```solidity theme={null}
function debitUser(address _user, address _token, uint256 _amount) external
```

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

#### creditUser

Credit user balance for trades.

```solidity theme={null}
function creditUser(address _user, address _token, uint256 _amount, bool _useMargin) external
```

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.

```solidity theme={null}
function creditUsersEncoded(bytes calldata _encodedData) external
```

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

#### creditFee

Credit protocol fees to fee collector.

```solidity theme={null}
function creditFee(address _assetA, uint256 _feeA, address _assetB, uint256 _feeB) external
```

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

### Router Operations

#### updateMarkets

Register a verified market.

```solidity theme={null}
function updateMarkets(address _marketAddress) external
```

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

### Administrative Functions

#### toggleProtocolState

Pause or resume protocol operations.

```solidity theme={null}
function toggleProtocolState(bool _state) external onlyOwner
```

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

#### setFeeCollector

Update fee collector address.

```solidity theme={null}
function setFeeCollector(address _feeCollector) external onlyOwner
```

Changes where protocol fees are credited.

## Events

### Deposit

```solidity theme={null}
event Deposit(
    address owner,
    address token,
    uint256 amount
);
```

Emitted when tokens are deposited into the margin account.

### Withdrawal

```solidity theme={null}
event Withdrawal(
    address owner,
    address token,
    uint256 amount
);
```

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

### ProtocolStateUpdated

```solidity theme={null}
event ProtocolStateUpdated(
    bool newState
);
```

Emitted when protocol pause state changes.

### FeeCollectorUpdated

```solidity theme={null}
event FeeCollectorUpdated(
    address newFeeCollector
);
```

Emitted when fee collector address is updated.
