# M0 Extensions

> Documentation of M0 Extensions, the application layer for building custom stablecoins on the M0 platform, including the SwapFacility for seamless 1:1 conversions.

## What Are M0 Extensions?

M0 Extensions are the **application layer** of the M0 Protocol. They are custom ERC-20 stablecoins that developers build on the M0 platform, inheriting its security and yield properties while adding their own unique features, branding, and business logic.

Think of M0 as the secure, collateralized foundation -- like digital infrastructure. Extensions are the applications, products, and user experiences built on top of this foundation.

### The Extension Architecture

```text
Your Custom Stablecoin (Extension)
        | wraps/unwraps
    M0 (Foundation)
        | backed by
    US Treasury Collateral
```

**Key Relationship:** Extensions are backed 1:1 by eligible collateral, meaning:

- 1 Extension Token = 1 unit of value (always redeemable)
- Extensions inherit the M0 platform's stability and regulatory clarity
- Extension contracts can earn yield (if approved by governance)
- Developers control how that yield flows to users, treasuries, or other destinations

### Why Build an Extension?

#### Full Customization

- **Yield Distribution**: Route yield to users, treasury, or split however you want
- **Access Controls**: Implement KYC, geographic restrictions, or institutional-only access
- **Fee Mechanisms**: Add transaction fees, management fees, or revenue sharing
- **Branding**: Create a fully branded stablecoin (YourAppUSD) or keep it generic

#### Inherited Benefits

- **Regulatory Clarity**: Built on M0's compliant, audited infrastructure
- **Shared Liquidity**: Tap into the M0 ecosystem's shared liquidity layer
- **Cross-Chain Ready**: Deploy on any chain where M0 operates
- **Battle-Tested Security**: Leverage M0's proven collateral and governance systems

#### Business Value

- **Control**: Unlike integrating someone else's stablecoin, you own the user relationship
- **Revenue**: Capture value through yield management and optional fees
- **Flexibility**: Evolve your stablecoin's features as your needs change

### Common Extension Types

#### Treasury Extensions

Route 100% of yield to a single treasury address while providing users with a stable, non-rebasing token experience.

**Use Cases**: Protocol treasuries, ecosystem development funds, corporate reserves

#### User Yield Extensions

Share yield with token holders while taking a small protocol fee for sustainability.

**Use Cases**: DeFi protocols, consumer apps, yield savings accounts

#### Institutional Extensions

Provide granular, per-account control with custom fee arrangements and whitelisting.

**Use Cases**: Prime brokerages, fintech platforms, institutional treasury management

### Who Should Build Extensions?

**Recommended for:**

- **Application Developers**: Games, payments, DeFi protocols wanting branded stablecoins
- **Ecosystem Builders**: L1/L2 chains needing native stablecoins for their ecosystems
- **Fintech Companies**: Businesses requiring custom compliance or yield distribution
- **Treasury Managers**: Organizations needing yield-bearing accounts with specific controls

**Consider Wrapped $M instead if:**

- You just need standard DeFi integration (AMM pools, lending markets)
- You prefer using an existing, established token rather than deploying your own

### Real-World Examples

