# Multicall System

> Markdown export of the Gearbox Protocol documentation page for agents and retrieval systems.

Canonical page: https://docs.gearbox.finance/developers/gm-concept-multicalls
Source file: content/developers/gm-concept-multicalls.mdx
Section router: https://docs.gearbox.finance/developers/llms.txt
Section full export: https://docs.gearbox.finance/developers/llms-full.txt

The multicall system is the transaction model for all Credit Account operations in Gearbox. It allows complex DeFi strategies — borrowing, swapping, farming, adjusting collateral — to execute atomically in a single transaction with a solvency check at the end.

## Why Multicalls?

In traditional lending protocols, each operation (deposit collateral, borrow, swap) is a separate transaction. This creates problems for leveraged positions:

- **Mid-execution insolvency** — after borrowing but before deploying capital, the account is technically undercollateralized
- **Gas inefficiency** — multiple transactions mean multiple solvency checks
- **Sandwich risk** — separate swap transactions are vulnerable to MEV

Multicalls solve all three: batch everything into one transaction, check solvency once at the end.

## How It Works

```mermaid
flowchart TD
    User[User / Bot] -->|"multicall(account, calls)"| Facade[Credit Facade]

    Facade -->|"1. Start"| Loop[Execution Loop]

    Loop --> Check{Target?}
    Check -->|"Facade"| Internal[Internal Operation]
    Check -->|"Adapter"| Adapter[Adapter Contract]

    Internal -->|"addCollateral, increaseDebt..."| Loop
    Adapter -->|"swap, deposit, stake..."| Protocol[DeFi Protocol]
    Protocol --> Loop

    Loop -->|"2. All calls done"| Security[Security Checks]

    Security --> HF{Health Factor >= 1?}
    HF -->|"Yes"| Success[Transaction Success]
    HF -->|"No"| Revert[Transaction Reverts]
```

1. **Start** — The Facade begins the multicall and sets the Credit Account as "active"
2. **Execute** — Each call in the array runs sequentially. Calls target either the Facade (internal operations) or an Adapter (external DeFi protocol calls)
3. **Check** — After all calls complete, the Facade performs security checks: slippage verification, forbidden token checks, and a full collateral check (HF >= 1)
4. **Result** — If the account is solvent, the transaction succeeds. If not, the entire transaction reverts — nothing happened.

## Available Operations

### Protocol Operations

| Operation | What It Does |
| --- | --- |
| `addCollateral` | Move tokens from wallet to Credit Account |
| `increaseDebt` | Borrow underlying from Pool |
| `decreaseDebt` | Repay debt to Pool |
| `updateQuota` | Enable/adjust quota for a collateral token |
| `withdrawCollateral` | Remove assets from account |

### Safety Controls

| Operation | What It Does |
| --- | --- |
| `onDemandPriceUpdates` | Push fresh price data (must be first call) |
| `storeExpectedBalances` | Record balances before swaps for slippage check |
| `compareBalances` | Verify balances after swaps meet minimums |
| `setFullCheckParams` | Optimize the collateral check with token hints |

### External Calls (via Adapters)

Adapters are whitelisted wrappers around DeFi protocols. Each adapter restricts which functions a Credit Account can call and validates outcomes. Through adapters, a Credit Account can:

- Swap tokens on Uniswap, Curve, or other DEXes
- Deposit into yield vaults (Yearn, ERC-4626)
- Stake tokens (Lido, Convex)
- Provide liquidity (Curve, Balancer)

## The "Diff" Pattern

Adapters implement "diff" functions (e.g., `swapDiff`, `depositDiff`) for handling unknown amounts. Instead of specifying exact input:

- **Standard**: needs exact `amountIn`
- **Diff**: calculates `amountIn = currentBalance - leftoverAmount`

This is essential when the result of a previous operation is unknown — for example, swapping all received tokens from a prior withdrawal.

## Functions That Accept Multicalls

All state-changing CreditFacade functions accept a multicall array:

| Function | Purpose |
| --- | --- |
| `openCreditAccount` | Create a new account with initial operations |
| `closeCreditAccount` | Close account, return remaining funds |
| `multicall` | Execute operations on existing account |
| `botMulticall` | Bot-initiated operations (requires permissions) |
| `liquidateCreditAccount` | Liquidate unhealthy account |

## Best Practices

1. **Price updates first** — always put `onDemandPriceUpdates` at the start when using pull-based oracles (Pyth, Redstone)
2. **Slippage protection** — use `storeExpectedBalances` before swaps and `compareBalances` after
3. **Dust management** — use `type(uint256).max` in `withdrawCollateral` to empty balances completely
4. **Gas optimization** — use `setFullCheckParams` with token mask hints for accounts with many enabled tokens

## Learn More

- **Building multicalls in TypeScript** — [Multicalls (SDK)](https://docs.gearbox.finance/developers/gm-accounts-multicalls)
- **Individual operation details** — [Adding Collateral](https://docs.gearbox.finance/developers/gm-mc-collateral), [Debt Management](https://docs.gearbox.finance/developers/gm-mc-debt), [External Calls](https://docs.gearbox.finance/developers/gm-mc-external)
- **How solvency is enforced** — [Health Factor & Risk](https://docs.gearbox.finance/developers/gm-concept-risk)
