> ## 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.

# Swap for a user

> Submit a swap with another wallet's assets, authorized by a standing allowance or a signed EIP-712 permit.

An operator is any wallet that calls `swap` for a different `user`: a relayer, an execution desk, or a smart account module. The user's tokens move, so the user must authorize the operator first, in one of two ways.

## Choose an authorization

| | Standing allowance | Signed permit |
| - | - | - |
| The user | Sends one transaction | Signs one EIP-712 message, and sends nothing |
| It covers | One operator and one input asset, up to an amount | The exact legs, operator, receiver, and deadline that the user signed |
| It lasts | Until it is spent or reduced | One transaction |
| The output goes to | The user only | Any receiver the user signed |

Both only authorize the operator. The user's ERC-20 approval to the capital provider's delegate is still what lets the tokens move.

## Before you start

* **Bounded legs.** Build and bound each leg as in [Swap on-chain](https://docs.multiliquid.xyz/evm/guides/integration.md#3-quote-and-set-your-bound). The user authorizes those bounds.
* **The user's approval.** The user approves the delegate of each leg's `stablecoinDelegateID` for the input token, as in [step 4 of Swap on-chain](https://docs.multiliquid.xyz/evm/guides/integration.md#4-approve-the-delegate).
* **An operator wallet** with ETH for network fees. The user, the operator, and the receiver must all be off the protocol blacklist.
* **One SDK client for each party.** The examples use `mlAsUser`, whose wallet client signs as the user, and `mlAsOperator`, whose wallet client signs as the operator. [Swap on-chain](https://docs.multiliquid.xyz/evm/guides/integration.md#1-connect) shows how to create a client.

## Use a standing allowance

Use a standing allowance when the same operator swaps for the user repeatedly, and the output always returns to the user.

**1. The user grants the allowance**

The allowance belongs to one operator and one input asset ID. `amount` is added to what remains.

```typescript theme={null}
await mlAsUser.swap.adjustSwapInputAllowance({
  operator: operatorAddress,
  assetInID: usdcID,
  amount: 1_000_000_000n, // 1,000 USDC
  increase: true,
});
```

**2. The operator swaps**

The operator sends the leg with no permit. The receiver must be the user.

```typescript theme={null}
const hash = await mlAsOperator.swap.swap({
  user: userAddress,
  receiver: userAddress,
  inputs: [boundedLeg],
});
```

Each delegated leg spends its resolved input from the allowance, so an exact-out leg spends what it actually cost, not its maximum. An allowance of `2n ** 256n - 1n` is unlimited and never decreases. To reduce an allowance, call `adjustSwapInputAllowance` with `increase: false`. Read the remainder with `mlAsUser.swap.getSwapInputAllowance(user, operator, assetInID)`.

## Use a signed permit

Use a permit when the user signs each swap, when the output goes to another wallet, or when the user should not send a transaction.

**1. The operator prepares the legs**

Build the bounded legs, choose the receiver, and set a deadline a few minutes ahead, in Unix seconds.

```typescript theme={null}
const legs = [boundedLeg];
const deadline = BigInt(Math.floor(Date.now() / 1000) + 10 * 60);
```

**2. The user signs**

`signSwapApproval` reads the user's current nonce and signs the `SwapBatchApproval` message with the user's wallet.

```typescript theme={null}
const permit = await mlAsUser.swap.signSwapApproval({
  operator: operatorAddress,
  receiver: receiverAddress,
  inputs: legs,
  deadline,
});
// permit = { deadline, signature, nonce, unordered: false }
```

**3. The operator simulates and submits**

The operator sends the same user, receiver, legs, and permit, in the same order. Any change invalidates the signature.

```typescript theme={null}
const swapCall = {
  user: userAddress,
  receiver: receiverAddress,
  inputs: legs,
  permit,
};

// Simulate as the operator, then send.
await publicClient.call({
  account: operatorAddress,
  to: deployment.addresses.multiliquidSwap,
  data: mlAsOperator.swap.buildSwapCalldata(swapCall),
});
const hash = await mlAsOperator.swap.swap(swapCall);
```

The signature binds the user, the operator, the receiver, every field of every leg in order, the nonce, the deadline, the chain, and the `MultiliquidSwap` address. Only the operator it names can submit it. A permit cannot be used for a direct swap: if the operator is the user, the contract rejects it.

A successful swap consumes the permit's nonce. If the transaction reverts, the nonce is not consumed, so the operator can retry the same permit before its deadline.

### Ordered and unordered nonces

By default a permit uses the user's ordered nonce, `nonces(user)`, which rises by one with each permit used. A user with several permits outstanding must sign them with consecutive nonces, and they must settle in that order. Any permit signed with a nonce that has already been used fails.

An unordered permit instead uses any nonce the user has not used, so independent permits can settle in any order. Choose a random 256-bit nonce and pass `unordered: true`:

```typescript theme={null}
import { randomBytes } from "node:crypto";

const nonce = BigInt(`0x${randomBytes(32).toString("hex")}`);

const permit = await mlAsUser.swap.signSwapApproval({
  operator: operatorAddress,
  receiver: receiverAddress,
  inputs: legs,
  deadline,
  nonce,
  unordered: true,
});
```

The user can cancel an unordered permit before it settles, even while the contract is paused:

```typescript theme={null}
await mlAsUser.swap.invalidateUnorderedNonce({ nonce });
```

### Smart accounts and external signers

The contract accepts:

* **Externally owned accounts:** a 65-byte ECDSA signature, or a 64-byte compact EIP-2098 signature.
* **EIP-7702 delegated accounts:** the account key's ECDSA signature, with an ERC-1271 check as a fallback.
* **Smart contract accounts:** ERC-1271. `isValidSignature` must return `0x1626ba7e` for the EIP-712 digest.

For a contract account, a multisig, or a custody platform, build the typed data without signing it, and have the signer sign it:

```typescript theme={null}
const typedData = mlAsOperator.swap.buildSwapApprovalTypedData({
  user: smartAccountAddress,
  operator: operatorAddress,
  receiver: receiverAddress,
  inputs: legs,
  nonce: await mlAsOperator.swap.getSwapNonce(smartAccountAddress),
  deadline,
});
```

The typed data uses the domain `{ name: "MultiliquidSwap", version: "2", chainId, verifyingContract }` with the `MultiliquidSwap` address as the verifying contract. [MultiliquidSwap](https://docs.multiliquid.xyz/evm/contracts/multiliquid-swap.md#eip-712-permits) lists every type.

## When something goes wrong

| Error | What happened | What to do |
| - | - | - |
| `InsufficientSwapAllowance` | There was no permit, and the allowance was below the leg's input or the receiver was not the user | Raise the allowance, set the receiver to the user, or use a permit |
| `InvalidSignature` | The signature does not match the submitted legs, operator, receiver, or nonce, or the nonce was used or cancelled | Ask the user to sign the exact submission again, with the current nonce |
| `InvalidSignature` with a correct signature | The operator is the user, or `unordered` is set without a signature | Send a direct swap with an empty permit |
| `PermitExpired` | The deadline passed before the transaction landed | Ask the user to sign again with a later deadline |
| `InvalidSwapAddress` | The user, the receiver, or the allowance's operator is the zero address | Set the address |
| `UserBlacklisted` | The user, the operator, or the receiver is on the protocol blacklist | Contact the Multiliquid team |
| The token's own transfer error | The user's ERC-20 approval to the delegate is too small | Ask the user to approve the delegate for the leg's input |

Swap errors such as a missed bound or an inadmissible receiver are the same as in [Swap on-chain](https://docs.multiliquid.xyz/evm/guides/integration.md#when-something-goes-wrong).

## Next steps

> [card] [MultiliquidSwap reference](https://docs.multiliquid.xyz/evm/contracts/multiliquid-swap.md)
>
> The `swap` function, permit types, nonces, and events.

> [card] [Auto-sweep](https://docs.multiliquid.xyz/evm/guides/auto-sweep.md)
>
> How a capital provider authorizes the contract to run legs for its own vault.


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