# What is Orbit Protocol

## Overview

Orbit Protocol is a decentralized finance (DeFi) platform built on the **Stellar** network. It issues fully‑collateralized, multi‑currency stablecoins through a secure **Collateralized Debt Position (CDP)** system. By locking **Stellar Lumens (XLM)** and **Etherfuse Bonds** as collateral, users mint stablecoins pegged to real‑world fiat currencies, gaining predictable purchasing power without exiting the crypto ecosystem.

## Purpose

Orbit unlocks five principal use‑cases:

1. **Borderless Payments** – Stablecoins settle in seconds on Stellar, letting individuals and businesses send money internationally for a fraction of a cent while avoiding crypto‑market volatility.
2. **Inflation Shield** – In regions with volatile local currencies, users can lock crypto once and draw a USD‑, EUR‑, or MXN‑denominated stablecoin. Even if the local currency depreciates, they repay the same fiat value, preserving purchasing power.
3. **Composable Liquidity for Builders** – oUSD, oEUR, and other Orbit stablecoins act as drop‑in collateral or settlement assets for perps, lending pools, payroll rails, and other Soroban dApps. This shared liquidity layer accelerates DeFi innovation on Stellar.
4. **FX Risk Management for Businesses** – Exporters, freelancers, and Web3 treasuries can hold earnings in oEUR, oMXN, or oJPY to hedge receivables and payables without relying on costly banking rails or OTC desks.
5. **Local Commerce & Payroll** – Merchants and DAOs can price goods, services, and salaries in local‑currency stablecoins so users avoid USD conversion fees yet retain price stability.

Together, these goals advance financial inclusion by lowering remittance costs, protecting savings, mitigating currency risk, and giving developers the tools to build next‑generation financial products.

## Architecture & Flow

1. **Deposit Collateral** – Users transfer XLM into a **Blend** lending pool; the smart contract records the collateral value and required safety margin.
2. **Mint Stablecoins** – The **Orbit Treasury** mints *oUSD, oEUR, oMXN* (or other supported tokens) up to the user’s borrowing limit.
3. **Utilise** – Stablecoins can be swapped on Stellar AMMs, deposited into yield dApps, spent via on‑chain FX paths, or off‑ramped through partners.
4. **Repay & Redeem** – Users repay principal plus accrued interest to unlock their XLM at any time.
5. **Pegkeeper Safeguards** – If collateral falls below the liquidation threshold, the **Pegkeeper** liquidates the vault and arbitrages price discrepancies; any surplus flows to the designated fee‑taker.

## Key Features

* **Collateralised Borrowing** – Over‑collateralisation and on‑chain price feeds guard against market swings.
* **Pegkeeper Automation** – Smart‑contract liquidations and arbitrage maintain each stablecoin’s 1:1 peg without manual intervention.
* **Low‑Cost FX Routing** – Stellar’s pathfinding finds best‑rate swaps, reducing friction for cross‑border transfers.
* **Composability** – Orbit stablecoins integrate with any Soroban dApp; developers can plug into the CDP system or build layered products such as perp exchanges, savings vaults, or on‑chain payroll.

## Benefits

* **Predictable Value** – Shield holdings from crypto volatility.
* **Capital Efficiency** – Access liquidity without selling long‑term XLM positions.
* **Global Inclusion** – Supply a reliable medium of exchange in economies affected by inflation or capital controls.
* **Open & Auditable** – All contracts are open‑source and verifiable on the Stellar blockchain.


# Ecosystem Participants

Orbit aims to mint **asset-backed, on-chain stablecoins for&#x20;*****any*****&#x20;fiat currency**—USD, EUR, MXN, INR, NGN, and beyond. That global reach unlocks:

* **Borderless commerce:** merchants settle in their home currency while customers pay in theirs.
* **Local-currency DeFi:** users in emerging markets earn on-chain yield without dollar exposure.
* **FX hedging & remittances:** traders and families move value instantly between currencies without banking friction.

Keeping this multi-currency engine running safely requires several incentive-aligned actors:

| Role                                            | What They Do                                                                                                                                                                    | Why It Matters for Multi-Currency Stablecoins                                                                              |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| **DAO** (Decentralized Autonomous Organization) | Token-holders propose and vote on parameters—collateral ratios, interest curves, new fiat listings.                                                                             | Governance lets local communities champion the next currency they need, so Orbit grows where demand is strongest.          |
| **Treasury** (Smart Contract)                   | Mints fresh Orbit coins (oUSD, oEUR, oMXN, …) and supplies them to **Blend** lending pools. Coins start unbacked and become fully collateral-backed once borrowers lock assets. | A single, auditable minting contract keeps issuance rules identical across all currencies, preventing fragmentation.       |
| **Borrowers**                                   | Lock crypto (ETH, BTC, XLM, …) to draw the stablecoin they actually need—e.g., oKES to pay Kenyan contractors or oJPY to hedge exposure.                                        | Borrower demand transforms “unbacked” supply into fully collateral-backed units and seeds liquidity in many local markets. |
| **PegKeeper** (Smart Contract)                  | Monitors each stablecoin’s oracle price and deploys incentives (mint/burn fees, open-market ops) to reel it back to target.                                                     | Different currencies face different volatility patterns; per-currency tuning keeps every Orbit coin hugging its peg.       |
| **Liquidators**                                 | Buy under-collateralized positions at a discount, repaying the debt and seizing collateral (using PegKeeper liquidity if needed).                                               | Fast liquidations are crucial when FX rates swing and collateral values diverge across currency pools.                     |
| **Arbitrage Traders**                           | Exploit price gaps between Orbit DEX pairs, CeFi exchanges, and off-chain FX markets.                                                                                           | Profit-seeking keeps oEUR ≈ €1, oINR ≈ ₹1, etc., across every venue.                                                       |
| **Backstop Providers**                          | Deposit into each Blend pool’s Backstop Module; if liquidations lag, the module auctions these deposits to cover bad debt (providers earn fees for taking the risk).            | Backstops are siloed by currency pool, so issues in one market (say oARS) can’t spill into another (oUSD).                 |

**Bottom line:** A transparent minting Treasury, per-currency risk modules, and market incentives let Orbit deliver the first truly global suite of stablecoins—giving anyone, anywhere, digital cash in the unit of account they actually live in.


# Smart Contracts

#### Treasury Contract

The Treasury smart contract is authorized to mint the stablecoins to supply to the Blend. This ensures the availability of stablecoins within their respective lending pools. The treasury can also provide flash loans to the dedicated pegkeeper in order to ensure the stablecoin has enough liquidity.

[Learn more about the Treasury contracts.](/technical-documentation/treasury)

#### **Bridge Oracle Contract**

The Bridge Oracle contract is responsible for providing a price feed to the Blend lending pool. The Treasury stablecoins do not have a price feed on creation, but are pegged to fiat currency. The Bridge Oracle will get the price of this fiat currency from a third party oracle and return the right price for the stablecoin.

[Learn more about the Bridge Oracle.](/technical-documentation/bridge-oracle)

#### Pegkeeper Contract

The PegKeeper. contract is designed to liquidate, settle debts of the blend pool, and trade on an AMM using flash-loaned tokens from the Treasury.

[Learn more about the PegKeepers.](/technical-documentation/pegkeeper)


# Whitepaper

Orbit: XLM backed Decentralized Stablecoin\
Zenith Protocols

**Abstract:** OrbitCDP is a decentralized finance (DeFi) platform built on the Stellar blockchain, designed to provide stablecoins through a Collateralized Debt Position (CDP) system. Users can overcollateralize their cryptocurrency to borrow stablecoins in an array of currencies.

**Introduction:** Starting in 2014, Stellar was designed to connect individuals to the global financial system through an open and decentralized protocol. Anchors, trusted entities within this network, hold deposits and issue backed tokens, serving as crucial bridges between various currencies and Stellar. Traditional financial systems often operate on a fractional reserve basis, Stellar’s anchors and other stablecoin issuers, due to their centralized structure, may also adopt similar practices. They have the flexibility to either hold full fiat reserves for all issued tokens or operate with fractional reserves, underscoring the balance between trust, transparency, and regulatory compliance.