- [**Wrapped $M**](/protocol/wrapped-m): The "reference implementation" showing standard DeFi compatibility
- [**Noble USD**](https://dollar.noble.xyz/): Cross-chain stablecoin serving the Cosmos ecosystem

### Technical Overview

Extensions are smart contracts that:

1. **Inherit from MExtension.sol**: A base contract providing core wrap/unwrap functionality
2. **Implement Custom Logic**: Add your unique features, access controls, and yield distribution
3. **Gain Earner Approval**: Get governance approval to earn yield
4. **Deploy Anywhere**: Launch on Ethereum, L2s, or any supported chain

**Key Functions Every Extension Must Implement:**

- `wrap(recipient, amount)`: Convert to your extension token
- `unwrap(recipient, amount)`: Convert your extension token back
- Custom yield claiming/distribution logic (your choice how this works)

### Getting Started

Ready to build your own stablecoin? The [Build section](/build/overview) provides everything you need:

- **Model Selection Guide**: Choose the right template for your use case
- **Step-by-Step Deployment**: Deploy and configure your extension
- **Earner Approval Process**: Get governance approval for yield earning
- **Integration Examples**: Real code examples and best practices

## SwapFacility Deep Dive

### Architecture Overview

SwapFacility serves as the universal router for the M0 Extension ecosystem, enabling atomic conversions between any
approved M0 Extensions. The contract maintains minimal state while relying on the TTG governance system for extension
approval and access control.

#### Core Dependencies

- **M Token Base**: The foundational rebasing token that backs all extensions
- **TTG Registrar**: Governance-controlled registry that maintains the approved earners list
- **ReentrancyLock**: Advanced protection using transient storage for atomic operations

### Swap Operations

#### Extension-to-Extension Swaps

```solidity
function swap(address extensionIn, address extensionOut, uint256 amount, address recipient) external
```

**Process Flow:**

1. Validates both extensions are approved earners via `_revertIfNotApprovedExtension()`
2. Transfers extension tokens from user to SwapFacility
3. Calls `extensionIn.unwrap()` to convert to $M
4. Measures actual `$M` received (accounts for rounding differences in v1 extensions)
5. Approves and calls `extensionOut.wrap()` to mint target extension tokens

#### Direct `$M` Token Operations

```solidity
function swapInM(address extensionOut, uint256 amount, address recipient) external
function swapOutM(address extensionIn, uint256 amount, address recipient) external
```

**Access Control Differences:**

- `swapInM`: Anyone can convert `$M` to extensions
- `swapOutM`: Requires `M_SWAPPER_ROLE` or permission for specific extension

### Permission System

#### Two-Tier Extension Model

1. **Standard Extensions**: Open for general extension-to-extension swaps
2. **Permissioned Extensions**: Require special authorization for `$M` conversions

```solidity
function setPermissionedExtension(address extension, bool permissioned) external
function setPermissionedMSwapper(address extension, address swapper, bool allowed) external
```

#### Role-Based Access

- `DEFAULT_ADMIN_ROLE`: Contract administration and upgrades
- `M_SWAPPER_ROLE`: Global permission for `swapOutM` operations on standard extensions

### Security Features

#### Advanced Reentrancy Protection

The contract inherits from `ReentrancyLock` which implements transient storage-based locking:

```solidity
modifier isNotLocked() {
    if (Locker.get() != address(0)) revert ContractLocked();
    address caller_ = isTrustedRouter(msg.sender) ? IMsgSender(msg.sender).msgSender() : msg.sender;
    Locker.set(caller_);
    _;
    Locker.set(address(0));
}
```

#### Trusted Router System

For complex integrations (like UniswapV3SwapAdapter), trusted routers can specify the original caller:

- Direct calls: `msg.sender` is stored as the locker
- Trusted router calls: `IMsgSender(msg.sender).msgSender()` retrieves the original user

Extensions can call `swapFacility.msgSender()` to get the true transaction initiator.

#### Governance Integration

All extension approvals are checked against the TTG Registrar:

```solidity
function _isApprovedEarner(address extension) private view returns (bool) {
    return IRegistrarLike(registrar).get(EARNERS_LIST_IGNORED_KEY) != bytes32(0) ||
           IRegistrarLike(registrar).listContains(EARNERS_LIST_NAME, extension);
}
```

### Gas Optimization

#### Permit Integration

All swap functions include permit variants supporting both EIP-2612 and EIP-712 signatures:

```solidity
function swapWithPermit(..., uint256 deadline, uint8 v, bytes32 r, bytes32 s) external
function swapWithPermit(..., uint256 deadline, bytes calldata signature) external
```

#### Balance Tracking Precision

For compatibility with Wrapped `$M` v1, the contract measures actual balance changes:

```solidity
uint256 mBalanceBefore = _mBalanceOf(address(this));
IMExtension(extensionIn).unwrap(address(this), amount);
amount = _mBalanceOf(address(this)) - mBalanceBefore;
```

### Technical Implementation

#### Immutable Architecture

```solidity
address public immutable mToken;
address public immutable registrar;
```

Core dependencies are immutable for security, while operational parameters remain upgradeable.

#### State Management

The contract maintains minimal state:

- `permissionedExtensions`: Extensions requiring special authorization
- `permissionedMSwappers`: Authorized swappers for specific permissioned extensions

#### Event System

```solidity
event Swapped(address indexed extensionIn, address indexed extensionOut, uint256 amount, address indexed recipient);
event SwappedInM(address indexed extensionOut, uint256 amount, address indexed recipient);
event SwappedOutM(address indexed extensionIn, uint256 amount, address indexed recipient);
```

### Economic Guarantees

SwapFacility maintains perfect 1:1 value relationships by design:

- No slippage or trading fees
- Atomic execution prevents arbitrage
- All conversions preserve dollar parity
- Extensions remain fully backed by eligible collateral

The contract creates implicit liquidity between all M0 Extensions without requiring separate AMM pools, enabling
seamless cross-extension value transfer.
