<!-- tempo-docs-context -->
> Source: [/docs/protocol/fees/spec-fee-amm](https://tempo.com/developers/docs/protocol/fees/spec-fee-amm.md)
> Section: [Tempo EVM](https://tempo.com/developers/docs/development.md). Build on Tempo EVM: wallets and keys, payments, transactions and fees, TIP-20 Tokens, contracts, exchange, network details, nodes, protocol specifications, and changelog.
> [Documentation index](https://tempo.com/developers/llms.txt) · [Docs skill](https://tempo.com/developers/SKILL.md)

> Tempo MCP: Use `search`, `find_pages`, `read_page`, and `code` at `https://mcp.tempo.xyz` for Tempo and related documentation.
> If an indexed page is missing or reflects an older site, read this site’s [documentation index](https://tempo.com/developers/llms.txt) and Markdown pages directly.

[**Specification**](https://tempo.com/developers/docs/protocol)

# Fee AMM specification: how fee conversion works

## Abstract

This specification defines a system of one-way Automated Market Makers (AMMs) designed to facilitate gas fee payments from a user using one stablecoin (the `userToken`) to a validator who prefers a different stablecoin (the `validatorToken`). Each AMM handles fee swaps from a `userToken` to a `validatorToken` at one price (0.9970 `validatorToken` per `userToken`), and allows rebalancing in the other direction at another fixed price (approximately 1.0015 `userToken` per `validatorToken`, before integer rounding).

## Motivation

Current blockchain fee systems typically require users to hold native tokens for gas payments. This creates friction for users who prefer to transact in stablecoins.

The Fee AMM is a dedicated AMM for trading between stablecoins, which can only be used by the protocol (and by arbitrageurs rebalancing it to keep it balanced). The protocol automatically collects fees in many different coins and immediately swaps them (paying a constant price) into the token preferred by the validator. Fees accumulate in the FeeManager, and validators can claim them on-demand.

Fixed conversion rates avoid price movement caused by trade size. Rebalancing is available throughout the block as reserves change; fixed pricing does not eliminate competition for available liquidity or validator control over transaction ordering.

## Specification

### Overview

The Fee AMM implements two distinct swap mechanisms:

1. **Fee Swaps**: Fixed-rate swaps at a price of `0.9970` (validator token per user token) from `userToken` to `validatorToken`
2. **Rebalancing Swaps**: Fixed-rate swaps at a price of `1.0015` (user token per validator token) from `validatorToken` to `userToken`

### Core Components

#### 1. FeeAMM Contract

The primary AMM contract managing liquidity pools and swap operations.

##### Pool Structure

```solidity
struct Pool {
    uint128 reserveUserToken;           // Reserve of userToken
    uint128 reserveValidatorToken;      // Reserve of validatorToken
}
```

Each pool is directional: `userToken` → `validatorToken`. For a pair of tokens A and B, there are two separate pools:

* Pool(A, B): for swapping A to B at fixed rate of 0.997 (fee swaps) and rebalancing B to A by paying approximately 0.9985 B per A received
* Pool(B, A): for swapping B to A at fixed rate of 0.997 (fee swaps) and rebalancing A to B by paying approximately 0.9985 A per B received

##### Constants

* `M = 9970` (scaled by 10000, representing 0.9970)
* `N = 9985` (scaled by 10000, representing 0.9985)
* `SCALE = 10000`
* `MIN_LIQUIDITY = 1000`

##### Key Functions

```solidity
function getPool(
    address userToken,
    address validatorToken
) external view returns (Pool memory)
```

Returns the pool structure for a given token pair.

```solidity
function getPoolId(
    address userToken,
    address validatorToken
) external pure returns (bytes32)
```

Returns the pool ID for a given token pair (used internally for pool lookup).

```solidity
function rebalanceSwap(
    address userToken,
    address validatorToken,
    uint256 amountOut,
    address to
) external returns (uint256 amountIn)
```

Executes rebalancing swaps from `validatorToken` to `userToken` at fixed rate of 1.0015 (user token per validator token). Can be executed by anyone. Calculates `amountIn = floor(amountOut * N / SCALE) + 1` (adds one base unit even when the division is exact). Updates reserves immediately. Emits `RebalanceSwap` event.

```solidity
function mint(
    address userToken,
    address validatorToken,
    uint256 amountValidatorToken,
    address to
) external returns (uint256 liquidity)
```

Adds liquidity using only the validator token. For a new pool, the provider receives `floor(amountValidatorToken / 2) - MIN_LIQUIDITY` shares, with `MIN_LIQUIDITY` permanently locked; the deposit must make this amount positive. For an existing pool, shares equal `floor(amountValidatorToken * totalSupply / (V + floor(N * U / SCALE)))`. Only the validator-token reserve increases. Shares are tracked in `liquidityBalances(poolId, account)`, not a separate ERC-20 token. Emits `Mint`.

Minting MUST authorize `msg.sender` as a sender on `userToken`, FeeManager as a recipient on `userToken`, and `to` as a recipient on **both** pool tokens. These requirements apply even though the deposit transfers only `validatorToken`. The underlying deposit also requires the caller's sender authorization and FeeManager's recipient authorization on `validatorToken`, plus the normal balance, pause, receive-policy, and applicable spending-limit checks. Failed issuer-policy authorization reverts with `PolicyForbids`.

```solidity
function burn(
    address userToken,
    address validatorToken,
    uint256 liquidity,
    address to
) external returns (uint256 amountUserToken, uint256 amountValidatorToken)
```

Burns LP tokens and receives pro-rata share of reserves. Emits `Burn` event.

Burning MUST authorize `msg.sender` as a sender on **both** pool tokens, independently of `to`. Each nonzero underlying payout also checks FeeManager as sender and the resolved payout destination as recipient on that token, with ordinary token-transfer restrictions. An authorized `to` cannot redeem shares on behalf of a policy-blocked LP caller. Issuer-policy failures revert with `PolicyForbids`; subsequent issuer-policy changes can therefore prevent redemption.

```solidity
function executeFeeSwap(
    address userToken,
    address validatorToken,
    uint256 amountIn
) internal returns (uint256 amountOut)
```

Executes a fee swap immediately. Calculates `amountOut = (amountIn * M) / SCALE`. Only executed by the protocol during transaction execution. This is an internal operation, not a public ABI method, and does not emit a `FeeSwap` event.

```solidity
function checkSufficientLiquidity(
    address userToken,
    address validatorToken,
    uint256 maxAmount
) internal view
```

Verifies sufficient validator token reserves for the fee swap. Calculates `maxAmountOut = (maxAmount * M) / SCALE`. Reverts if insufficient liquidity.

#### 2. FeeManager Contract

Tempo introduces a precompiled contract, the `FeeManager`, at the address `0xfeec000000000000000000000000000000000000`.

The `FeeManager` is a singleton contract that implements all the functions of the Fee AMM for every pool. It handles the collection and refunding of fees during each transaction, executes fee swaps immediately, stores fee token preferences for users and validators, and accumulates fees for validators to claim via `distributeFees(validator, token)`.

##### Key Functions

```solidity
function setUserToken(address token) external
```

Sets the default fee token preference for the caller (user). Requires token to be a USD TIP-20 token. If the token equals the stored user preference, returns without a storage write or event. Otherwise updates the preference and emits `UserTokenSet`. Access: Direct calls only (not via delegatecall).

```solidity
function setValidatorToken(address token) external
```

Sets the fee token preference for the caller (validator). Requires token to be a USD TIP-20 token. Cannot be called during a block built by that validator. Emits `ValidatorTokenSet` event. Access: Direct calls only (not via delegatecall).

Fee collection and refund are internal execution-handler hooks. They are not exposed through the FeeManager ABI and cannot be invoked by calling the precompile with a special sender. Before execution, the handler collects the maximum fee and validates conversion liquidity. After execution, it refunds the unused amount, executes any conversion, and records fees for the block's fee recipient.

```solidity
function distributeFees(address validator, address token) external
```

Allows anyone to trigger distribution of accumulated fees for a specific token to a validator. Transfers all accumulated fees in the specified token to the validator address. If no fees have accumulated for that token, this is a no-op.

```solidity
function collectedFees(address validator, address token) external view returns (uint256)
```

Returns the amount of accumulated fees for a validator and specific token. Distribution through `distributeFees(validator, token)` is subject to the token-transfer rules below.

### Swap Mechanisms

#### Fee Swaps

* **Rate**: Fixed at m=0.9970 (validator receives 0.9970 of their preferred token per 1 user token that user pays)
* **Direction**: User token to validator token
* **Purpose**: Convert tokens paid by users as fees to tokens preferred by validators
* **Settlement**: Immediate during transaction execution
* **Access**: Protocol only
* **Routing**: If the direct `userToken → validatorToken` pool has insufficient liquidity, the Fee AMM tries one two-hop route through `userToken.quoteToken()`. Both hops must have sufficient liquidity. The validator receives `floor(floor(actualSpending × 9970 / 10000) × 9970 / 10000)` on the two-hop path.

#### Rebalancing Swaps

* **Rate**: Fixed at n=0.9985 (swapper receives 1 of the user token for every 0.9985 that they put in of the validator's preferred token)
* **Direction**: Validator token to user token
* **Purpose**: Refill reserves of validator token in the pool
* **Settlement**: Immediate
* **Access**: Anyone

### Fee Collection Flow

1. **Pre-Transaction**:
   * Protocol determines user's fee token using logic that considers: explicit tx fee token, setUserToken calls, stored user preference, tx.to if TIP-20
   * Protocol calculates the maximum token charge from the gas limit and applicable gas price, converting attodollars to base units with upward rounding
   * `FeeManager.collectFeePreTx(user, userToken, maxAmount)` is called:
     * If user token differs from validator token, checks AMM has sufficient liquidity via `checkSufficientLiquidity()`
     * Collects maximum fee from user using `transferFeePreTx()`
   * If any check fails (insufficient balance, insufficient liquidity), transaction is invalid

2. **Post-Transaction**:
   * Calculate the actual token charge as `ceil(gasUsed * effectiveGasPrice / 10^12)`
   * `FeeManager.collectFeePostTx(user, maxAmount, actualUsed, userToken)` is called:
     * Validator token and fee recipient are inferred from `block.coinbase`
     * Calculates refund: `refundAmount = maxAmount - actualUsed`
     * Refunds unused tokens to user via `transferFeePostTx()`
     * If user token differs from validator token and `actualUsed > 0`, executes fee swap immediately via `executeFeeSwap()`
     * Accumulates swapped fees for the validator

3. **Fee Distribution**:
   * Validators (or anyone) can call `distributeFees(validator, token)` at any time to transfer accumulated fees to the validator

### Fee-policy authorization

Before fee collection, the fee token MUST authorize the fee payer as sender. FeeManager's recipient authorization is not required for this protocol fee deposit. Refunds of unused fees to the original payer skip issuer recipient-policy and receive-policy evaluation, including when the transaction has paused the token. These exemptions apply only to the internal fee lifecycle, not public liquidity operations or fee distribution.

A nonzero `distributeFees` transfer MUST check FeeManager as sender and the resolved validator as recipient, with ordinary pause and receive-policy behavior. A receiver-policy rejection holds the distribution in ReceivePolicyGuard. If issuer policy blocks FeeManager as sender, distribution MUST revert even when collecting same-token fees succeeded. `collectedFees` records an accounting entitlement, not a guarantee that current token policy permits payout.

### Events

```solidity
event RebalanceSwap(
    address indexed userToken,
    address indexed validatorToken,
    address indexed swapper,
    uint256 amountIn,
    uint256 amountOut
)
event Mint(
    address sender,
    address indexed to,
    address indexed userToken,
    address indexed validatorToken,
    uint256 amountValidatorToken,
    uint256 liquidity
)
event Burn(
    address indexed sender,
    address indexed userToken,
    address indexed validatorToken,
    uint256 amountUserToken,
    uint256 amountValidatorToken,
    uint256 liquidity,
    address to
)
event UserTokenSet(address indexed user, address indexed token)
event ValidatorTokenSet(address indexed validator, address indexed token)
```

`Transfer` events are emitted as usual for transactions, with the exception of paying gas fees via TIP20 tokens. For fee payments, a single `Transfer` event is emitted post execution to represent the actual fee amount consumed (i.e. `ceil(gasUsed * effectiveGasPrice / 10^12)` token base units).

### Gas

Fee swaps are designed to be gas-free from the user perspective. The pre-tx and post-tx steps in each transaction do not cost any gas.