OrbitCDP enhances this ecosystem by introducing collateral-backed stablecoins for various fiat currencies through collateralized debt position (CDP) based smart contracts. This innovation provides access to global currencies, allowing users to engage in transactions with enhanced stability, security, and auditability. By offering stablecoins not only for the dollar but also for the euro, yen, peso, and other major currencies, OrbitCDP expands the Stellar ecosystem beyond centrally backed stablecoins. This advancement aims to unlock global economic potential by making money more fluid, markets more open, and people more empowered.\
CDP Stablecoins: A Collateralized Debt Position (CDP), known as a Vault in MakerDAO, is a DeFi smart contract used to generate the stablecoin DAI. Users deposit volatile cryptocurrencies like ETH as collateral, allowing them to mint DAI based on a Collateralization Ratio (CR). The DAI represents a debt accruing interest (Stability Fee). To unlock collateral, users repay DAI plus fees. If collateral value drops too low, it’s liquidated to cover the debt. External price feeds and governance by MKR token holders ensure system stability and solvency.

**Orbit Architecture:**

* Treasury Contract: All stablecoins are managed by one Orbit Treasury smart contract, authorized to mint the stablecoins to supply to the Blend lending pool and also burn tokens from the pool. This ensures the availability of stablecoins within the lending pool. The treasury can also provide flash loans to the dedicated pegkeeper to enable it to perform arbitrage trades, in order to ensure the stablecoin has enough liquidity.
* Blend Pool: Users would deposit collateral into the blend pool to borrow the stablecoin they want. This collateral could be XLM, but also bonds like CETES and USTRY. Conversely, when they want to retrieve their collateral, users can do so by returning their borrowed stablecoins plus interest to the pool. Through this process the Blend pool will algorithmically calculate the interest rate for both lending and borrowing stablecoin, which will be the way to encourage and discourage users from borrowing stablecoins.
* Backstop Module: The backstop module in the Blend protocol functions as a reserve pool of funds that acts as first-loss capital for each isolated lending pool, meaning it covers losses before any impact on lenders’ funds. Specifically, each lending pool has its own dedicated backstop funds, which are crucial for pool management operations. These funds come from both deposits from users and taking part of the interest paid to the pool, a percentage given by the backstop take rate. These deposits can be withdrawn at any time; however, initiating a withdrawal moves the funds into a 30-day withdrawal queue. This delay ensures that the backstop module retains its ability to serve as effective lender insurance. The user can retrieve their funds after this queue period, provided the backstop module does not have any outstanding bad debt.
* PegKeeper: Curve Finance implemented pegkeepers which is an automated smart contract mechanism designed to stabilize the price of crvUSD, ensuring it remains pegged to the US dollar. In Orbit protocol the pegkeeper helps keeping the protocol healthy by performing liquidations making use of flash loans. It then sells the liquidated positions to an AMM to repay the flash loan. This system enhances currency stability by performing liquidations on the blend pool for users. Users are encouraged to submit profitable liquidations to the treasury, which then uses the pegkeeper perform them. Users initiating profitable liquidations are rewarded with a share of the profits.
* Bridge Oracle: The Bridge Oracle contract ensures that the stablecoins' prices are accurately reflected in the system by bridging their prices to corresponding fiat currencies. This is crucial for maintaining accurate lending and borrowing operations within the blend pool.

**Usage of Blend:** Instead of building everything in house we are spreading out responsibilities as mentioned before. Blend’s framework facilitates the permissionless creation of isolated lending pools, offering significant adaptability to meet emerging market needs without compromising security or capital efficiency. This is crucial for CDP stablecoin issuance, where risk management and operational flexibility are paramount. Furthermore, Blend’s market-driven backstop system for pool curation maintains appropriate risk levels dynamically, enhancing the resilience of stablecoin operations. The protocol also features a dynamic interest rate model that adjusts based on asset utilization, optimizing capital efficiency and making stablecoin issuance economically viable over time. Operating as an ungoverned, modular protocol, Blend streamlines adjustments to pool parameters in response to market conditions, offering a decentralized and efficient foundation for stablecoin management.

