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

# MultiliquidSwap Contract

> The route, pricing, authorization, and settlement orchestrator for Multiliquid on EVM

## Overview

`MultiliquidSwap` is the central execution layer for Multiliquid on EVM. It prices and settles atomic exchanges across permissioned RWAs and stablecoins while coordinating capital provider delegates, RWA risk controls, price adapters, whitelist adapters, and protocol fee configuration.

> [card] One Routing Surface
>
> One `quoteSwap` function prices every route and one `swap` function settles
> single-leg or multi-leg transactions.

> [card] NAV-Based Pricing
>
> Every asset is converted through 18-decimal USD values with deterministic
> exact-in and exact-out math.

> [card] Flexible Execution
>
> Users can transact directly or authorize operators through standing
> allowances and one-shot EIP-712 permits.

> [card] Integrated Liquidity
>
> Stablecoin delegates can use automatic prefund and sweep legs backed by a
> designated liquidity stablecoin.

## Architecture

```mermaid theme={null}
flowchart LR
    U[User] --> S[MultiliquidSwap]
    O[Operator] --> S
    S --> P[Price Adapters]
    S --> W[Whitelist Adapters]
    S --> R[RWA Delegates]
    S --> D[Stablecoin Delegate]
    D --> C[Capital Provider Custody]
    S --> V[Protocol Fee Vault]
```

The swap contract owns routing, pricing, authorization, protocol-level controls, and atomic execution. Asset movement is delegated to the selected stablecoin capital provider domain. Optional RWA delegates apply stateful asset-specific controls, while whitelist adapters preflight recipient eligibility.

The contract is upgradeable through UUPS and uses OpenZeppelin access control, pausing, and reentrancy protection.

## Unified Route Model

Every requested leg uses the same structure:

```solidity theme={null}
struct SwapInputs {
    uint256 routeId;
    bytes32 assetInID;
    bytes32 assetOutID;
    bytes32 stablecoinDelegateID;
    uint256 assetInAmt;
    uint256 assetOutAmt;
}
```

`stablecoinDelegateID` selects the capital provider domain whose custody, whitelists, fee schedules, and settlement implementation apply to the leg.

| Route ID | Direction | Amount mode |
| -: | - | - |
| `0` | Stablecoin → RWA | Exact-in |
| `1` | Stablecoin → RWA | Exact-out |
| `2` | RWA → stablecoin | Exact-in |
| `3` | RWA → stablecoin | Exact-out |
| `4` | RWA → RWA | Exact-in |
| `5` | RWA → RWA | Exact-out |
| `6` | Stablecoin → stablecoin | Exact-in |
| `7` | Stablecoin → stablecoin | Exact-out |
| `8` | Prefunded RWA → stablecoin | Exact-in |
| `9` | Prefunded RWA → stablecoin | Exact-out |
| `10` | Prefunded stablecoin → stablecoin | Exact-in |
| `11` | Prefunded stablecoin → stablecoin | Exact-out |

Even route IDs are exact-in and odd route IDs are exact-out.

### Amount Semantics

| Mode | `assetInAmt` | `assetOutAmt` |
| - | - | - |
| Exact-in | Exact input spent | Minimum acceptable output |
| Exact-out | Maximum acceptable input | Exact output received |

The route configuration determines which stablecoin delegate is valid:

* Stablecoin → RWA uses the input stablecoin ID.
* RWA → stablecoin uses the output stablecoin ID.
* RWA → RWA uses an accepted stablecoin capital provider domain selected by the caller.
* Stablecoin → stablecoin can use either the input or output stablecoin delegate.
* Prefunded routes follow the same delegate rule as their corresponding base route.

## Quoting

`quoteSwap` prices one requested leg:

```solidity theme={null}
function quoteSwap(address user, SwapInputs calldata inputs)
    external
    view
    returns (SwapResolved memory outputs);
```

```solidity theme={null}
struct SwapResolved {
    uint256 tokenInAmt;
    uint256 tokenOutAmt;
    uint256 issuerFeeAmt;
    uint256 spreadFeeAmt;
    uint256 lpFeeAmt;
}
```

The quote validates the route, asset registrations, delegate selection, price availability, and stablecoin guardrails. It uses current fee and yield-accounting state without moving tokens, spending approvals, or mutating accrued interest.

