# Emergency Shutdown

<figure><img src="https://2441370967-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fu8CvMeTMwSaHYwChGoRz%2Fuploads%2FFiH3oo7uIppkiecnDQ9t%2FFXD_EmergencyShutdown.drawio.png?alt=media&#x26;token=29515821-8ca2-4463-999d-8d2fa7d1940c" alt=""><figcaption><p>Emergency Shutdown</p></figcaption></figure>

The emergency shutdown process for Fathom's FXD is a comprehensive mechanism designed to safeguard both the protocol and its users in a significant crisis. This process is crucial for maintaining stability in decentralized finance (DeFi) systems. The emergency shutdown facilitates the return of excess collateral from safe positions. It allows for the return of collateral to those who give back FXD to the protocol, using a specific FXD to Collateral conversion ratio determined during the emergency shutdown. Here's a detailed explanation of the Fathom protocol's emergency shutdown procedure:

#### 1. **Initiating Emergency Shutdown**

* **Caging the Protocol**: The shutdown process starts with the protocol owner calling the [`cage`](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/ShowStopper.sol#L113) function in the [**ShowStopper**](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/ShowStopper.sol) contract. This action halts most activities within the protocol and is irreversible. The `_cageCooldown` period is the time allotted for calling the accumulateBadDebt function before the `finalizeDebt` function is executed.

{% code overflow="wrap" %}

```solidity
function cage(uint256 _cageCoolDown) external;
```

{% endcode %}

* **Caging Specific Collateral Pools**: The [`cagePool`](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/ShowStopper.sol#L132) function is then called to initiate the shutdown for a particular collateral pool type, marking a point of no return for that pool.

{% code overflow="wrap" %}

```solidity
function cagePool(bytes32 _collateralPoolId) external;
```

{% endcode %}

* **Accumulating Bad Debt**: The [`accumulateBadDebt`](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/ShowStopper.sol#L151) function, is called for all positions, leaving each with a certain amount of excess collateral. All positions within the protocol must undergo this process. If any positions have not been processed by users using `accumulateBadDebt`, the protocol administrator must ensure that all remaining positions are appropriately managed.

{% code overflow="wrap" %}

```solidity
function accumulateBadDebt(bytes32 _collateralPoolId, address _positionAddress) external;
```

{% endcode %}

* **Redeeming Locked Collateral**: Position owners can then use the [`redeemLockedCollateral`](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/ShowStopper.sol#L247) function to transfer this excess collateral to a specified receiver. The receiver's collateral balance is recorded in the `BookKeeper`.

{% code overflow="wrap" %}

```solidity
function redeemLockedCollateral(
    bytes32 _collateralPoolId,
    address _positionAddress,
    address _collateralReceiver,
    bytes calldata /* _data */
) external;
```

{% endcode %}

#### 3. **Returning FXD and Retrieving Collateral**

* **Finalizing Debt and Price**: After dealing with bad debt by calling  [`accumulateBadDebt`](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/ShowStopper.sol#L151) function for all the positions, the [`finalizeDebt`](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/ShowStopper.sol#L180) function is called to fix the debt amount, followed by the [`finalizeCashPrice`](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/ShowStopper.sol#L195) function to set a conversion ratio from FXD to collateral. `finalizeDebt` function will revert if there will be remaining `systemSurplus`.

{% code overflow="wrap" %}

```solidity
function finalizeDebt() external;
```

{% endcode %}

* **Depositing FXD**:  FXD Owners deposit their FXD into the system using the [stablecoinAdapterDeposit](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/proxy-actions/FathomStablecoinProxyActions.sol#L184) function in the  [FathomStablecoinProxyActions](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/proxy-actions/FathomStablecoinProxyActions.sol) contract. Since the `FathomStablecoinProxyActions` contract serves as a library for the [ProxyWallet](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/proxy-wallet/ProxyWallet.sol)  contract, calls to the `stablecoinAdapterDeposit` function need to be well-encoded and executed using the [execute](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/proxy-wallet/ProxyWallet.sol#L19) function of the `ProxyWallet`, owned by the FXD owner. When encoding the function call, the `_positionAddress` argument must match the address of the FXD Owner depositing FXD into the protocol.

{% code overflow="wrap" %}

```solidity
function stablecoinAdapterDeposit(
    address _adapter,
    address _positionAddress,
    uint256 _stablecoinAmount, // [wad]
    bytes calldata _data
) public;
```

{% endcode %}

{% code overflow="wrap" %}

```solidity
function execute(bytes memory _data) public payable returns (bytes memory _response);
```

{% endcode %}

* **Whitelisting and Accumulating Stablecoin**: FXD owners must [whitelist](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/BookKeeper.sol#L203) the ShowStopper contract in the [BookKeeper](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/BookKeeper.sol) contract to allow FXD/Collateral manipulation. They then call [accumulateStablecoin](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/ShowStopper.sol#L214C5-L214C60) to move the FXD accounting from the `BookKeeper` to the `ShowStopper`’s `stablecoinAccumulator`.

{% code overflow="wrap" %}

```solidity
function accumulateStablecoin(uint256 _amount) external;
```

{% endcode %}

* **Redeeming Stablecoin for Collateral**: FXD owners use [redeemStablecoin](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/ShowStopper.sol#L228) to transfer collateral from the ShowStopper to their account (EOA) within the `BookKeeper`.

{% code overflow="wrap" %}

```solidity
function redeemStablecoin(bytes32 _collateralPoolId, uint256 _amount) external;
```

{% endcode %}

#### 4. **Final Withdrawal of Collateral**

* **Caging the** [**CollateralTokenAdapter**](https://github.com/Into-the-Fathom/fathom-stablecoin-smart-contracts/blob/master/contracts/main/stablecoin-core/adapters/CollateralTokenAdapter/CollateralTokenAdapter.sol): This action signifies the end of the process for depositing FXD and retrieving collateral. The owner of the protocol does the caging.
* **Emergency Withdrawal**: Finally, users can call the emergency withdrawal function to withdraw their collateral.

{% code overflow="wrap" %}

```solidity
function emergencyWithdraw(address _to) external;
```

{% endcode %}

#### 5. **Responsibility of Users**

* **Adhering to Process**: Users are advised to follow the steps specified to reduce confusion and ensure a smooth process.
* **Bearing Consequences of Deviation**: If a user deviates from the prescribed process and incurs a loss, they bear the responsibility for their actions.

#### **6. Responsibility of the protocol**

* **Providing instruction:** In times of emergency, the Fathom protocol team should provide user-friendly interfaces to ensure that users do not have to deal with overly technical tasks, such as encoding a function call and directly calling the smart contracts.
* **Skimming all the positions**: The protocol administrator must ensure that all positions are processed using the `accumulateBadDebt` function before the `coolDownPeriod` ends to ensure the correct execution of the emergency shutdown process.
* **Settling systemBadDebt and withdrawing systemSurplus**: The protocol administrator must ensure that the `systemBadDebt` is settled using the systemSurplus, and all the surplus (if any is left) is withdrawn before the `finalizeDebt` function is called.

#### Summary of the Fathom's FXD Emergency Shutdown

The emergency shutdown of Fathom's FXD is an intricate, irreversible, multi-step process crucial for preserving the stability and security of the decentralized finance (DeFi) system during significant crises. This procedure involves several key stages:

1. **Initiating Emergency Shutdown**: The process begins with halting most protocol activities through the cage function in the `ShowStopper` contract, marking a no-return point. The cooldown period following this action allows for the necessary processing of positions.
2. **Handling Excess Collateral from Positions**: The `accumulateBadDebt` function, essential for managing excess collateral, must be applied to all positions. This responsibility falls to the protocol administrator if not completed by users. Subsequently, position owners can transfer excess collateral using the `redeemLockedCollateral` function.
3. **Returning FXD and Retrieving Collateral**: After handling bad debt, the `finalizeDebt` function is called to solidify the debt amount, followed by the `finalizeCashPrice` function for setting the FXD to collateral conversion ratio. FXD owners must deposit their tokens using the `stablecoinAdapterDeposit` function, which requires precise encoding and execution. They also need to whitelist the `ShowStopper` contract for FXD/Collateral manipulation, followed by using `redeemStablecoin` to transfer collateral.
4. **Final Withdrawal of Collateral**: The process concludes with caging the `CollateralTokenAdapter` and the final step of `emergencyWithdraw` by users to reclaim their collateral.
5. **User and Protocol Responsibilities**: Users must adhere to the specified process sequence to minimize confusion and prevent losses. Any deviation leading to losses falls under the user's responsibility. On the protocol's end, providing user-friendly interfaces during emergencies and ensuring all positions are skimmed within the cooldown period is critical for smooth shutdown execution. The protocol administrator is also responsible for settling system bad debt and withdrawing any remaining system surplus before calling `finalizeDebt`.