**Interest:** Interest rates play a crucial role in any financial system by serving as a mechanism to balance supply and demand for capital. Interest rates are necessary to incentivize users to either supply or demand the stablecoin, thus helping to maintain its peg to a stable asset, typically a fiat currency like the US dollar. When the demand for Orbit stablecoins exceeds its supply, an increase in interest rates encourages users to supply more Orbit stablecoins, increasing its availability in the market and stabilizing its value. Conversely, when there is an excess supply of Orbit stablecoins, lowering interest rates incentivizes users to borrow Orbit stablecoins, thereby reducing its supply and preventing its value from deviating from the intended peg. Therefore, interest rates serve as a critical tool in stabilizing the value of decentralized stablecoins and ensuring their usability within the broader financial ecosystem.

The different parameters from the interest rate formula are adjustable by the DAO, more details on this can be read in the litepaper. Users must overcollateralize their position to protect against liquidation due to price fluctuations, the degree of this overcollateralization depends on the nature and volatility of the collateral. This setup ensures debt positions remain secure. Furthermore, stablecoins cannot be used as collateral, maintaining system integrity. This robust structure supports reliable interest rates, ensuring stability for borrowers and sufficient liquidity for the platform.

**Risk Management and Pegging:** The system has built-in mechanisms to prevent collapse, including overcollateralization and liquidation. Additionally, the pegkeeper can be used to liquidate users using flash loans, helping to keep the protocol healthy as described above. Orbit also uses a backstop module to finance liquidations, a pool of funds that acts as first-loss capital for the lending pool. The pool’s backstop funds are specific to that pool and are extensively used in pool management to protect the system from undercollateralized positions.

Blend Capital. “Backstop Module.” Blend Whitepaper, January 2024, <https://docs.blend.capital/whitepaper/blend-whitepaper>

MakerDAO. “Dai Stablecoin System.” December 2017. <https://makerdao.com/whitepaper/DaiDec17WP.pdf>.

Curve Finance. “Curve Stablecoin Whitepaper.” Available at: <https://github.com/curvefi/curve-stablecoin/blob/master/doc/curve-stablecoin.pdf>.


# Litepaper

**Orbit makes extensive use of the Blend protocol for its lending pools. In setting up these pools there are several parameters that need to be determined before deployment. This litepaper aims to offer insight in the way Orbit functions through these pools and the parameter choices that make this possible.**

### Usage of Blend pools

The Blend pools in the Orbit protocol are used for the minting and distributing of Orbit stablecoins. This works as follows:

The treasury supplies a Blend pool with a certain amount of unbacked Orbit stablecoins, a supply which from that moment on can only be altered by the dao. Users can subsequently take these stablecoins out of the pool by putting up collateral (thereby also providing backing for the coins).

### Settings overview

Listed below are the chosen parameter values for the XLM/oUSD Blend pool from Orbit protocol, these can be altered later on by the dao. These values allow the protocol to function in the ways described in this litepaper and the Orbit whitepaper. For a further deepdive in the functions and possibilities of these parameters, the Blend whitepaper is recommended.

| Parameter              | Strong FX (USD/EUR/GBP) | XLM  | USTRY | CETES |
| ---------------------- | ----------------------- | ---- | ----- | ----- |
| **C-factor**           | 0                       | 0.75 | 0.9   | 0.85  |
| **L-factor**           | 1                       | 0    | 0     | 0     |
| **Rbase**              | 0.005                   | 0    | 0     | 0     |
| **R1**                 | 0                       | 0    | 0     | 0     |
| **R2**                 | 0.02                    | 0    | 0     | 0     |
| **R3**                 | 0.1                     | 0    | 0     | 0     |
| **ReactivityConstant** | 0.000004                | 0    | 0     | 0     |
| **Target Util**        | 0.8                     | 0    | 0     | 0     |
| **Max Util**           | 0.95                    | 1    | 1     | 1     |