For exact-in routes, the quote uses `assetInAmt` and treats `assetOutAmt` only as an execution bound. For exact-out routes, it uses `assetOutAmt` and treats `assetInAmt` only as an execution bound.

> [!NOTE]
>
> Quotes are prospective and do not require the user or custody accounts to hold
> the quoted assets. Applications can exercise the complete settlement path with
> an `eth_call` simulation before submission.

## Swap Execution

All requested legs settle through one entrypoint:

```solidity theme={null}
function swap(
    address user,
    address receiver,
    SwapInputs[] calldata inputs,
    ApprovalPermit calldata permit
) external;
```

* `user` owns the input assets and yield credits.
* `msg.sender` is the operator submitting the transaction.
* `receiver` receives every requested leg's output.
* `inputs` is an ordered array of one or more bounded swap legs.
* `permit` is optional EIP-712 authorization for delegated execution.

Every transaction is atomic. Route validation, pricing, authorization, yield synchronization, token transfers, internally derived liquidity legs, allowance spending, and nonce changes all revert together if any leg fails.

### Multi-Leg Transactions

The contract executes requested legs in array order up to the operator-configured maximum.

Each leg is independently specified and priced. Outputs are not implicitly assigned as the next leg's input; applications can construct chained amounts off-chain and submit the resulting ordered batch.

Multi-leg execution supports:

* Portfolio rebalancing
* Batch order settlement
* Multi-route institutional workflows
* Atomic execution around auto-liquidity legs

## User, Operator, and Receiver

Separating the economic user, transaction operator, and output receiver enables relayers, institutional operators, smart-account workflows, scheduled execution, and settlement to a designated custody account.

The contract supports three authorization modes:

| Mode | Authorization | Receiver |
| - | - | - |
| Direct | `msg.sender == user` | Any nonzero, non-blacklisted address |
| Standing allowance | Per user, operator, and input asset | Must equal `user` |
| EIP-712 permit | Signed exact execution, receiver, operator, nonce, and deadline | Signed receiver |

ERC-20 token allowance to the selected stablecoin delegate remains separate from protocol-level operator authorization.

### Standing Swap Allowances

```solidity theme={null}
function adjustSwapInputAllowance(
    address operator,
    bytes32 assetInID,
    uint256 amount,
    bool increase
) external;
```

Allowances are stored as:

```solidity theme={null}
swapInputAllowances[user][operator][assetInID]
```

The function adds or subtracts a delta. Exact-out swaps consume the resolved input rather than the submitted maximum. `type(uint256).max` acts as an infinite allowance and is not decremented.

Standing allowances can only authorize a delegated swap when `receiver == user`, keeping the reusable permission tied to the user's own output account.

### EIP-712 One-Shot Permits

The one-shot permit allows the user, operator, and receiver to be three different addresses for one signed execution. The user owns the inputs and signs the authorization, the operator submits the transaction, and the receiver receives the output.

The signed `SwapInputs[]` can contain one requested leg or an ordered multi-leg batch. Batch authorization is supported because `swap` accepts an array, but the permit's defining purpose is one-shot authorization across separate user, operator, and receiver identities.

```solidity theme={null}
struct ApprovalPermit {
    uint256 deadline;
    bytes signature;
}
```

The `SwapBatchApproval` typed message binds:

* User, operator, and receiver
* The complete ordered `SwapInputs[]`
* Every route, asset, delegate, amount, and execution bound
* The user's current nonce
* The permit deadline
* Chain ID and verifying contract

The domain name is `MultiliquidSwap` and the domain version is `2`. Signatures support standard ECDSA, compact EIP-2098, ERC-1271 contract accounts, and EIP-7702 delegated EOAs.

One nonce authorizes the complete signed execution, whether single-leg or multi-leg. A reverted transaction rolls back the nonce with the rest of settlement.

## Pricing Engine

Multiliquid uses deterministic NAV-based pricing rather than an AMM curve.

The engine:

1. Normalizes input amounts to 18-decimal WAD precision.
2. Converts the input asset into a common USD-denominated route unit.
3. Applies the selected capital provider's fee schedule and protocol fee policy.
4. Applies yield-adjusted value where the input is yield-bearing.
5. Converts the remaining route value into output-token decimals.
6. Rounds conservatively for exact-in and exact-out guarantees.

RWA prices come from `IPriceAdapter.getPrice()`. Stablecoins use an operator-configured WAD value and can additionally enforce an oracle deviation guardrail.