The backstop take rate is set to 0.2, which means that 20% of the accrued interest goes to the backstop, to provide the backstop with enough liquidity to ensure the robustness of the protocol.

### Interest rates

Blend makes use of an interest rate model with three legs, dependent on the utilization of the asset in question. As the utilization moves, the interest rate will adjust dynamically in order to incentivize users to bring the utilization closer to its target.

The first leg is for a utilization U lower or equal to the target utilization:

$$
IR\_{1}(U) = RM\*(R\_{base}+ {\frac U U\_T} \*R\_1)
$$

The second leg is for a utilization between the target value and 0.95:

$$
IR\_{2}(U) = RM\*(R\_{base}+R\_1+ {\frac {U-U\_T} {0.95-U\_T}} \*R\_2)
$$

The third leg can be seen as a kind of ‘emergency interest rate’ which only kicks in when the utilization exceeds 0.95:

$$
IR\_{3}(U) = RM\*(R\_{base}+R\_1+R\_2)+ {\frac {U-0.95} {0.05}} \*R\_3
$$

With RateModifier (RM) at a given time ‘t’:

$$
RateModifier\_{t} = UtilRateError \* ReactivityConstant + RateModifier\_{t-1}
$$

The graph below displays the interest rates for strong FX without the rate modifier. As can be seen the rates will start of quite low, but increase as the utilization exceeds its target. Ideally, the dao would increase the supply before the highest interest rates come into play. The dao could also alter the interest rates themselves by changing the different R-values and the target utilization.

![image](https://github.com/user-attachments/assets/726d3575-1b3f-4281-899c-fad1f028b6cb)

### Collateral and liability factors

Apart from the interest rates, the collateral and liability factors are also important settings for the pools, since these determine just how much collateral has to be put up in order to borrow an Orbit stablecoin from the protocol. This works as follows:

The maximum amount a user can borrow with a certain amount of collateral is given by the borrow limit:

$$
BorrowLimit=\sum CollateralFactor\*CollateralValue
$$

To calculate the value of the amount to borrow we make use of the following formula:

$$
EffectiveLiabilityValue = {\frac {LiabilityValue} {LiabilityFactor} }
$$

To prevent the Orbit stablecoins to be used as collateral themselves, we set their C-factor to 0, while their L-factor is set to 1. For XLM, the L-factor is set to 0 to prevent the XLM from being borrowed and the C-factor to 0,75. This means that a user would have to put up XLM worth 133% of the value of the desired stablecoins. This way the debt position is fairly well protected against liquidation due to price changes.

### Emissions configuration

In the case that the Orbit protocol pool gets in Blend’s reward zone, the emissions will be distributed entirely among the oUSD borrowers. As with the other settings, this can be updated at any time by the dao.

### Max positions

The max number of positions a user can hold in the pool is set to 6, which is the recommended number from Blend for assets such as Orbit stablecoins.

###


# Treasury

The Treasury contract serves as the central bank of the Orbit Protocol, responsible for controlling the issuance of stablecoins, managing their supply, and facilitating peg maintenance operations.

## Stablecoin Management

The Treasury manages stablecoins throughout their lifecycle within the protocol, from initial creation to supply adjustments.

### Adding Stablecoins

Stablecoins are added to the protocol through the Treasury by calling the `add_stablecoin()` function.

```rust
fn add_stablecoin(e: Env, token: Address, blend_pool: Address)
```

This function:

* Maps a stablecoin token to its corresponding Blend pool
* Can only be called by the admin (the DAO contract)
* Verifies the Blend pool exists through the factory
* Checks if the stablecoin is already registered

### Supply Control

The Treasury precisely controls the circulating supply of each stablecoin through two complementary functions:

```rust
fn increase_supply(e: Env, token: Address, amount: i128)
fn decrease_supply(e: Env, token: Address, amount: i128)
```

When increasing supply:

1. The Treasury mints the specified amount of the stablecoin
2. The minted tokens are deposited into the corresponding Blend pool
3. The internal supply counter is updated

When decreasing supply:

1. The Treasury withdraws tokens from the Blend pool
2. Verifies the withdrawal succeeded
3. Burns the withdrawn tokens to reduce the total supply

Both operations require administrative privileges and emit appropriate events.

### Claiming Interest

The Treasury can collect interest accrued from stablecoin deposits in Blend pools:

```rust
fn claim(e: Env, reserve_address: Address, to: Address) -> i128
```

When interest is claimed:

1. The contract calculates interest by comparing the current B-rate value to the original deposit
2. The interest amount is withdrawn from the Blend pool
3. Withdrawn tokens are sent to the specified recipient

### Keep Peg Mechanism

The Treasury provides a mechanism for maintaining stablecoin pegs through the `keep_peg()` function:

```rust
fn keep_peg(e: Env, name: Symbol, args: Vec<Val>)
```

This function:

1. Extracts token address, amount, and Blend pool from the args
2. Validates parameters and checks for registered Blend pool
3. Mints the requested amount to the Pegkeeper
4. Invokes the specified function on the Pegkeeper
5. Handles the return of tokens
6. Burns the returned tokens

## Administration

The Treasury provides administrative functions to manage protocol configuration.

### Setting the Pegkeeper

The Pegkeeper address can be updated by the admin:

```rust
fn set_pegkeeper(e: Env, pegkeeper: Address)
```

This function updates the stored Pegkeeper address and emits an event recording the change.

### Setting the Admin

The admin address can be updated by the current admin:

```rust
fn set_admin(e: Env, admin: Address)
```

This function updates the admin address and emits an event recording the change.

### Contract Upgrades

The Treasury supports upgradability through Soroban's native upgrade mechanism:

```rust
fn upgrade(e: Env, new_wasm_hash: BytesN<32>)
```

This function allows the admin to upgrade the contract to a new implementation while preserving all contract storage.

## Contract Initialization

The Treasury is initialized with three key parameters:

```rust
fn __constructor(e: Env, admin: Address, factory: Address, pegkeeper: Address)
```

During initialization:

* The admin address is set (the DAO contract)
* The factory address is stored for validating Blend pools
* The Pegkeeper address is configured
* An initialization event is emitted

All future administrative operations will require authorization from this admin address.

## Errors

The Treasury contract may produce the following errors:

* `AlreadyAddedError` (1507): Attempting to add a stablecoin that's already registered
* `InvalidAmount` (1502): Providing zero or negative amount for supply changes
* `BlendPoolNotFoundError` (1506): Operating on a token without a registered Blend pool
* `InvalidBlendPoolError` (1508): Providing an invalid Blend pool address
* `NotEnoughSupplyError` (1504): Insufficient supply when attempting to decrease supply
* `FlashloanFailedError` (1503): Failed token return during peg maintenance
* `NoInterestToClaim` (1509): No interest available when attempting to claim

## Events

The Treasury emits events for all major operations:

* `initialize`: Contract initialization with admin and pegkeeper addresses
* `add_stablecoin`: Registration of a new stablecoin with its Blend pool
* `increase_supply`: Supply increase with token and amount
* `decrease_supply`: Supply decrease with token and amount
* `claim`: Interest claim with reserve, recipient, and amount
* `keep_peg`: Peg maintenance operation with token and amount
* `set_pegkeeper`: Pegkeeper address update
* `set_admin`: Admin address update


# Bridge Oracle

The Bridge Oracle contract provides reliable price feeds for the Orbit Protocol by connecting different assets to their reference values. It serves as a critical price discovery mechanism that enables accurate asset valuations within the protocol.

## Price Feed Management

The Bridge Oracle manages price feeds by mapping assets to their reference counterparts and retrieving price data from specialized oracle sources.

### Asset Mapping

Assets are mapped to their reference assets using the `add_asset()` function:

```rust
fn add_asset(e: Env, asset: Asset, to: Asset)
```

This function:

* Creates a mapping between the source asset and its reference asset
* Can only be called by the admin
* Allows bridging between Stellar assets and external assets
* Emits an event recording the mapping

### Price Retrieval

The Bridge Oracle provides price data through the `lastprice()` function:

```rust
fn lastprice(env: Env, asset: Asset) -> Option<PriceData>
```

When retrieving prices:

1. The contract looks up the reference asset for the requested asset
2. Based on the type of reference asset, it routes the request to the appropriate oracle:
   * For Stellar assets, it queries the Stellar oracle
   * For USD, it returns a fixed value of 1 with the current timestamp
   * For other external assets, it queries the external oracle
3. Returns the price data if available, or None if not found

### Decimal Precision

The contract provides information about the decimal precision used by the Stellar oracle:

```rust
fn decimals(env: Env) -> u32
```

This function relays the decimal precision information from the underlying Stellar oracle.

## Administration

The Bridge Oracle provides administrative functions to manage protocol configuration.

### Setting Oracle Sources

The data sources for the Bridge Oracle can be updated using:

```rust
fn set_oracles(e: Env, stellar_oracle: Address, other_oracle: Address)
```

This function:

* Updates the addresses for both the Stellar and external oracles
* Can only be called by the admin
* Emits an event recording the change

### Setting the Admin

The admin address can be updated by the current admin:

```rust
fn set_admin(e: Env, new_admin: Address)
```

This function updates the admin address and emits an event recording the change.

### Contract Upgrades

The Bridge Oracle supports upgradability through Soroban's native upgrade mechanism:

```rust
fn upgrade(e: Env, new_wasm_hash: BytesN<32>)
```

This function allows the admin to upgrade the contract to a new implementation while preserving all contract storage.

## Contract Initialization

The Bridge Oracle is initialized with three key parameters:

```rust
fn __constructor(e: Env, admin: Address, stellar_oracle: Address, other_oracle: Address)
```

During initialization:

* The admin address is set (the DAO contract)
* The Stellar oracle address is configured
* The external oracle address is configured
* An initialization event is emitted

All future administrative operations will require authorization from this admin address.

## Events

The Bridge Oracle emits events for all major operations:

* `init`: Contract initialization with admin and oracle addresses
* `add_asset`: Creation of a new asset mapping
* `set_oracles`: Update to oracle sources
* `set_admin`: Admin address update


# PegKeeper

The Pegkeeper contract is a critical component of the Orbit Protocol that maintains stablecoin pegs through automated market operations. It executes liquidations and performs AMM trades to ensure stablecoin stability.

## Operational Mechanism

The Pegkeeper works by participating in liquidation auctions and trading the acquired collateral, generating profits while simultaneously helping maintain stablecoin pegs.

### Liquidation and Trading

The core functionality of the Pegkeeper is implemented in the `fl_receive()` function:

```rust
fn fl_receive(
    e: Env, 
    token: Address,              // Stablecoin address
    amount: i128,                // Received amount
    blend_pool: Address,         // Blend pool address
    auction: Address,            // Auction contract address
    collateral_token: Address,   // Collateral token address
    lot_amount: i128,            // Amount of collateral to withdraw
    liq_amount: i128,            // Liquidation percentage (0-100)
    amm: Address,                // AMM address for swaps
    min_profit: i128,            // Minimum acceptable profit
    fee_taker: Address           // Address to receive profits
)
```

When this function is called, it performs a sequence of operations:

1. Verifies that the call is authorized by the Treasury
2. Records the initial token balances
3. Participates in the liquidation auction through the Blend pool
4. Verifies that the liquidation successfully closed the position
5. Swaps the acquired collateral for the original token
6. Calculates the profit from the operation
7. Ensures the operation is profitable
8. Transfers the profit to the fee taker
9. Approves the Treasury to take back the original amount
10. Emits an event recording the operation

All of these steps must complete successfully, or the function will revert with an appropriate error.

## Liquidation Process

The Pegkeeper uses the helper `liquidate()` function to participate in liquidation auctions:

```rust
fn liquidate(
    e: &Env,
    auction_creator: Address,
    token_a: Address,
    token_a_bid_amount: i128,
    token_b: Address,
    token_b_lot_amount: i128,
    blend_pool: Address,
    liq_amount: i128
) -> Positions
```

This function:

1. Creates a set of liquidation requests:
   * An auction request with the liquidation percentage
   * A repayment request with the bid amount
   * A collateral withdrawal request for the expected lot
2. Transfers the bid amount to the Blend pool
3. Submits the requests to the Blend pool
4. Returns the remaining positions after liquidation

## AMM Integration

The Pegkeeper integrates with AMMs through the helper `swap()` function:

```rust
fn swap(
    e: &Env,
    pair: Address,
    token_a: Address,
    token_b: Address,
    amount_a: i128,
    amount_b: i128
)
```

This function:

1. Gets the router address from storage
2. Creates a token path from token A to token B
3. Transfers token A to the pair contract
4. Executes the swap through the router
5. Sets the minimum output amount and deadline

## Contract Initialization

The Pegkeeper is initialized with two key parameters:

```rust
fn __constructor(e: Env, treasury: Address, router: Address)
```

During initialization:

* The Treasury address is stored for authorization
* The router address is stored for AMM operations
* An initialization event is emitted

## Error Handling

The Pegkeeper contract may produce the following errors:

* `NotProfitable` (1505): The operation did not generate the minimum required profit
* `PositionStillOpen` (1507): The liquidation did not successfully close the position

## Events

The Pegkeeper emits events for tracking:

* `init`: Contract initialization with Treasury and router addresses
* `fl_receive`: Successful operation with token and amount details

## Operational Flow

The complete operational flow of a Pegkeeper operation is as follows:

1. The user identifies a liquidatable position in a Blend pool
2. The user calls `keep_peg()` on the Treasury contract, which:
   * Mints the required amount of stablecoins
   * Calls `fl_receive()` on the Pegkeeper
   * Expects repayment of the amount
3. The Pegkeeper executes the liquidation and swap
4. If profitable, the Pegkeeper:
   * Transfers the profit to the fee taker
   * Approves the Treasury to take back the original amount
5. The Treasury verifies repayment and burns the tokens


# DAO

The DAO Utils contract serves as a utility layer that enables the DAO to execute complex operations in a single transaction. It does not hold any administrative privileges itself but provides convenience functions for the DAO to interact with multiple protocol contracts efficiently.

## Soroban Governor Integration

The Orbit Protocol is governed by [Soroban Governor](https://governance.script3.io/), which serves as the DAO for the protocol. The DAO Utils contract enhances this integration by providing simplified methods for the DAO to execute common administrative actions that involve multiple contracts.

## Contract Functions

### Creating New Stablecoins

The DAO can deploy new stablecoins through the `new_stablecoin()` function:

```rust
fn new_stablecoin(
    e: Env,
    admin: Address,
    treasury: Address,
    oracle: Address,
    token: Address,
    asset: Asset,
    blend_pool: Address,
    initial_supply: i128
)
```

This function orchestrates all the steps required to deploy a new stablecoin:

1. Maps the stablecoin token to its reference asset in the Bridge Oracle
2. Registers the stablecoin with its Blend pool in the Treasury
3. Mints the initial supply of the stablecoin through the Treasury

For this operation, the admin (DAO) must authorize the transaction.

### Managing Supply

The DAO can adjust stablecoin supply using the `update_supply()` function:

```rust
fn update_supply(e: Env, admin: Address, treasury: Address, token: Address, amount: i128)
```

This function:

* Allows increasing supply by providing a positive amount
* Allows decreasing supply by providing a negative amount
* Automatically calls the appropriate Treasury function based on the sign of the amount
* Requires admin (DAO) authorization


# System Diagram

<figure><img src="https://3265088548-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIAfQqCs9TsbTm6qiL2iC%2Fuploads%2FmoCTaACg663gcOzaOZbK%2FOrbit%20Diagrams%20Lucidchart.png?alt=media&amp;token=e966e40b-e08b-4871-81bb-3d26bb05b927" alt=""><figcaption></figcaption></figure>