### Fee Outputs

`SwapResolved` and the `Swap` event report three fee amounts:

| Field | Meaning |
| - | - |
| `issuerFeeAmt` | Configured protocol fee funded by the capital provider reported separately from the user's route value; the selected delegate handles settlement |
| `spreadFeeAmt` | Protocol share of the capital provider spread calculated from discount, acceptance, and redemption settings |
| `lpFeeAmt` | Explicit capital provider fee retained or minted for the selected delegate, such as a redemption or acceptance fee |

The protocol can configure rates per stablecoin for protocol fees funded by capital providers, a global protocol take on capital provider spread, and fee exemptions for selected stablecoins. Capital provider delegates configure their own RWA discounts, RWA redemption fees, stablecoin acceptance fees, and stablecoin redemption fees.

Treasury's portfolio management fee belongs to the yield-bearing delegate and is applied to posted APY before user yield accrues.

## Auto-Liquidity

A stablecoin delegate can designate an accepted stablecoin—typically a
yield-bearing asset—through `autoLiquidityStablecoinIDs`.

### Prefund

Routes `8`–`11` signal that a stablecoin-output swap may require liquidity immediately before the user leg. The contract:

1. Quotes the requested output requirement.
2. Builds a stablecoin-to-stablecoin exact-out leg from the configured auto-liquidity asset.
3. Executes that leg from the selected delegate's stablecoin custody account.
4. Executes the user's requested route.

The derived capital provider leg uses the custody account's standing `swapInputAllowance` with `MultiliquidSwap` itself as operator. The user authorizes only the requested leg.

### Sweep

Eligible stablecoin-input routes can sweep the stablecoin balance received by custody into the configured auto-liquidity asset after the requested leg. The sweep:

* Uses the custody balance delta measured inside the transaction
* Executes only when a standing capital provider allowance is present
* Quotes and sets its own exact-in output bound
* Settles atomically with the requested swap

Every derived leg emits its own `Swap` event.

## Asset and Compliance Controls

### RWA Registration

`MultiliquidSwap` records the following for each RWA:

* Acceptance status
* Token address and decimals
* Optional RWA delegate for stateful risk controls

Each accepted RWA also uses a price adapter. An optional whitelist adapter can validate the actual custody sender, receiver, and transfer amount before an RWA leaves custody.

### Stablecoin Registration

`MultiliquidSwap` records the following for each stablecoin:

* Acceptance status
* Token address and decimals
* Stablecoin delegate
* Yield-bearing status

A stablecoin with a delegate can participate in all applicable route families. A registration without a delegate can serve as the non-delegate side of a stablecoin-to-stablecoin route.

### Stablecoin Guardrails

When enabled, the contract compares the stablecoin's configured USD value with its oracle price and requires the percentage deviation to remain within the WAD-scaled band.

### Blacklist

The protocol blacklist applies once per batch to the user, operator, and receiver. Stablecoin delegates can apply an additional blacklist controlled by the capital provider during settlement.

## Access Control

| Role | Capabilities |
| - | - |
| `DEFAULT_ADMIN_ROLE` | Contract upgrades, role administration, and protocol fee vault |
| `OPERATOR_ROLE` | Asset configuration, price and guardrail configuration, fee policy, batch limit, pause, and unpause |
| `BLACKLISTER_ROLE` | Protocol blacklist management |
| `EXTERNAL_PAUSER_ROLE` | Pause-only operational authority |

Fee schedule and auto-liquidity setters are callable only through the registered stablecoin delegate, which applies capital provider admin authorization.

## Unified Swap Event

Every requested and internally derived leg emits:

```solidity theme={null}
event Swap(
    address indexed user,
    bytes32 indexed assetInID,
    bytes32 indexed assetOutID,
    address operator,
    address receiver,
    uint256 routeId,
    bytes32 stablecoinDelegateID,
    uint256 amountIn,
    uint256 amountOut,
    uint256 issuerFeeAmt,
    uint256 spreadFeeAmt,
    uint256 lpFeeAmt
);
```

The event contains enough information to reconstruct route direction, execution identity, selected capital provider domain, resolved amounts, and fee allocation for each leg.

> [card] [Next: Stablecoin Delegate Contracts](https://docs.multiliquid.xyz/evm/contracts/stablecoin-delegate.md)
>
> Learn how capital provider domains manage settlement, custody, fees, and liquidity


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.