# Welcome

Welcome to the Genius Bridge Protocol (GBP) documentation. GBP is the first cross-chain interoperability layer that behaves like a capital-efficient liquidity network—not just a router. Designed for ultra-low latency and universal chain compatibility, it enables seamless token swaps across EVM and non-EVM chains, combining CEX-level UX with uncompromising decentralization.

### What is GBP?

GBP is a novel intent-based interoperability protocol that allows users and dApps to execute complex, cross-chain token operations through a single abstracted interface. It abstracts away the complexity of multi-hop routing, liquidity discovery, bridging, and swap finality. GBP supports both Ethereum-based and non-EVM ecosystems, offering native interop across networks like Solana, Arbitrum, Base, and others.

### Why GBP?

Legacy bridges are route coordinators, not liquidity sources. Users must stitch together multiple protocols, and swaps are often delayed, expensive, or restricted to homogenous environments (e.g., EVM-only). As a response, intents-based bridges have emerged. These cross-chain bridges operate as routing layers, not liquidity sources. Protocols like Across and deBridge rely on third-party solvers who temporarily front liquidity on the destination chain and later settle net balances. This model avoids custody, requires no capital base, and offers agility—but it comes at a cost. Because these systems don't hold user funds, they can't generate yield, issue receipt tokens, or reward LPs. All in-flight capital belongs to external actors, making native, protocol-driven yield structurally impossible.

Genius Bridge Protocol (GBP) inverts this model. It doesn't coordinate liquidity—it *is* the liquidity. When users deposit USDC, it's held directly in protocol-owned Vaults deployed on each supported chain. These Vaults aren't idle—they actively drive swaps, absorb order flow, and form the basis for native yield. GBP captures execution fees from every cross-chain swap and distributes them to LPs via **usdGG**, a fully redeemable, yield-bearing receipt token. This yield is not synthetic, speculative, or reliant on emissions. It’s a native byproduct of GBP’s role as a capital source and execution layer.

By embedding execution logic into the Lit Protocol’s decentralized MPC network, GBP maintains full determinism and decentralization without relying on a permissioned solver set. Execution is triggered based on blockchain events and carried out by Lit nodes using threshold-signed instructions. Vault balances are constantly monitored, and rebalancing actions are triggered when needed—ensuring the protocol remains solvent, capital-efficient, and chain-agnostic. Competing bridges would need to re-engineer from first principles to replicate this model. GBP becomes more than a bridge. It becomes a productive dollar primitive.

### Key Features

* **Intent-Based Automation:** Users sign what they want done—GBP handles the how.
* **Deterministic, Decentralized Execution:** Powered by Lit Protocol’s threshold MPC network.
* **Native Yield Mechanism:** All LPs earn swap fees via usdGG, no staking or wrapping required.
* **Universal Chain Access:** Works seamlessly across EVM and non-EVM environments.
* **Execution Latency:** Finality in 5–8 seconds across most supported chains.
* **Capital Efficiency:** Up to 98% cheaper than other cross-chain systems.

### Supported Chains

| Chain     | Type    | Status |
| --------- | ------- | ------ |
| Ethereum  | EVM     | ✅ Live |
| Base      | EVM     | ✅ Live |
| Optimism  | EVM     | ✅ Live |
| Arbitrum  | EVM     | ✅ Live |
| Avalanche | EVM     | ✅ Live |
| BNB Chain | EVM     | ✅ Live |
| Polygon   | EVM     | ✅ Live |
| Solana    | Non-EVM | ✅ Live |


# Thesis

### Onchain Finance: The Post-Bridge Reality

The collapse of centralized infra catalyzed a flight to safety — not just of custody, but of *composability*. The core question today isn’t “where are your assets held?” — it’s **“what does your liquidity do while idle?”**

Yet even now:

* **Cross-chain flow is rent-extractive.** Bridges consume capital for settlement but do not return value to users or LPs.
* **Stablecoin velocity is inefficient.** Most cross-chain swaps or bridging functions simply pass tokens from A to B — no flow accounting, no fees accrued, no yield.
* **Bridges are opaque.** Users face fragmented UX, hidden slippage, and no transparency on routing logic or underlying economic flows.

Despite the structural importance of bridging in the multichain era, **most bridge designs operate as stateless pipes** — instead of programmable, fee-generating systems.

This is the gap Genius Bridge Protocol is designed to close.

***

### The GBP Thesis

**GBP is a universal swap + settlement router that captures value from cross-chain flow and redirects it back to users.**

It is built around three core insights:

1. **Every token transfer is a yield event.** Every time liquidity moves between chains or assets, value is created. Genius makes that value extractable — for LPs, protocols, and end users — without adding friction.
2. **Bridges should be engines, not pipes.** GBP treats flow as programmable — dynamically routing based on gas, slippage, pathing, and economic return — with deterministic, onchain accounting.
3. **Settlement assets should pay you.** When you bridge, swap, or stake — your destination token shouldn’t be inert. It should be productive. This is the role of **usdGG**.

***

### Introducing usdGG: Yield-Native Collateral

**usdGG is a fully-backed stablecoin (1:1 USDC) that passively accrues yield from all protocol fees generated by GBP.**

Unlike wrapped assets or rebasing stablecoins, usdGG is:

* **Non-custodial.** Minted by LPs who deposit USDC into Genius-controlled liquidity pools.
* **Auto-yielding.** Fees from cross-chain swaps are streamed to LPs pro-rata, with no active staking or lockup.
* **Composable.** usdGG is ERC-20 standard and usable anywhere USDC is — as collateral, liquidity, or settlement.

This transforms the typical stablecoin role from **idle medium of exchange** to **yield-generating unit of account**.

In short: **holding usdGG = earning from the entire bridge economy.**

***

### The Opportunity

As capital rotates across chains and asset classes, the infrastructure that *routes, settles, and monetizes flow* will become the backbone of DeFi. Genius sits at that intersection:

* **Bridge → Swap → Yield** is a single flow.
* **User action → Protocol revenue → LP return** is a closed loop.
* **Liquidity routing → Settlement token → Onchain accounting** is a native feedback system.

Where current bridges are silent pipes, Genius is a **value-capturing flywheel**.

***


# Architecture Overview

## Protocol Architecture

### Architecture Overview

Genius Bridge Protocol (GBP) is an intent-based, cross-chain execution layer designed to enable deterministic and transparent routing of liquidity across chains. Unlike probabilistic bridges or liquidity networks that rely on external relayers or generalized message passing, GBP enforces strict execution rules, asset custody constraints, and liquidity accounting to ensure solvency, capital efficiency, and yield traceability. The protocol is engineered around a few core architectural primitives—Lit-based intent authentication, Orchestrator Wallets for deterministic liquidity control, and vault-based modular execution logic—that together facilitate a new class of yield-bearing stablecoin, usdGG.

At its foundation, GBP functions as a coordination layer for liquidity providers (LPs) to deposit USDC into chain-specific vaults, which the protocol uses to execute cross-chain swaps. These swaps are user-generated intents, cryptographically signed and verified using the Lit Protocol network. Every swap constitutes an atomic settlement event: users sign off-chain intents, which are verified by Lit Actions, executed by GBP, and finalized via canonical bridge adapters. The protocol guarantees that swaps execute only when all preconditions—fees, slippage tolerances, and liquidity availability—are met exactly as specified in the signed payload.

The Lit Protocol and Network documentation can be found here: <https://developer.litprotocol.com/>

### How GBP works

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2FcmcMH752t46ZxCklICb4%2FGeniusModules.png?alt=media&amp;token=8f53371a-cba7-47c6-818d-debda762d00c" alt=""><figcaption></figcaption></figure>

**GBP's execution process follows a deterministic two-phase protocol:**&#x20;

First, users declare their intent and provides a clear breakdown of total costs.

**Source Chain Phase:**

* User submits intent with cryptographic signature
* Router Module converts source asset to USDC via DEX aggregation
* USDC deposited into source chain vault
* Lit Action verifies deposit and coordinates with target chain

\
**Target Chain Phase:**

* Orchestrator Wallet withdraws USDC from target chain vault
* USDC swapped to desired target asset via DEX liquidity
* Asset transferred to user's target address
* Withdrawal event emitted and verified through Lit Action

### Core Components

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2FQ6wOjJnO1ZnRdKmgCoer%2FArchitecture_OverallPicture.png?alt=media&amp;token=bc8cd877-4e94-4c64-81b3-7233fae5f444" alt=""><figcaption></figcaption></figure>

#### 1. Lit protocol

Genius integrates the Lit Protocol as a foundational component for cross-chain execution, eliminating the need for a traditional solver network. Rather than relying on permissioned actors to carry out off-chain logic, Genius leverages Lit’s decentralized threshold cryptography to ensure deterministic and verifiable automation.

Lit operates through Distributed Key Generation (DKG) and Multi-Party Computation (MPC), enabling a set of independent nodes to collaboratively execute arbitrary code tied to programmable conditions—without any single party holding full signing authority. This architecture guarantees censorship resistance and auditability at the execution layer.

The Lit Protocol and Network documentation can be found here: <https://developer.litprotocol.com/>

#### 2. Blockchain Layer

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2FpgMFsu2QSFUCXKTcULxf%2FBlockchain_Architecture.png?alt=media&amp;token=d1947f84-7def-4097-923e-3be63ef633f0" alt=""><figcaption></figcaption></figure>

Genius Vaults are smart contracts that accept deposits and emit pending orders for off-chain services to process. They function as the primary interface for staking USDC, managing user deposits, withdrawals, and distributing protocol fees to liquidity providers.

The GBP protocol integrates with major DEXs and aggregators to fetch real-time pricing data required to fulfill user intents. It standardizes all swaps by converting tokens into USDC, the protocol’s native settlement asset.

In cases where Vaults on a specific chain experience liquidity depletion due to skewed order flow, off-chain services monitor balances and initiate rebalancing operations. These operations utilize cross-chain bridges such as Circle’s CCTP and Wormhole to restore target liquidity levels and maintain protocol solvency.

#### 3. Off-chain Services

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2F9mxBjQUG90VIp3atb91U%2FGBP_Architecture_Goals.png?alt=media&amp;token=ef523aa8-6341-4946-8193-831f2a59d7b6" alt=""><figcaption></figcaption></figure>

The Genius off-chain services are critical infrastructure components that support the operation of the GBP protocol. While external to the on-chain contracts, these services are modular and replicable, preserving the protocol’s decentralization guarantees.

Their primary responsibilities include monitoring supported blockchains for new orders, estimating execution costs, and querying decentralized exchanges and liquidity aggregators to determine optimal swap paths. These services function as trusted data relays, supplying the protocol with actionable execution logic in a permissionless and verifiable manner.

Beyond order execution, they ensure the protocol remains in an operationally sound state by continuously tracking cross-chain liquidity conditions and triggering rebalancing operations when thresholds are breached. Operational telemetry is persistently collected to surface inefficiencies and inform ongoing system-level optimizations.


# usdGG

## Overview

usdGG is a fully backed USD stablecoin (1 usdGG = 1 USDC in reserves) that accrues real yield from cross-chain swap fees on the Genius Bridge Protocol (GBP). Unlike a typical passive USDC holding (which yields 0% when held in a wallet that is not backed by Coinbase), usdGG allows liquidity providers (LPs) to earn a share of protocol fees whenever users swap assets across chains.

The Genius Protocol converts user deposits into USDC (or USDT on certain chains) and holds them in vaults. As cross-chain swaps occur, the protocol collects fees (tiered by swap size) and automatically distributes 90% of those fees to usdGG holders. In essence, usdGG = USDC + continuous fee income, achieved without lending out funds or relying on price oracles (the yield comes solely from swap activity). **To amplify yield without introducing credit risk, Genius integrates** [**M0**](https://docs.m0.org/home/overview/) **as a base-layer for reserve optimization—earning a baseline yield equivalent to the prevailing T-bill rate (\~4%). All swap-based yield is passed back on top of this, allowing usdGG to stack protocol-native income on a risk-free floor.**

Insurance fees are added to the backed USDC to protect against re-orgs and to account for rebalancing fees. This design eliminates traditional counterparty risk from lending, and usdGG's value remains anchored to its USDC reserves at all times. A minimum 25% of each vault's liquidity is kept on-hand to facilitate instant redemptions, ensuring 1:1 convertibility even under heavy usage.


# Fees and Yield

Fee calculations are straightforward and utilize the following formula to determine an average yield

$$
\text{Daily Yield per $1} = (\frac{\text{Daily Volume} \times \text{Weighted Fee Rate} \times \text{LP Share}}{\text{Total usdGG Supply}})+\text{T-bill rate}
$$

<table><thead><tr><th>Transaction Amount</th><th>Fee Rate</th></tr></thead><tbody><tr><td><pre class="language-html"><code class="lang-html">≤ $100 
</code></pre></td><td><pre><code>0.50%
</code></pre></td></tr><tr><td><pre><code>$100 - $1K
</code></pre></td><td><pre><code>0.35%  
</code></pre></td></tr><tr><td><pre><code>$1K - $10K  
</code></pre></td><td><pre><code>0.25%   
</code></pre></td></tr><tr><td><pre><code>> $10K    
</code></pre></td><td><pre><code>0.15%  
</code></pre></td></tr></tbody></table>

For all modeled yield scenarios of how the protocol performs under various real world conditions, please refer to this page:&#x20;

{% embed url="<https://yield.bridgesmarter.com/>" %}


# DeFi—stusdGG

Staked usdGG

### Staked usdGG

\
When users deposit USDC into the Genius Protocol, they receive **usdGG**, a 1:1 fully backed receipt token that passively accrues yield from cross-chain swap fees. The problem is that while usdGG appreciates in value relative to its backing (each token is worth more than 1 USDC over time), it is **non-rebasing and not natively DeFi-compatible** with protocols that expect fixed-value stablecoins. Holding usdGG earns yield, but it cannot easily be used as collateral or LP capital without sacrificing the underlying fee accrual benefits.

To solve this, users can **stake their usdGG to mint&#x20;*****stgusdGG***, a **liquid staking token** (LST) that represents a claim on usdGG + accrued yield. stgusdGG maintains a **fixed 1.0 unit representation**, while usdGG itself appreciates in backing value. When a user wants to exit, they redeem stgusdGG back to usdGG and then usdGG to USDC, receiving the full yield earned during the staking period.

This mirrors what stETH does for Ethereum: it decouples the **yield-bearing asset (usdGG)** from its **liquid wrapper (stusdGG)**, enabling seamless integration with DeFi protocols. A user can hold stgusdGG in Curve, use it as collateral in lending markets, or LP it in Uniswap-style pools – all while their position continues to benefit from swap fee revenue, abstracted away inside the usdGG backing.

\
Comparisons

| Feature                    | usdGG                                                                  | USDC                                        | Aave USDC                                        | USDe (Ethena)                                      |
| -------------------------- | ---------------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------ | -------------------------------------------------- |
| **Backing Type**           | Fully backed 1:1 by USDC held in protocol vaults                       | Centralized fiat reserves (Circle)          | Same as USDC                                     | Synthetic delta-neutral ETH + CEX perp shorts      |
| **Yield Source**           | Organic protocol fees from cross-chain swaps                           | None (0%)                                   | Lending interest from borrowers                  | Funding rate arbitrage via short perps             |
| **Yield Profile**          | Variable, usage-based real yield (0-300%+ APY possible)                | 0%                                          | Market-rate, borrower-dependent (\~3-6%)         | Variable, derived from perp markets (\~8-25%+)     |
| **Yield Risk**             | Swap volume sensitive; no borrower/default risk                        | No yield = no risk                          | Counterparty + utilization rate risk             | High dependency on CEX liquidity + perp rates      |
| **Capital Custody**        | Held in Genus vaults on-chain (non-custodial)                          | Centralized custodians (Circle + banks)     | Custodied in Aave smart contracts                | Held across smart contracts + CEX positions        |
| **Smart Contract Risk**    | Yes – bridge + vault logic risk                                        | No (off-chain risk dominates)               | Yes – protocol risk + liquidation engine         | Yes – complex algorithmic + market-linked risks    |
| **Composability**          | High (via stgUSD)                                                      | Low – passive asset                         | Medium – must borrow to use actively             | Medium – synthetic integrations, evolving support  |
| **DeFi Compatibility**     | Native via stusdGG wrapper                                             | Limited (passive holding)                   | Better (via borrow)                              | Medium – synthetic integrations, evolving support  |
| **Exit Liquidity**         | Instant via protocol vaults (25% reserves)                             | Instant redemption via Circle partners      | Must repay borrow to unlock                      | Liquidity dependent on AMMs + secondary markets    |
| **Redemption Mechanics**   | 1:1 USDC redemption anytime                                            | Centralized redemption (Circle only)        | Must unwind lending position                     | Synthetic unwind logic, not guaranteed 1:1         |
| **Leverage Potential**     | Yes – stusdGG can be collateralized                                    | No                                          | Yes – via borrowing against USDC                 | Yes – yield strategies + structured trades         |
| **Transparency**           | On-chain vault balances + fee flows                                    | Partial – reserves off-chain                | On-chain, but abstracted by lending logic        | Mixed – depends on CEX data + hedge visibility     |
| **Regulatory Risk**        | Moderate – depends on USDC solvency & DeFi                             | High – full reliance on U.S. banking system | Same as USDC                                     | Medium – CEX exposure, less regulatory clarity     |
| **Market Dependency**      | Low – usage-driven (swap volume)                                       | None                                        | High – borrow demand fluctuates                  | Very high – funding rates + market structure       |
| **Token Type**             | Non-rebasing stablecoin (usdGG), with stgUSD as LST wrapper            | Stablecoin                                  | Interest-bearing LP token                        | Synthetic stablecoin                               |
| **Composability Solution** | stusdGG wrapper (1:1 claim on usdGG)                                   | N/A                                         | aUSDC tokens (protocol-specific)                 | Native integrations via synthetic infrastructure   |
| **Yield Claim Mechanism**  | Fee split paid continuously to usdGG, staked via stusdGG               | N/A                                         | Accrues over time, paid on exit                  | Funding captured through hedged perp strategies    |
| **Risk-Reward Tradeoff**   | Transparent, usage-driven yield with known base risk (USDC + protocol) | No yield, low volatility, centralized risk  | Medium yield, borrower risk, smart contract risk | High yield, high complexity, funding/market risk   |
| **Use Case Fit**           | Treasuries, DAOs, LPs seeking real yield + liquidity                   | Passive holding, payments                   | Leveraged lending or farming                     | Speculative yield-seekers with high risk tolerance |


# Risk

Risk Dynamics

## Redemption and Risk Dynamics

### Instant Liquidity & Redemption

usdGG is always redeemable 1:1 for USDC due to a protocol rule: each vault retains 25% of its capital in reserve. LPs can typically withdraw instantly without delays or fees. The remaining 75% is deployed for swaps, and if usage pushes reserves toward the 25% floor, swaps or withdrawals automatically trigger rebalancing.

In rare cases (e.g. mass redemptions or one-way flows), the protocol pauses swaps and routes liquidity from other chains to restore balance. This may cause brief withdrawal delays, but never a freeze—mimicking centralized exchange liquidity with decentralized infrastructure.

**Tradeoff:** Yield is capped by the idle 25%, but this guarantees LPs can always exit, avoiding "trapped capital" risk.

### Behavior Under Stress

If one vault faces major outflows, its reserve may deplete. The system rebalances by bridging funds from other chains. Worst-case delay is the time for a cross-chain transfer—typically seconds to minutes on modern bridges.

Even during outflows, usdGG remains fully backed across all vaults. A governance module can pause activity in critical failure scenarios, though this is a last resort.

**Net Effect:** Risk is auto-managed. High volume = more fees; low volume = reserves stay untouched. In both cases, peg and liquidity remain intact.

### Yield "Cliffs"

usdGG yield can drop to zero if bridge volume dries up, but cannot go negative—fees are never negative, and no rebasing or debt mechanics exist. LPs only earn or exit flat.

### Tail Risks

Core risks are smart contract and bridge failures. An exploit could drain vaults. These are low-probability but real, given DeFi's $2B+ history of bridge hacks. usdGG also inherits USDC's risks—custody, regulatory exposure, and banking instability (e.g. the 2023 SVB-driven depeg).

**Summary:** usdGG adds protocol risk (contracts + bridges) on top of USDC's baseline risks. In exchange, LPs earn elevated yield.


# Quickstart

## For Users

### **1. Connect Your Wallet**

* Visit the Genius Bridge interface at app.bridgesmarter.com
* Click "Connect Wallet"

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2FQYzNNTbGezcZeqW27LRY%2Fimage.png?alt=media&amp;token=4ec58318-73fd-4342-8a28-42b67eadb21b" alt="" width="375"><figcaption></figcaption></figure>

* Choose your wallet provider (MetaMask, Phantom, WalletConnect, etc.)

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2FUvj6eRayAbMSSQNJ8mWc%2Fimage.png?alt=media&amp;token=429c55b5-1e3d-4d26-a12a-b6f1aa4d4b12" alt="" width="188"><figcaption></figcaption></figure>

* Approve the connection

### **2. Select Your Swap**

* **Source Chain**: Choose your tokens on any of the 9 currently supported networks

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2F1PiI8UHFabyicww0SCmP%2Fimage.png?alt=media&amp;token=e474856f-90d0-474c-9227-b989fd0b0068" alt="" width="375"><figcaption></figcaption></figure>

* **Source Token**: Select the token you want to swap

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2FQyJoAvnzi2HmLvWPFYUB%2Fimage.png?alt=media&amp;token=95adb786-d041-476f-81d5-37886e3643de" alt="" width="375"><figcaption></figcaption></figure>

* **Destination Chain**: Choose where you want your tokens

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2FG9FSlSCL6rOk3BKbDce8%2Fimage.png?alt=media&amp;token=7ca3a43f-fdbc-4184-8e83-655105caa495" alt="" width="375"><figcaption></figcaption></figure>

* **Destination Token**: Select the token you want to receive

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2FrYNs0bCRIiDlh595VL1q%2Fimage.png?alt=media&amp;token=ca0d42b3-c1f2-4ee1-abed-5cc9065a68e2" alt="" width="375"><figcaption></figcaption></figure>

* **Amount**: Enter the amount to swap

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2FjBtbFffVbumDJNCBQqXw%2Fimage.png?alt=media&amp;token=cf5c252d-e37d-4cb7-996e-bde1baa5f877" alt=""><figcaption></figcaption></figure>

### **2. Review and execute**

* Review the quote, and execute

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2FQWyikZC9415w4XCcsibv%2Fimage.png?alt=media&amp;token=1233e7cc-9b25-48c4-b038-5ddcb8576368" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3567640876-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3TVL6Da4IxwhMpQsbS0x%2Fuploads%2F5yaOGhlTIbOM0QpXHjeG%2Fimage.png?alt=media&amp;token=e926eb8d-a8ac-4118-880d-d3059ac0175c" alt=""><figcaption></figcaption></figure>

### For Developers

Refer to the API docs section to get started on integrating GBP in your project.


# Developer guide

## API Documentation

The Genius Bridge Protocol provides a comprehensive REST API for developers to integrate cross-chain functionality into their applications. Our API is designed for simplicity, reliability, and performance.

#### Base URLs

* Production: `https://api.geniusbridge.com/v1`
* Staging: `https://genius-bridge-staging-894762848.us-east-2.elb.amazonaws.com/quoting`&#x20;

### Endpoints

TODO: add correct link here

The details of the various available endpoints are present at [here](http://genius-bridge-staging-894762848.us-east-2.elb.amazonaws.com/api/v1/docs)

## SDK integration

#### Installation

```bash
# JavaScript/TypeScript
npm install genius-bridge-sdk
```

#### Basic Setup

TODO: to add

## Executing Solana transactions

When executing cross-chain swaps involving Solana, the GBP API returns an array of base58-encoded Solana transactions that must be executed in a specific sequence. These transactions are designed to work atomically using Jito bundles for optimal execution.

**Transaction Types**

1. **Swap Transactions** (all except last): Convert user's desired token to USDC via aggregators
2. **Order Creation** (last transaction): Creates an order on the Genius Solana Pool

Transactions must be executed in the exact order received:

```
// ❌ Don't execute in parallel
await Promise.all(transactions.map(tx => connection.sendTransaction(tx)));

// ⚠️ Execute sequentially, but not recommended
for (const transaction of transactions) {
  await connection.sendTransaction(transaction);
}
```

**Atomic Execution with Jito Bundles**

For optimal execution, use Jito bundles to ensure atomicity. Details on using jito can be found [here](https://www.quicknode.com/guides/solana-development/transactions/jito-bundles).

Here is a sample implementation of the transaction execution via jito

```
import {
  Connection,
  Keypair,
  PublicKey,
  SystemProgram,
  TransactionMessage,
  VersionedTransaction,
} from '@solana/web3.js';
import bs58 from 'bs58';

export class JitoService {
  private readonly DEFAULT_JITO_FEE = 200000;
  private readonly jitoTipAccounts = [
    'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt',
    'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh',
  ];
  private readonly jitoEndpoints = [
    'https://ny.mainnet.block-engine.jito.wtf/api/v1/bundles',
    'https://tokyo.mainnet.block-engine.jito.wtf/api/v1/bundles',
  ];

  constructor() {}

  /**
   * Gets a random validator key from the validator list
   */
  private getRandomValidatorKey(): PublicKey {
    const randomValidator =
      this.jitoTipAccounts[
        Math.floor(Math.random() * this.jitoTipAccounts.length)
      ];
    return new PublicKey(randomValidator);
  }

  /**
   * Bundles transactions for Jito processing
   */
  public async bundle(
    txs: VersionedTransaction[],
    keypair: Keypair,
    connection: Connection,
    additionalSigners: Keypair[] = [],
  ): Promise<string[]> {
    const abortController = new AbortController();

    try {
      const txNum = Math.ceil(txs.length / 3);
      let successNum = 0;
      const results = [];

      const latestBlockhash = await connection.getLatestBlockhash('confirmed');
      for (let i = 0; i < txNum; i++) {
        const upperIndex = (i + 1) * 3;
        const downIndex = i * 3;
        const newTxs = [];

        for (let j = downIndex; j < upperIndex; j++) {
          if (txs[j]) {
            const message = txs[j].message;
            message.recentBlockhash = latestBlockhash.blockhash;
            const txn = new VersionedTransaction(message);
            txn.sign([keypair]);
            try {
              additionalSigners.forEach((signer) => {
                txn.sign([signer]);
              });
            } catch (error) {
              console.log(
                `Failed to sign transaction for index ${j}: `,
                error,
              );
            }
            newTxs.push(txn);
          }
        }

        const success = await this.bulldozer(
          newTxs,
          keypair,
          connection,
          abortController.signal,
        );
        const { success: successValue } = success;
        console.log('successfully finished bulldozer', success);

        if (success && successValue > 0) successNum += 1;
        results.push(success);
      }
      if (successNum == 0) {
        throw new Error('No successful responses received from Jito');
      }
      const successResults = results?.[0]?.signatures?.map((signature) => {
        return signature;
      });
      if (!successResults || successResults.length == 0) {
        throw new Error(
          'Executing Order SOLANA No successful responses received from Jito - transactions failed',
        );
      }
      return successResults;
    } catch (error) {
      console.log(
        'Executing Order SOLANA JITO Error during transaction execution',
        error,
      );
      return [];
    } finally {
      abortController.abort();
    }
  }

  /**
   * Send transactions to Jito block engine
   */
  public async bulldozer(
    txs: VersionedTransaction[],
    payer: Keypair,
    connection: Connection,
    abortSignal: AbortSignal,
  ) {
    try {
      // Get dynamic JITO fee instead of using constant
      const jitoFee = this.DEFAULT_JITO_FEE;

      const jitoFeeWallet = this.getRandomValidatorKey();
      const latestBlockhash = await connection.getLatestBlockhash('confirmed');
      const jitTipTxFeeMessage = new TransactionMessage({
        payerKey: payer.publicKey,
        recentBlockhash: latestBlockhash.blockhash,
        instructions: [
          SystemProgram.transfer({
            fromPubkey: payer.publicKey,
            toPubkey: jitoFeeWallet,
            lamports: jitoFee,
          }),
        ],
      }).compileToV0Message();

      const jitoFeeTx = new VersionedTransaction(jitTipTxFeeMessage);
      jitoFeeTx.sign([payer]);

      const serializedJitoFeeTx = bs58.encode(jitoFeeTx.serialize());
      const serializedTransactions = [
        serializedJitoFeeTx,
        ...txs.map((tx: VersionedTransaction) => bs58.encode(tx.serialize())),
      ];

      const requests = this.jitoEndpoints.map(async (url) => {
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            jsonrpc: '2.0',
            id: 1,
            method: 'sendBundle',
            params: [serializedTransactions],
          }),
          signal: abortSignal,
        });

        if (!response.ok) {
          console.log('not okay response for url', url);
          return null;
        }

        return response.json();
      });
      const results = await Promise.all(requests.map((p) => p.catch((e) => e)));
      console.log('Executing Order SOLANA jitoresults', { results });

      const successfulResults = results
        .filter((result) => result !== null)
        .filter((result) => !(result instanceof Error));

      if (successfulResults.length > 0) {
        txs.map((tx) =>
          console.log(
            `TX Confirmed: https://solscan.io/tx/${bs58.encode(
              tx.signatures[0],
            )}`,
          ),
        );

        return {
          success: 1,
          signatures: txs.map((tx) => bs58.encode(tx.signatures[0])),
          links: txs.map(
            (tx) => `https://solscan.io/tx/${bs58.encode(tx.signatures[0])}`,
          ),
        };
      } else {
        console.log(`No successful responses received for jito`);
      }

      return {
        success: 0,
        error: 'No successful responses received for jito',
      };
    } catch (error) {
      console.log(
        'Executing Order SOLANA JITO Error during transaction execution',
        error,
      );
      return {
        success: 0,
        error,
      };
    }
  }
}

```


# LIT Actions

#### Lit Actions Overview

**Lit Actions** are immutable JavaScript programs executed in a decentralized environment on the Lit Network. Designed for secure, condition-based automation, they enable blockchain-agnostic execution with native cryptographic primitives such as signing, encryption, and decryption.

Key properties:

* **Language + Runtime:** JavaScript (Deno), with support for selected libraries like `ethers.js` and `@solana/web3.js`.
* **Programmable Signing:** Integrated with **Programmable Key Pairs (PKPs)** to perform threshold-based signing when predefined conditions are met.
* **Cross-Chain Capable:** Interacts with multiple chains (EVM, Solana, etc.) and can query off-chain APIs directly.
* **Decentralized & Verifiable:** Executes on a globally distributed node network, ensuring censorship resistance, determinism, and transparency.

***

#### Lit Actions in Genius Bridge Protocol (GBP)

Within GBP, Lit Actions form the **execution layer** that replaces centralized backends or solver networks. Specifically, they are used to:

* **Monitor On-Chain Events:** Detect order emissions, vault imbalances, and state transitions across supported chains.
* **Trigger Execution Logic:** Initiate swaps, vault rebalancing, or USDC movements across chains using CCTP or Wormhole.
* **Sign Transactions:** Use threshold PKPs to programmatically sign transactions once trigger conditions are met—no single signer, no trusted relayer.
* **Coordinate Cross-Chain State:** Enforce deterministic logic across heterogeneous chains without compromising decentralization or liveness.

Lit Actions are foundational to how Genius achieves *deterministic, decentralized cross-chain automation*—without centralized intermediaries.


# Orchestrators

## Overview

Orchestrators are the core security and execution components of the Genius Protocol's decentralized orchestration system. They are programmable keys that execute sensitive operations on behalf of the protocol, ensuring secure and decentralized management of cross-chain bridge operations.

## What are Orchestrators?

Orchestrators are **Lit programmable keys** that are created with specific Lit actions as their only authorized scopes. They have permissions to perform critical operations on the protocol such as:

* **Filling orders** across different blockchain networks
* **Reverting orders** when necessary
* **Rebalancing liquidity** between supported chains
* **Managing native token refunds** for orchestrator rotation

## Key Characteristics

### Single Responsibility Principle

Each orchestrator is bound to **only one specific responsibility** (e.g., rebalancing, order filling, etc.). This design ensures:

* **Security isolation**: Compromise of one orchestrator doesn't affect others
* **Operational clarity**: Clear separation of concerns
* **Risk mitigation**: Limited scope of potential damage

### Refund Capability

Every orchestrator includes an additional **refund orchestrator** Lit action that allows the protocol to:

* Recover native tokens (ETH, SOL) left on the orchestrator
* Enable safe orchestrator rotation and updates
* Prevent fund loss when retiring orchestrators

## Security Model

### EVM Chains: Lit PKPs (Programmable Key Pairs)

For EVM chains, orchestrators use **Lit PKPs** which leverage **Multi-Party Computation (MPC)**:

```typescript
// Example: Creating an EVM orchestrator PKP
const pkpMintCost = await litContracts.pkpNftContract.read.mintCost();
const tx = await litContracts.pkpHelperContract.write.mintNextAndAddAuthMethods(
  AUTH_METHOD_TYPE.LitAction, // keyType
  actionHashes.map(() => AUTH_METHOD_TYPE.LitAction),
  actionHashes.map((actionHash) => `0x${Buffer.from(bs58.decode(actionHash)).toString('hex')}`),
  actionHashes.map(() => '0x'),
  actionHashes.map(() => [[AUTH_METHOD_SCOPE.SignAnything]]),
  true, // addPkpEthAddressAsPermittedAddress
  true, // sendPkpToItself
  { value: pkpMintCost }
);
```

**Security Benefits:**

* **No single node** ever has access to the complete private key
* **Threshold cryptography** ensures key security
* **Decentralized key management** across the Lit network

### Solana: Lit Encryption

For Solana, PKPs are not available, so orchestrators use **Lit encryption**:

```typescript
// Example: Creating a Solana orchestrator
const orchestrator = Keypair.generate();
const orchestratorSecretKey = bs58.encode(orchestrator.secretKey);

// Encrypt with access control conditions
const encryptedPk = await encryptor.encrypt(
  orchestratorSecretKey,
  accessControlPkOnlyAuthorizedAction
);
```

**Security Benefits:**

* **TEE (Trusted Execution Environment)** protection
* **Encrypted keys** are only decrypted within secure enclaves
* **No node** has access to the complete Solana private key

## Orchestrator Types and Responsibilities

### 1. Rebalancing Orchestrator

**Purpose**: Manages liquidity distribution across supported chains

**Responsibilities**:

* Execute rebalancing instructions
* Transfer liquidity between chains via bridges
* Maintain optimal liquidity ratios
* Handle cross-chain transactions

**Example Usage**:

```typescript
// Rebalancing orchestrator execution
const res = await rebalancingExecutionImpl(
  env,
  orchestratorSolanaPubKey,
  new LitHelpers(),
  RPC_URLS(envVars),
  instructionsResponse,
  actionsBatch
);
```

### 2. Solver Orchestrator

**Purpose**: Fills orders across different blockchain networks

**Responsibilities**:

* Execute order fills on EVM chains
* Execute order fills on Solana
* Handle cross-chain order processing
* Manage transaction execution

### 3. Refund Orchestrator

**Purpose**: Recovers native tokens from orchestrators

**Responsibilities**:

* Withdraw ETH from EVM orchestrators
* Withdraw SOL from Solana orchestrators
* Enable safe orchestrator rotation
* Prevent fund loss during updates

**Example Implementation**:

```typescript
// EVM refund orchestrator
const message = `REFUND_ORCHESTRATOR_${orchestratorAddress}`;
if (!validateEthSignature(message, ownerSignature, OWNER_ADR_EVM(env))) {
  throw new Error('Invalid signature');
}

// Calculate safe transfer amount
const gasCost = BigInt(gasLimit) * BigInt(gasPrice);
const buffer = BigInt(1000000000000);
const safeTransferAmount = BigInt(balance) - gasCost - buffer;

const transferEthTxn = {
  to: OWNER_ADR_EVM(env),
  value: safeTransferAmount.toString(),
  data: '',
  gasLimit,
  gasPrice,
};
```

## Access Control and Permissions

### Lit Action Scopes

Orchestrators are restricted to specific Lit action IPFS hashes:

```typescript
// Access control conditions for orchestrator
const accessControlPkOnlyAuthorizedAction: AccessControlConditions = [
  {
    contractAddress: '',
    standardContractType: '',
    chain: 'ethereum',
    method: '',
    parameters: [':currentActionIpfsId'],
    returnValueTest: {
      comparator: '=',
      value: 'QmerWcM4m4jWyo62LoQJEwjKrjG7c8q7vQB9wc2iA18ptk', // rebalancing action
    },
  },
  { operator: 'or' },
  {
    contractAddress: '',
    standardContractType: '',
    chain: 'ethereum',
    method: '',
    parameters: [':currentActionIpfsId'],
    returnValueTest: {
      comparator: '=',
      value: 'QmYejeXiM1fhmZmrP3neWt7vW7HkFt75bHHVGkBJw5BYJF', // refund action
    },
  }
];
```

### Authorization Checks

All orchestrator actions include authorization validation:

```typescript
// Example: Authorization check in Lit actions
if (!isCallerAuthorizedLit(EXECUTOR_ADR_EVM(env))) {
  throw new Error(`Caller is not authorized. Expected: ${EXECUTOR_ADR_EVM(env)}`);
}
```

## Orchestrator Lifecycle

### 1. Creation

```typescript
// Create orchestrator with specific action scopes
const res = await createOrchestratorBase(new EncryptorLit(), ipfsHashs);
```

### 2. Deployment

* Orchestrator keys are encrypted and stored securely
* Access control conditions are configured
* Lit actions are deployed to IPFS

### 3. Operation

* Orchestrators execute their designated functions
* All operations are logged and monitored
* Failures trigger appropriate error handling

### 4. Rotation/Retirement

* Refund orchestrator recovers native tokens
* New orchestrators can be deployed
* Old orchestrators are safely decommissioned

## Security Considerations

### Key Management

1. **EVM PKPs**: Never expose complete private keys
2. **Solana Keys**: Always encrypted and TEE-protected
3. **Access Control**: Strict IPFS hash-based permissions
4. **Rotation**: Regular key rotation for enhanced security

### Operational Security

1. **Authorization**: All actions require proper authorization
2. **Validation**: Comprehensive input validation
3. **Error Handling**: Graceful failure handling
4. **Monitoring**: Continuous operation monitoring

### Attack Prevention

1. **Replay Protection**: Timestamp-based signature validation
2. **Access Control**: IPFS hash-based action restrictions
3. **Isolation**: Single responsibility per orchestrator
4. **Recovery**: Refund mechanisms for safe rotation

## Best Practices

### Orchestrator Design

1. **Single Responsibility**: Each orchestrator handles one specific function
2. **Minimal Permissions**: Grant only necessary permissions
3. **Refund Capability**: Always include refund functionality
4. **Error Handling**: Implement comprehensive error handling

### Security Implementation

1. **Key Encryption**: Always encrypt sensitive keys
2. **Access Control**: Use strict access control conditions
3. **Authorization**: Validate all incoming requests
4. **Monitoring**: Monitor all orchestrator activities

### Operational Management

1. **Regular Rotation**: Rotate orchestrators periodically
2. **Backup Recovery**: Maintain backup recovery procedures
3. **Documentation**: Keep detailed operational documentation
4. **Testing**: Regular security testing and validation

Orchestrators are the backbone of the Genius Protocol's decentralized orchestration system. They provide secure, isolated, and efficient execution of critical protocol operations while maintaining the highest security standards through Lit Network's advanced cryptographic techniques.

The combination of Lit PKPs for EVM chains and Lit encryption for Solana ensures that no single entity ever has access to complete private keys, making the system truly decentralized and secure.


# Solver Lit Action

## What is the Solver Lit Action?

The Solver Lit Action is like a smart order processor that lives on the Lit Network. Think of it as a digital assistant that takes care of filling orders across different blockchains automatically and securely.

## What Does It Do?

### The Problem It Solves

When someone wants to move tokens from one blockchain to another (like from Ethereum to Solana), they create an "order" - basically a request that says "I want to send X amount of token A from chain 1 to get token B on chain 2."

The problem is: **who actually executes this order?** Who makes sure the tokens get moved correctly and safely?

### The Solution

The Solver Lit Action is that "who." It's a program that:

1. **Picks up orders** that need to be filled
2. **Checks if they're valid** (not expired, correct amounts, etc.)
3. **Executes the transactions** to move tokens between chains
4. **Handles the complexity** of different blockchain requirements

## Architecture: The Proxy Pattern

The Solver Lit Action uses a **proxy pattern** that allows the core logic to be upgraded without changing the entry point. This is crucial for maintaining a secure and upgradable system.

### How the Proxy Pattern Works

**The Problem:**

* Lit Actions are immutable once deployed to IPFS
* If we find bugs or want to add features, we can't update the existing action without changing all the orchestrators

**The Solution:** The proxy pattern separates the **entry point** from the **implementation**:

1. **Proxy Actions** (Entry Points): These are the stable interfaces that users call
2. **Implementation Actions** (Logic): These contain the actual solving logic and can be upgraded

### The Upgrade Process

```
User calls Proxy → Proxy checks on-chain registry → Proxy calls Implementation → Result returned to user
```

**Step-by-step:**

1. **User calls the proxy**: `solver-proxy-staging.ts` (stable, never changes)
2. **Proxy looks up implementation**: Queries the Genius Actions contract on Base
3. **Proxy calls implementation**: Uses the IPFS hash from the contract
4. **Implementation executes**: Runs the actual solving logic
5. **Result returned**: User gets their result

### Benefits of This Architecture

* **Stable interface**: The proxy address never changes
* **Backward compatibility**: Old integrations continue to work
* **Flexible upgrades**: Can fix bugs and add features easily
* **Emergency fixes**: Can quickly deploy critical fixes
* **Controlled upgrades**: Only authorized addresses can update implementations
* **Audit trail**: All changes are recorded on-chain
* **Rollback capability**: Can revert to previous implementations if needed

### Technical Implementation

**Proxy Structure:**

```typescript
// solver-proxy-staging.ts (stable entry point)
const go = async () => {
  const res = await solverProxyBase(
    ENVIRONMENT.STAGING,
    orders,
    swapsCalls,
    arbitraryCalls,
    evmPkpAddress,
    evmPkpPublicKey,
    orchestratorSolana,
    envVars,
    accessControl,
  );
  return Lit.Actions.setResponse({ response: JSON.stringify(res) });
};
```

**Implementation Lookup:**

```typescript
// Get the current implementation IPFS hash from on-chain registry
const implementationId = await geniusActions.getActionImplementationId(
  ActionTypeEnum.SOLVER,
);

// Call the implementation with parameters
const resImpl = await Lit.Actions.call({ 
  ipfsId: implementationId, 
  params 
});
```

**On-Chain Registry:** The Genius Actions contract on Base stores:

* Action type (SOLVER, REBALANCER, etc.)
* Current implementation IPFS hash
* Admin controls for updates

### Environment-Specific Proxies

Different environments have their own proxies:

* **`solver-proxy-dev.ts`**: Development environment
* **`solver-proxy-staging.ts`**: Staging environment
* **`solver-proxy-test.ts`**: Test environment

This allows:

* **Isolated testing**: Test new implementations without affecting production
* **Environment-specific logic**: Different implementations for different environments
* **Gradual rollout**: Deploy to staging first, then production

## How Does It Work?

### Step 1: Order Collection

The solver looks for orders that are ready to be filled. These orders come from users who want to bridge tokens between different blockchains.

### Step 2: Validation

Before doing anything, the solver checks:

* Is the order still valid? (not expired)
* Are the amounts correct?
* Is the order actually available on the blockchain?
* Does the user have enough tokens?

**Technical Details:**

* Validates order signatures and seeds
* Checks order status on both source and destination chains
* Verifies arbitrary call data matches order parameters
* Ensures order hasn't been filled already

### Step 3: Execution

Once validated, the solver:

**For EVM chains** (like Ethereum, Base, Optimism, etc.):

* Creates a single `fillOrderBatch` transaction
* Handles token swaps through aggregator calls if needed
* Executes arbitrary calls for additional logic
* Uses the vault contract to process the order

**For Solana:**

* Creates multiple transactions in sequence:
  1. `fillOrder` transaction to process the order
  2. Token swap transactions (if needed) through Jupiter
  3. Transfer transaction to send tokens to the user
* Includes a fallback USDC transfer transaction for reliability

### Step 4: Confirmation

The solver confirms that everything worked and the user received their tokens.

## Why Is This Important?

### Security

* **No human intervention**: Orders are filled automatically by secure code
* **No single point of failure**: The Lit Network ensures the solver can't be tampered with
* **Verification**: Every step is checked and validated

### Efficiency

* **Batch processing**: Multiple orders can be filled at once
* **Cross-chain**: Works seamlessly across different blockchains
* **Automatic**: No need for manual order processing

### Reliability

* **Fallback mechanisms**: If something goes wrong, there are backup plans
* **Error handling**: Problems are caught and handled gracefully
* **Monitoring**: Everything is logged and tracked

## The Different Types of Solvers

### EVM Solver

Handles orders on Ethereum-compatible chains (Ethereum, Base, Optimism, etc.):

**Technical Implementation:**

* Uses `GeniusEvmVault.prepFillOrderBatch()` to create transactions
* Processes orders in batches for efficiency
* Maps swap calls and arbitrary calls to order parameters
* Returns `EvmArbitraryCall` transaction data

**Key Features:**

* Single transaction per order batch
* Direct vault contract interaction
* Support for token swaps through aggregators
* Arbitrary call execution for custom logic

### Solana Solver

Handles orders on Solana:

**Technical Implementation:**

* Uses `GeniusSvmPool` for Solana-specific operations
* Converts token decimals between chains (e.g., 6 decimals on EVM to 6 decimals on Solana)
* Generates multiple `VersionedTransaction` objects
* Implements fallback mechanisms with USDC transfers

**Key Features:**

* Multiple transactions per order (fill + swap + transfer)
* Jupiter integration for token swaps
* Fallback transaction for reliability
* Decimal conversion handling

## Real-World Example

Let's say Alice wants to bridge 100 USDC from Base to Solana:

1. **Alice creates an order**: "I want to send 100 USDC from Base to Solana"
2. **The Solver picks up the order**: It sees Alice's order in the queue
3. **Validation**: The solver checks that Alice has 100 USDC on Base and the order is valid
4. **Execution**:
   * The solver creates a transaction on Base to fill the order
   * It creates a transaction on Solana to give Alice her USDC
5. **Completion**: Alice receives her 100 USDC on Solana

**Technical Flow:**

```
Order Input → Validation → SolverFactory → Chain-specific Solver → Transaction Execution
```

**Order Structure:**

```typescript
{
  seed: "0x...",           // Unique identifier
  trader: "0x...",         // Alice's address
  receiver: "0x...",       // Destination address
  tokenIn: "0x...",        // USDC contract address
  tokenOut: "0x...",       // Destination token
  amountIn: "100000000",   // Amount in smallest units
  minAmountOut: "99000000", // Minimum output
  srcChainId: "8453",      // Base chain ID
  destChainId: "1399811149", // Solana chain ID
  fee: "1000000"           // Protocol fee
}
```

## Key Benefits

### For Users

* **Fast execution**: Orders are filled automatically without waiting
* **Reliable**: Built-in error handling and fallback mechanisms
* **Secure**: No need to trust a centralized service

### For the Protocol

* **Decentralized**: No single entity controls order filling
* **Scalable**: Can handle many orders efficiently
* **Maintainable**: Easy to update and improve

## How It Fits Into the Bigger Picture

The Solver Lit Action is part of the Genius Protocol's bridge system:

1. **Users** create orders to bridge tokens
2. **The Solver** picks up and fills these orders
3. **The Bridge** handles the actual cross-chain communication
4. **Users** receive their tokens on the destination chain

Think of it as the "worker" that makes sure all the bridge orders get processed correctly and efficiently.

## Why Use Lit Actions?

Lit Actions provide several advantages for this type of work:

* **Decentralized execution**: No single server or company controls it
* **Secure**: Runs in trusted execution environments
* **Reliable**: Multiple nodes ensure availability
* **Transparent**: All code is open and verifiable

**Technical Benefits:**

* **Orchestrator Integration**: Uses Lit PKPs for EVM chains and encrypted keys for Solana
* **Access Control**: IPFS hash-based permissions ensure only authorized actions can execute
* **Error Handling**: Built-in error handling with `ErrorHandlerLit` service
* **Execution Management**: `ExecutionHandlerLit` manages transaction signing and submission
* **Caching**: `LitHelpers` provides caching for RPC calls and transaction data

## Conclusion

The Solver Lit Action is essentially the "brain" that makes cross-chain bridging work smoothly. It takes the complexity of moving tokens between different blockchains and makes it simple, secure, and automatic. Without it, users would have to manually process orders or trust centralized services, which would be slow, expensive, and risky.

By automating this process on the Lit Network, the Genius Protocol ensures that cross-chain transfers are fast, reliable, and secure for everyone.


# Rebalancing Lit Action

## What is the Rebalancing Lit Action?

The Rebalancing Lit Action is like a smart liquidity manager that automatically balances token supplies across different blockchains. Think of it as a financial advisor that constantly monitors and adjusts where money is stored to ensure optimal distribution and availability.

## What Does It Do?

### The Problem It Solves

When the Genius Protocol operates across multiple blockchains (Ethereum, Base, Solana, etc.), liquidity can become unevenly distributed. For example:

* Base might have $10 million in USDC but only $2 million in demand
* Solana might have $2 million in USDC but $8 million in demand
* This creates inefficiency and poor user experience

The problem is: **how do we automatically move liquidity to where it's needed most?**

### The Solution

The Rebalancing Lit Action solves this with a **two-phase approach**:

1. **Instructions Phase**: Analyzes all vaults and calculates what needs to be moved where
2. **Execution Phase**: Actually moves the liquidity using bridges

## Architecture: Two-Phase System

Due to Lit Network limitations (HTTP call limits, 30-second timeouts), rebalancing uses a sophisticated two-phase approach:

### Phase 1: Instructions (Planning)

```
Analyze Vaults → Calculate Rebalancing → Sign Instructions → Store Results
```

**What happens:**

1. **Fetch vault data** from all supported chains
2. **Calculate optimal distribution** based on current balances and target ratios
3. **Generate rebalancing actions** (what to move where)
4. **Sign the instructions** with authorized keys
5. **Return signed instructions** for execution

### Phase 2: Execution (Action)

```
Receive Instructions → Validate Signature → Execute Transfers → Confirm Results
```

**What happens:**

1. **Receive signed instructions** from Phase 1
2. **Validate the signature** and timestamp
3. **Execute the transfers** using bridges
4. **Confirm successful execution**

## How Does It Work?

### Step 1: Vault Analysis

The system checks all vaults across supported chains:

**For EVM chains:**

* Gets stablecoin balance
* Gets available liquidity
* Gets top holder balance (for risk assessment)

**For Solana:**

* Gets USDC balance from the pool
* Gets available liquidity
* Calculates risk metrics

### Step 2: Rebalancing Calculation

The algorithm determines what needs to be moved:

**Target Distribution:**

* **Equal distribution**: Each chain gets the same amount (default)
* **Custom ratios**: Specific percentages per chain (if provided)
* **Minimum amounts**: Only rebalance if amount > $1 (configurable)

**Calculation Logic:**

```typescript
// Example: 3 chains with equal distribution
Chain A: $10M available → Target: $4M → Move out: $6M
Chain B: $2M available → Target: $4M → Move in: $2M  
Chain C: $0M available → Target: $4M → Move in: $4M
```

### Step 3: Bridge Selection

For each rebalancing action, the system:

1. **Fetches bridge quotes** from multiple providers
2. **Selects the best route** (lowest fees, fastest)
3. **Prepares transactions** for execution

### Step 4: Execution

The system executes the transfers:

**For EVM chains:**

* Creates bridge transactions using vault contracts
* Handles gas optimization
* Manages transaction ordering

**For Solana:**

* Creates multiple transactions (remove liquidity + bridge + add liquidity)
* Includes fallback mechanisms
* Handles decimal conversions

## Technical Implementation

### Instructions Phase

**Vault Data Structure:**

```typescript
interface VaultData {
  network: ChainId;           // Which blockchain
  stablecoin: string;         // Token address
  decimals: number;           // Token decimals
  vaultBalance: bigint;       // Total vault balance
  availableBalance: bigint;   // Available for rebalancing
  highestStakedAmount: bigint; // Risk metric
}
```

**Rebalancing Action:**

```typescript
interface RebalanceAction {
  sourceNetwork: ChainId;     // Where to take from
  targetNetwork: ChainId;     // Where to send to
  amount: string;             // How much to move
}
```

**Signed Instructions:**

```typescript
interface RebalancingInstructions {
  actions: RebalanceAction[];           // What to do
  finalAvailableBalances: { [chainId: string]: string }; // Expected results
  timestamp: number;                    // When created
  env: ENVIRONMENT;                     // Which environment
}
```

### Execution Phase

**Signature Validation:**

* **5-minute validity period** to prevent replay attacks
* **Authorized signer verification** using `REBALANCING_INSTRUCTIONS_SIGNER`
* **Environment matching** to prevent cross-environment attacks

**Bridge Integration:**

* **Genius Intents** for bridge quote fetching
* **Multiple bridge support** (Across, Stargate, etc.)
* **Slippage protection** (1% default)
* **Authority delegation** for cross-chain transfers

## Real-World Example

Let's say the system detects uneven liquidity distribution:

**Current State:**

* Base: $8M USDC available
* Optimism: $1M USDC available
* Solana: $1M USDC available

**Target State (Equal Distribution):**

* Each chain should have \~$3.33M USDC

**Phase 1 - Instructions:**

```typescript
{
  actions: [
    {
      sourceNetwork: ChainId.BASE,
      targetNetwork: ChainId.OPTIMISM,
      amount: "4667000000" // $4.667M
    },
    {
      sourceNetwork: ChainId.BASE, 
      targetNetwork: ChainId.SOLANA,
      amount: "4667000000" // $4.667M
    }
  ],
  timestamp: 1703123456789,
  env: ENVIRONMENT.STAGING
}
```

**Phase 2 - Execution:**

1. **Base → Optimism**: Bridge $4.667M using Across bridge
2. **Base → Solana**: Bridge $4.667M using Stargate bridge
3. **Confirm**: Verify all transfers completed successfully

## Security Features

### 1. Signature Validation

* **Authorized signers only**: Only specific addresses can create valid instructions
* **Timestamp validation**: Prevents replay attacks with 5-minute window
* **Environment isolation**: Staging and production are completely separate

### 2. Risk Management

* **Minimum amounts**: Only rebalance if amount > $1 (prevents dust attacks)
* **Maximum amounts**: Respects vault capacity limits
* **Slippage protection**: 1% maximum slippage on bridge transfers

### 3. Error Handling

* **Graceful failures**: If one transfer fails, others continue
* **Fallback mechanisms**: Alternative execution paths for Solana
* **Comprehensive logging**: All actions are logged for audit

## Key Benefits

### For Users

* **Better liquidity**: Always have tokens available where you need them
* **Lower fees**: Optimized routing reduces bridge costs
* **Faster execution**: Pre-funded liquidity means instant transfers

### For the Protocol

* **Efficient capital usage**: Money is always where it's needed
* **Risk reduction**: Balanced exposure across chains
* **Scalability**: Can handle growing demand across all chains

### For Bridge Providers

* **Predictable volume**: Regular rebalancing creates consistent demand
* **Optimized routes**: System finds the best bridges automatically
* **Reduced congestion**: Spreads transfers across multiple providers

## Architecture: The Proxy Pattern

Like the Solver, the Rebalancing Lit Action uses a **proxy pattern** for upgradability:

### Proxy Structure

```
User calls Proxy → Proxy checks on-chain registry → Proxy calls Implementation → Result returned
```

**Environment-Specific Proxies:**

* **`rebalancing-execution-proxy-dev.ts`**: Development environment
* **`rebalancing-execution-proxy-staging.ts`**: Staging environment
* **`rebalancing-execution-proxy-test.ts`**: Test environment

### Implementation Lookup

```typescript
// Get current implementation from on-chain registry
const implementationId = await geniusActions.getActionImplementationId(
  ActionTypeEnum.REBALANCER,
);

// Call implementation with parameters
const resImpl = await Lit.Actions.call({ 
  ipfsId: implementationId, 
  params 
});
```

## Best Practices

### 1. Monitoring

* **Regular execution**: Run rebalancing every few hours
* **Balance thresholds**: Trigger when imbalance > 20%
* **Performance tracking**: Monitor execution times and success rates

### 2. Risk Management

* **Gradual rebalancing**: Don't move everything at once
* **Bridge diversification**: Use multiple bridges for large amounts
* **Emergency stops**: Ability to pause rebalancing if needed

### 3. Optimization

* **Batch processing**: Execute multiple actions together
* **Gas optimization**: Choose optimal times for EVM transactions
* **Route selection**: Always use the best available bridge

## Conclusion

The Rebalancing Lit Action is the backbone of the Genius Protocol's liquidity management system. By automatically maintaining optimal token distribution across all supported chains, it ensures users always have access to the liquidity they need, when they need it.

The two-phase architecture makes it robust and efficient, while the proxy pattern ensures it can evolve and improve over time. This creates a seamless cross-chain experience where users don't need to worry about which chain has liquidity - the system handles it all automatically.


# EVM Smart Contracts


# Vault

The GeniusVault is the core contract of the Genius bridge protocol, serving as a cross-chain stablecoin bridge with sophisticated price-based deposit protection mechanisms. It enables users to bridge stablecoins across different blockchain networks while maintaining liquidity and protecting against stablecoin depegs through Chainlink price feed integration.

The vault acts as a liquidity pool that accepts stablecoin deposits from users and manages cross-chain order fulfillment. It implements a sophisticated fee system, price verification mechanisms, and liquidity management to ensure the protocol's stability and security.

### The GeniusVault contract - overview

The GeniusVault contract is built on top of the GeniusVaultCore abstract contract, inheriting all the core functionality while adding specific vault-related features. It serves as the main entry point for users to create cross-chain orders and manages the protocol's liquidity pool.

The contract implements a dual-layer architecture where GeniusVaultCore handles the core logic (staking, order management, rebalancing) while GeniusVault adds vault-specific functionality like fee collection and insurance fee management.

### The GeniusVault contract - key features

#### **Cross-chain order creation**

Users can create orders to bridge stablecoins across different blockchain networks. Each order specifies the source chain, destination chain, amounts, and recipient addresses. The vault validates all order parameters and ensures sufficient liquidity before accepting the order.

#### **Price-based deposit protection**

The vault integrates with Chainlink price feeds to monitor stablecoin prices in real-time. Before accepting any deposit, it verifies that the stablecoin price is within acceptable bounds (between `stablePriceLowerBound` and `stablePriceUpperBound`). This protects against stablecoin depegs and market volatility.

#### **Sophisticated fee system**

The contract implements a multi-tier fee structure:

* **Insurance fees**: Retained in the vault as additional liquidity to protect against reorgs and rebalancing fees
* Rest of fees: Transferred to the FeeCollector contract for distribution to protocol, LPs, and operators

#### **Liquidity management**

The vault maintains a minimum liquidity threshold based on the total staked assets and rebalance threshold. This ensures that sufficient liquidity is always available for order fulfillment while allowing excess liquidity to be used for cross-chain operations.

#### **Order lifecycle management**

Orders go through a complete lifecycle:

1. **Created**: Order is accepted and fees are collected
2. **Filled**: Order is executed on the destination chain
3. **Reverted**: Order is cancelled and funds are returned (if applicable)

#### **Role-based access control**

The contract implements comprehensive role management:

* **Admin**: Can configure all vault parameters and manage roles
* **Pauser**: Can pause/unpause the contract in emergencies
* **Orchestrator**: Can execute cross-chain operations and fill orders

#### **Emergency controls**

The contract includes pause functionality that can be activated by authorized pausers to halt all operations in emergency situations.

### Understanding the workflow of GeniusVault

1. **Initialization**: The vault is initialized with stablecoin address, admin, multicall contract, price feed, and various thresholds.
2. **Staking**: Users can stake stablecoins to provide liquidity to the vault and receive gUSD tokens in return.
3. **Order Creation**: Users create cross-chain orders by calling `createOrder()` with the required parameters. The vault verifies the stablecoin price and validates all order parameters.
4. **Fee Collection**: When an order is created, fees are automatically collected and distributed:
   * Insurance fees are retained in the vault
   * Rest of the fees are transferred to the FeeCollector
5. **Order Fulfillment**: Orchestrators execute orders on destination chains by calling `fillOrder()` or `fillOrderBatch()`.
6. **Liquidity Rebalancing**: Orchestrators can rebalance liquidity across chains using `rebalanceLiquidity()`.
7. **Unstaking**: Users can withdraw their staked assets by burning their gUSD tokens.

### Core functions and their purposes

#### **Order Management**

{% code title="GeniusVault.sol" %}

```solidity
function createOrder(Order memory order) external payable virtual override whenNotPaused {
    // Check stablecoin price before accepting the order
    _verifyStablecoinPrice();

    // Validate order parameters
    if (order.trader == bytes32(0) || order.receiver == bytes32(0))
        revert GeniusErrors.NonAddress0();
    if (order.amountIn == 0 || order.amountIn <= order.fee || order.amountIn > maxOrderAmount)
        revert GeniusErrors.InvalidAmount();
    
    // Process fees and transfer stablecoins
    uint256 amountToTransfer = feeCollector.collectFromVault(
        orderHash_,
        order.amountIn,
        order.destChainId,
        order.fee
    );

    insuranceFeesAccumulated += order.fee - amountToTransfer;
    STABLECOIN.safeTransferFrom(msg.sender, address(this), order.amountIn);
    STABLECOIN.safeTransfer(address(feeCollector), amountToTransfer);

    orderStatus[orderHash_] = OrderStatus.Created;
}
```

{% endcode %}

#### **Price Verification**

{% code title="GeniusVaultCore.sol" %}

```solidity
function _verifyStablecoinPrice() internal view returns (bool) {
    try stablecoinPriceFeed.latestRoundData() returns (
        uint80 roundId,
        int256 price,
        uint256 startedAt,
        uint256 updatedAt,
        uint80 answeredInRound
    ) {
        // Check for stale data
        if (block.timestamp - updatedAt > priceFeedHeartbeat)
            revert GeniusErrors.StalePrice(updatedAt);

        // Verify price is within bounds
        uint256 priceUint = uint256(price);
        if (priceUint < stablePriceLowerBound || priceUint > stablePriceUpperBound) {
            revert GeniusErrors.PriceOutOfBounds(priceUint);
        }

        return true;
    } catch {
        revert GeniusErrors.PriceFeedError();
    }
}
```

{% endcode %}

#### **Liquidity Management**

{% code title="GeniusVault.sol" %}

```solidity
function minLiquidity() public view override returns (uint256) {
    uint256 _totalStaked = totalStakedAssets;
    uint256 reduction = (_totalStaked * rebalanceThreshold) / BASE_PERCENTAGE;
    uint256 minBalance = _totalStaked - reduction;
    return minBalance;
}
```

{% endcode %}

#### **Staking Operations**

{% code title="GeniusVaultCore.sol" %}

```solidity
function stakeDeposit(uint256 amount, address receiver) external override whenNotPaused {
    if (amount == 0) revert GeniusErrors.InvalidAmount();
    if (receiver == address(0)) revert GeniusErrors.NonAddress0();

    totalStakedAssets += amount;
    STABLECOIN.safeTransferFrom(msg.sender, address(this), amount);
    _mint(receiver, amount);

    emit StakeDeposit(msg.sender, receiver, amount);
}
```

{% endcode %}

### Security features

#### **Price Feed Protection**

The vault continuously monitors stablecoin prices through Chainlink feeds and rejects deposits when prices are outside acceptable bounds or when price data is stale.

#### **Reentrancy Protection**

All critical functions are protected against reentrancy attacks using OpenZeppelin's ReentrancyGuard.

#### **Access Control**

Comprehensive role-based access control ensures that only authorized addresses can perform sensitive operations.

#### **Pause Mechanism**

The contract can be paused in emergency situations to halt all operations and protect user funds.

#### **Input Validation**

Extensive input validation ensures that all parameters are within acceptable ranges and that addresses are valid.

### Integration with other contracts

The GeniusVault interacts with several other contracts in the Genius ecosystem:

* **FeeCollector**: Manages protocol fee collection and distribution
* **GeniusMulticall**: Executes cross-chain operations and swaps
* **Chainlink Price Feeds**: Provides real-time stablecoin price data
* **Stablecoin Contracts**: The underlying stablecoin being bridged

### Key state variables

* `STABLECOIN`: The stablecoin token being bridged
* `totalStakedAssets`: Total amount of stablecoins staked in the vault
* `insuranceFeesAccumulated`: Accumulated insurance fees retained in the vault
* `stablePriceLowerBound` / `stablePriceUpperBound`: Price bounds for stablecoin validation
* `rebalanceThreshold`: Threshold for liquidity rebalancing
* `maxOrderAmount`: Maximum amount allowed per order

### Events

The contract emits various events to track important state changes:

* `OrderCreated`: When a new cross-chain order is created
* `OrderFilled`: When an order is successfully executed
* `OrderReverted`: When an order is cancelled and funds are returned
* `StakeDeposit`: When users stake stablecoins
* `StakeWithdraw`: When users withdraw their staked assets
* `RebalancedLiquidity`: When liquidity is rebalanced across chains

The GeniusVault is the cornerstone of the Genius bridge protocol, providing secure, efficient, and protected cross-chain stablecoin transfers while maintaining protocol stability through sophisticated liquidity and risk management mechanisms.


# Fee Collector

The FeeCollector is a fee management contract that handles the calculation, collection, and distribution of fees in the Genius bridge protocol. It implements a multi-tier fee structure with separate fee types for protocol maintenance, liquidity providers, and operators, ensuring sustainable protocol economics while incentivizing all participants.

The contract serves as the central hub for all fee-related operations, providing transparent fee calculation, secure fee collection, and automated distribution to various stakeholders. It supports dynamic fee tiers based on order size and maintains separate accounting for different fee types.

### The FeeCollector contract - overview

The FeeCollector contract is an upgradeable contract that implements a comprehensive fee management system. It calculates fees based on order size using tiered structures, collects fees from the vault during order creation, and distributes them to designated receivers based on role-based access control.

The contract maintains separate accounting for protocol fees, liquidity provider (LP) fees, and operator fees, ensuring transparent tracking and secure distribution to the appropriate stakeholders.

### The FeeCollector contract - key features

#### **Multi-tier fee structure**

The contract implements sophisticated fee tiers based on order size, allowing for dynamic fee calculation that scales with transaction volume. This ensures that larger orders contribute proportionally more to protocol sustainability while keeping fees reasonable for smaller transactions.

#### **Separate fee types**

The contract manages three distinct fee types:

* **Protocol fees**: Allocated to protocol maintenance and development
* **LP fees**: Distributed to liquidity providers as incentives
* **Operator fees**: Compensates operators for cross-chain execution work

#### **Role-based fee distribution**

Different fee types are distributed to different roles:

* **Admin**: Can claim protocol fees for the designated receiver
* **Distributor**: Can claim LP fees for liquidity providers
* **Worker**: Can claim operator fees for operators

#### **Chain-specific minimum fees**

Each destination chain has its own minimum fee requirement, accounting for different gas costs and operational expenses across different blockchain networks.

#### **Insurance fee calculation**

The contract calculates insurance fees separately from other fees, which are retained in the vault as additional liquidity protection against reorgs and rebalancing fees.

#### **Comprehensive fee tracking**

All fees are tracked with separate accounting for collected and claimed amounts, providing full transparency and preventing double-spending.

#### **Upgradeable architecture**

The contract uses the UUPS upgradeable pattern, allowing for future improvements to the fee structure without disrupting existing operations.

### Understanding the workflow of FeeCollector

1. **Initialization**: The contract is initialized with admin address, stablecoin, fee percentages, and receiver addresses.
2. **Fee Calculation**: When an order is created, the vault calls `collectFromVault()` to calculate the complete fee breakdown based on order size and destination chain.
3. **Fee Collection**: The vault transfers the calculated fees to the FeeCollector, which distributes them into the appropriate fee buckets (protocol, LP, operator).
4. **Fee Distribution**: Authorized roles can claim their respective fees by calling the appropriate claim functions:
   * `claimProtocolFees()` for admins
   * `claimLPFees()` for distributors
   * `claimOperatorFees()` for workers
5. **Fee Tracking**: All fee movements are tracked and emitted as events for transparency and auditing purposes.

### Core functions and their purposes

#### **Fee Collection and Calculation**

{% code title="FeeCollector.sol" %}

```solidity
function collectFromVault(
    bytes32 _orderHash,
    uint256 _amountIn,
    uint256 _destChainId,
    uint256 _orderFee
) external returns (uint256 amountToTransfer) {
    if (msg.sender != vault) revert GeniusErrors.NotAuthorized();
    if (_amountIn == 0) revert GeniusErrors.InvalidAmount();

    // Calculate fee breakdown
    FeeBreakdown memory feeBreakdown = _calculateFeeBreakdown(
        _amountIn,
        _destChainId
    );

    // Check if the provided fee is sufficient
    if (_orderFee < feeBreakdown.totalFee)
        revert GeniusErrors.InsufficientFees(
            _orderFee,
            feeBreakdown.totalFee
        );

    // Calculate fee distribution based on percentages
    uint256 protocolFeeAmount = (feeBreakdown.bpsFee * protocolFee) /
        BASE_PERCENTAGE;
    uint256 lpFee = feeBreakdown.bpsFee - protocolFeeAmount;

    // Add fees to their respective buckets
    protocolFeesCollected += protocolFeeAmount;
    lpFeesCollected += lpFee;
    operatorFeesCollected += feeBreakdown.baseFee + feeSurplus;

    // The vault should transfer the total fee minus insurance fee to the fee collector
    amountToTransfer = _orderFee - feeBreakdown.insuranceFee;

    emit FeesCollectedFromVault(
        _orderHash,
        protocolFeeAmount,
        lpFee,
        feeBreakdown.baseFee + feeSurplus
    );
    return amountToTransfer;
}
```

{% endcode %}

#### **Fee Breakdown Calculation**

{% code title="FeeCollector.sol" %}

```solidity
function _calculateFeeBreakdown(
    uint256 _amount,
    uint256 _destChainId
) internal view returns (FeeBreakdown memory) {
    uint256 baseFee = targetChainMinFee[_destChainId];

    if (baseFee == 0) {
        revert GeniusErrors.InvalidDestChainId(_destChainId);
    }

    // Calculate BPS fee
    uint256 bpsFeePercentage = _getBpsFeeForAmount(_amount);
    uint256 bpsFee = (_amount * bpsFeePercentage) / BASE_PERCENTAGE;

    // Calculate insurance fee
    uint256 insuranceFeePercentage = _getInsuranceFeeBpsForAmount(_amount);
    uint256 insuranceFee = (_amount * insuranceFeePercentage) /
        BASE_PERCENTAGE;

    // Calculate total fee
    uint256 totalFee = baseFee + bpsFee + insuranceFee;

    return FeeBreakdown({
        baseFee: baseFee,
        bpsFee: bpsFee,
        insuranceFee: insuranceFee,
        totalFee: totalFee
    });
}
```

{% endcode %}

#### **Fee Claiming**

{% code title="FeeCollector.sol" %}

```solidity
function claimProtocolFees()
    external
    nonReentrant
    onlyAdmin
    returns (uint256 amount)
{
    amount = protocolFeesCollected - protocolFeesClaimed;
    if (amount == 0) revert GeniusErrors.InvalidAmount();
    if (protocolFeeReceiver == address(0))
        revert GeniusErrors.NonAddress0();

    protocolFeesClaimed += amount;
    stablecoin.safeTransfer(protocolFeeReceiver, amount);

    emit ProtocolFeesClaimed(msg.sender, protocolFeeReceiver, amount);
    return amount;
}
```

{% endcode %}

#### **Tiered Fee Calculation**

{% code title="FeeCollector.sol" %}

```solidity
function _getBpsFeeForAmount(
    uint256 _amount
) internal view returns (uint256 bpsFee) {
    if (feeTiers.length == 0) return 0;

    // Default to the lowest tier fee
    bpsFee = feeTiers[0].bpsFee;

    // Find the highest tier that the amount qualifies for
    for (uint256 i = 0; i < feeTiers.length; i++) {
        if (_amount >= feeTiers[i].thresholdAmount) {
            bpsFee = feeTiers[i].bpsFee;
        } else {
            // Found a tier with threshold higher than amount, so break
            break;
        }
    }

    return bpsFee;
}
```

{% endcode %}

### Fee structure and calculation

#### **Fee Components**

The total fee for an order consists of three components:

1. **Base Fee**: A fixed minimum fee per destination chain, accounting for gas costs and operational expenses
2. **BPS Fee**: A percentage-based fee calculated on the order amount, split between protocol and LP fees
3. **Insurance Fee**: A percentage-based fee retained in the vault for additional liquidity protection

#### **Fee Tiers**

The contract supports dynamic fee tiers based on order size:

* **Threshold-based**: Each tier has a minimum order size threshold
* **Ascending order**: Tiers are ordered from smallest to largest threshold
* **Highest applicable**: The highest tier that the order qualifies for is applied

#### **Fee Distribution**

* **Protocol fees**: Calculated as `(bpsFee * protocolFee) / BASE_PERCENTAGE`
* **LP fees**: Remaining BPS fees after protocol allocation
* **Operator fees**: Base fee plus any surplus fees

### Security features

#### **Access Control**

The contract implements comprehensive role-based access control:

* **Admin**: Can manage all fee settings and claim protocol fees
* **Distributor**: Can claim LP fees for liquidity providers
* **Worker**: Can claim operator fees for operators

#### **Reentrancy Protection**

All fee claiming functions are protected against reentrancy attacks using OpenZeppelin's ReentrancyGuard.

#### **Input Validation**

Extensive validation ensures:

* Valid addresses for all receivers
* Proper fee percentages within acceptable bounds
* Correct tier ordering and validation
* Sufficient fees provided for orders

#### **Vault Authorization**

Only the authorized vault contract can call fee collection functions, preventing unauthorized fee manipulation.

### Integration with other contracts

The FeeCollector interacts with several other contracts in the Genius ecosystem:

* **GeniusVault**: Calls fee collection functions during order creation
* **Stablecoin Contracts**: The underlying stablecoin used for fee payments
* **Fee Receivers**: Various addresses that receive different fee types

### Key state variables

* `stablecoin`: The stablecoin token used for fee payments
* `vault`: The authorized vault contract that can collect fees
* `protocolFee`: Percentage of BPS fees allocated to protocol
* `feeTiers`: Array of fee tiers based on order size
* `insuranceFeeTiers`: Array of insurance fee tiers
* `targetChainMinFee`: Mapping of chain ID to minimum fees
* `protocolFeesCollected` / `protocolFeesClaimed`: Protocol fee accounting
* `lpFeesCollected` / `lpFeesClaimed`: LP fee accounting
* `operatorFeesCollected` / `operatorFeesClaimed`: Operator fee accounting

### Events

The contract emits various events to track fee operations:

* `FeesCollectedFromVault`: When fees are collected from the vault
* `ProtocolFeesClaimed`: When protocol fees are claimed
* `LPFeesClaimed`: When LP fees are claimed
* `OperatorFeesClaimed`: When operator fees are claimed
* `ProtocolFeeReceiverSet`: When protocol fee receiver is updated
* `LPFeeReceiverSet`: When LP fee receiver is updated
* `OperatorFeeReceiverSet`: When operator fee receiver is updated
* `FeeTiersUpdated`: When fee tiers are updated
* `InsuranceFeeTiersUpdated`: When insurance fee tiers are updated
* `TargetChainMinFeeChanged`: When minimum fees for chains are updated

### Fee management functions

#### **Configuration Functions**

* `setProtocolFeeReceiver()`: Set the protocol fee receiver address
* `setLPFeeReceiver()`: Set the LP fee receiver address
* `setOperatorFeeReceiver()`: Set the operator fee receiver address
* `setProtocolFee()`: Set the protocol fee percentage
* `setTargetChainMinFee()`: Set minimum fees for specific chains
* `setFeeTiers()`: Configure fee tiers based on order size
* `setInsuranceFeeTiers()`: Configure insurance fee tiers

#### **Query Functions**

* `claimableProtocolFees()`: Get claimable protocol fees
* `claimableLPFees()`: Get claimable LP fees
* `claimableOperatorFees()`: Get claimable operator fees
* `getOrderFees()`: Calculate complete fee breakdown for an order

The FeeCollector is a critical component of the Genius protocol's economic model, ensuring sustainable revenue generation while maintaining transparency and fair distribution among all stakeholders. Its sophisticated fee structure and secure distribution mechanisms provide the foundation for long-term protocol viability.


# Proxy Call

The GeniusProxyCall is a multi-call aggregation contract that enables the execution of complex cross-chain operations, token swaps, and arbitrary contract calls in a single transaction. It serves as the execution engine for the Genius bridge protocol, allowing orchestrators to perform intricate operations like swapping stablecoins for other tokens and executing custom logic on destination chains.

The contract provides a secure and efficient way to bundle multiple operations together, reducing gas costs and improving user experience. It supports token approvals, swaps, transfers, and arbitrary contract calls while maintaining strict access controls and comprehensive error handling.

### The GeniusProxyCall contract - overview

The GeniusProxyCall contract is a non-upgradeable contract that implements a comprehensive multi-call system. It allows authorized callers to execute complex sequences of operations including token approvals, swaps, transfers, and arbitrary contract calls in a single transaction.

The contract inherits from MultiSendCallOnly for batch transaction processing and implements AccessControl for secure role management. It provides a flexible interface for orchestrating complex cross-chain operations while maintaining security and efficiency.

### The GeniusProxyCall contract - key features

#### **Multi-call aggregation**

The contract enables the execution of multiple operations in a single transaction, significantly reducing gas costs and improving efficiency for complex cross-chain operations.

#### **Token approval and execution**

Supports automatic token approvals for external contracts, execution of the target operation, and cleanup of approvals to maintain security.

#### **Swap and call operations**

Combines token swaps with arbitrary contract calls, allowing for complex operations like swapping stablecoins for other tokens and then executing custom logic.

#### **Native token support**

Fully supports native token (ETH) operations alongside ERC20 tokens, providing flexibility for different blockchain networks.

#### **Role-based access control**

Implements strict access controls where only authorized callers (orchestrators) can execute operations, preventing unauthorized access and potential exploits.

#### **Comprehensive error handling**

Provides detailed error messages and validation for all operations, ensuring reliable execution and clear debugging.

#### **Batch operations**

Supports batch processing of multiple tokens and operations, enabling efficient handling of complex scenarios.

#### **Security-first design**

Implements security best practices including contract validation, approval cleanup, and safe token transfers.

### Understanding the workflow of GeniusProxyCall

1. **Authorization**: Only addresses with CALLER\_ROLE or the contract itself can execute operations.
2. **Operation Execution**: The contract supports various operation types:
   * Simple contract calls via `execute()`
   * Complex swap and call operations via `call()`
   * Token approval and execution via `approveTokenExecute()`
   * Batch token operations via `approveTokensAndExecute()`
3. **Token Management**: The contract handles token approvals, transfers, and balance management automatically.
4. **Result Processing**: Operations return execution results, effective token addresses, and amounts for further processing.
5. **Cleanup**: Approvals are automatically cleaned up after execution to maintain security.

### Core functions and their purposes

#### **Complex Swap and Call Operations**

{% code title="GeniusProxyCall.sol" %}

```solidity
function call(
    address receiver,
    address swapTarget,
    address callTarget,
    address stablecoin,
    address tokenOut,
    uint256 minAmountOut,
    bytes calldata swapData,
    bytes calldata callData
)
    external
    override
    onlyCallerOrSelf
    returns (
        address effectiveTokenOut,
        uint256 effectiveAmountOut,
        bool success
    )
{
    bool isSwap = swapTarget != address(0);
    bool isCall = callTarget != address(0);

    uint256 stablecoinBalance = IERC20(stablecoin).balanceOf(address(this));
    effectiveAmountOut = stablecoinBalance;
    effectiveTokenOut = stablecoin;
    success = true;

    if (isSwap) {
        bytes memory wrappedSwapData = abi.encodeWithSelector(
            IGeniusProxyCall.approveTokenExecuteAndVerify.selector,
            stablecoin,
            swapTarget,
            swapData,
            tokenOut,
            minAmountOut,
            isCall ? address(this) : receiver
        );
        bytes memory returnData;
        (success, returnData) = address(this).call(wrappedSwapData);
        if (success) {
            effectiveTokenOut = tokenOut;
            effectiveAmountOut = abi.decode(returnData, (uint256));
        } else {
            IERC20(stablecoin).safeTransfer(receiver, stablecoinBalance);
            return (stablecoin, stablecoinBalance, success);
        }
    }

    if (isCall) {
        bytes memory wrappedCallData = abi.encodeWithSelector(
            IGeniusProxyCall.transferTokenAndExecute.selector,
            tokenOut,
            callTarget,
            callData
        );

        (success, ) = address(this).call{value: address(this).balance}(
            wrappedCallData
        );
    }

    // Transfer final balances to receiver
    if (effectiveTokenOut != NATIVE_TOKEN) {
        uint256 balance = IERC20(effectiveTokenOut).balanceOf(address(this));
        if (balance != 0)
            IERC20(effectiveTokenOut).safeTransfer(receiver, balance);
    }

    return (effectiveTokenOut, effectiveAmountOut, success);
}
```

{% endcode %}

#### **Token Approval and Execution with Verification**

{% code title="GeniusProxyCall.sol" %}

```solidity
function approveTokenExecuteAndVerify(
    address token,
    address target,
    bytes calldata data,
    address tokenOut,
    uint256 minAmountOut,
    address expectedTokenReceiver
) external payable override onlyCallerOrSelf returns (uint256) {
    uint256 balancePreSwap;
    uint256 balancePostSwap;
    bool isNativeOut = tokenOut == NATIVE_TOKEN;

    if (isNativeOut) {
        balancePreSwap = address(expectedTokenReceiver).balance;
        _approveTokenAndExecute(token, target, data);
        balancePostSwap = address(expectedTokenReceiver).balance;
    } else {
        balancePreSwap = IERC20(tokenOut).balanceOf(expectedTokenReceiver);
        _approveTokenAndExecute(token, target, data);
        balancePostSwap = IERC20(tokenOut).balanceOf(expectedTokenReceiver);
    }

    uint256 amountOut = balancePostSwap - balancePreSwap;
    if (amountOut < minAmountOut)
        revert GeniusErrors.InvalidAmountOut(amountOut, minAmountOut);
    else return amountOut;
}
```

{% endcode %}

#### **Batch Token Operations**

{% code title="GeniusProxyCall.sol" %}

```solidity
function _approveAddressAndExecute(
    address[] memory tokens,
    address target,
    bytes calldata data,
    address toApprove
) internal {
    if (target == address(0)) revert GeniusErrors.NonAddress0();
    if (!_isContract(target)) revert GeniusErrors.TargetIsNotContract();
    if (!_isContract(toApprove))
        revert GeniusErrors.ApprovalTargetIsNotContract();

    if (target == address(this)) {
        (bool _success, ) = target.call{value: msg.value}(data);
        if (!_success) revert GeniusErrors.ExternalCallFailed(target);
    } else {
        uint256 tokensLength = tokens.length;
        for (uint256 i; i < tokensLength; i++) {
            IERC20(tokens[i]).approve(toApprove, type(uint256).max);
        }

        (bool _success, ) = target.call{value: msg.value}(data);
        if (!_success) revert GeniusErrors.ExternalCallFailed(target);

        for (uint i; i < tokensLength; i++) {
            IERC20(tokens[i]).approve(toApprove, 0);
        }
    }
}
```

{% endcode %}

#### **Simple Contract Execution**

{% code title="GeniusProxyCall.sol" %}

```solidity
function execute(
    address target,
    bytes calldata data
) external payable override onlyCallerOrSelf {
    if (target == address(0)) revert GeniusErrors.NonAddress0();
    if (!_isContract(target)) revert GeniusErrors.TargetIsNotContract();

    (bool _success, ) = target.call{value: msg.value}(data);
    if (!_success) revert GeniusErrors.ExternalCallFailed(target);
}
```

{% endcode %}

### Operation types and use cases

#### **Simple Execution**

* **Purpose**: Execute arbitrary contract calls
* **Use case**: Simple operations that don't require token management
* **Function**: `execute()`

#### **Swap Operations**

* **Purpose**: Swap tokens using external DEX protocols
* **Use case**: Converting stablecoins to other tokens on destination chains
* **Function**: `approveTokenExecuteAndVerify()`

#### **Swap and Call**

* **Purpose**: Combine token swaps with custom logic execution
* **Use case**: Complex DeFi operations requiring multiple steps
* **Function**: `call()`

#### **Batch Operations**

* **Purpose**: Execute operations with multiple tokens
* **Use case**: Complex protocols requiring multiple token approvals
* **Function**: `approveTokensAndExecute()`

#### **Transfer and Execute**

* **Purpose**: Transfer tokens and execute custom logic
* **Use case**: Protocols that require token deposits before execution
* **Function**: `transferTokenAndExecute()`

### Security features

#### **Access Control**

The contract implements strict role-based access control:

* **Admin**: Can manage roles and configuration
* **Caller**: Can execute operations (typically orchestrators)
* **Self**: The contract can call itself for internal operations

#### **Contract Validation**

All target addresses are validated to ensure they are actual contracts, preventing calls to EOA addresses.

#### **Approval Management**

Token approvals are automatically cleaned up after execution to prevent potential security issues.

#### **Safe Token Transfers**

All token transfers use SafeERC20 to prevent common token-related vulnerabilities.

#### **Error Handling**

Comprehensive error handling with custom errors provides clear feedback for debugging and monitoring.

#### **Native Token Support**

Proper handling of native tokens (ETH) alongside ERC20 tokens with appropriate balance checks.

### Integration with other contracts

The GeniusProxyCall interacts with several other contracts in the Genius ecosystem:

* **GeniusVault**: Called by the vault for order execution
* **DEX Protocols**: Various decentralized exchanges for token swaps
* **DeFi Protocols**: External protocols for complex operations
* **Token Contracts**: ERC20 tokens for transfers and approvals

### Key state variables

* `NATIVE_TOKEN`: Constant address representing native tokens (ETH)
* `CALLER_ROLE`: Role identifier for authorized callers
* `DEFAULT_ADMIN_ROLE`: Role identifier for administrators

### Events

The contract inherits events from the interfaces and emits various events for operation tracking:

* `ExternalCallFailed`: When external contract calls fail
* `InvalidAmountOut`: When swap output doesn't meet minimum requirements
* `InvalidCaller`: When unauthorized addresses attempt operations
* `TargetIsNotContract`: When target address is not a contract

### Operation flow examples

#### **Simple Token Swap**

1. User creates order to swap USDC for ETH
2. Vault calls `call()` with swap target (DEX)
3. Contract approves USDC for DEX
4. Executes swap on DEX
5. Verifies minimum output amount
6. Transfers ETH to receiver
7. Cleans up approvals

#### **Complex DeFi Operation**

1. User creates order for complex DeFi operation
2. Vault calls `call()` with both swap and call targets
3. Contract swaps stablecoin for protocol token
4. Transfers protocol token to DeFi contract
5. Executes custom logic on DeFi contract
6. Returns any remaining tokens to receiver

### Error handling and validation

#### **Input Validation**

* Target address must be non-zero
* Target must be a contract
* Caller must have appropriate role
* Token addresses must be valid

#### **Execution Validation**

* External calls must succeed
* Swap outputs must meet minimum requirements
* Token transfers must complete successfully

#### **Security Checks**

* Approvals are cleaned up after use
* Native token balances are properly handled
* Contract state is validated before operations

The GeniusProxyCall is a critical component of the Genius bridge protocol, providing the execution engine for complex cross-chain operations. Its sophisticated multi-call capabilities, security features, and flexible interface enable the protocol to support a wide range of DeFi operations while maintaining efficiency and security.


# Genius Router

The GeniusRouter is a contract that simplifies the process of creating cross-chain orders in the Genius bridge protocol. It provides convenient functions for users to swap tokens and create bridge orders in a single transaction, with optional Permit2 integration for gasless approvals and enhanced user experience.

The router acts as a bridge between users and the core vault functionality, handling token transfers, swaps, and order creation in a streamlined manner. It supports both traditional token approvals and gasless Permit2 transactions, making it accessible to a wide range of users and wallet types.

### The GeniusRouter contract - overview

The GeniusRouter contract is an immutable contract that serves as the primary user interface for the Genius bridge protocol. It integrates with the vault, proxy call, fee collector, and Permit2 contracts to provide a seamless experience for creating cross-chain orders.

The contract handles the complexity of token management, fee calculation, and order creation, allowing users to focus on their desired cross-chain operations rather than the underlying technical details.

### The GeniusRouter contract - key features

#### **Integrated swap and order creation**

The router allows users to swap tokens and create cross-chain orders in a single transaction, eliminating the need for multiple separate transactions and reducing gas costs.

#### **Permit2 integration**

Supports gasless token approvals through Uniswap's Permit2 system, enabling users to create orders without requiring pre-approved token allowances.

#### **Flexible token input**

Supports multiple input tokens in a single transaction, allowing users to swap various tokens for stablecoins before creating bridge orders.

#### **Automatic fee calculation**

Integrates with the fee collector to automatically calculate and include the appropriate fees for cross-chain orders based on destination chain and order size.

#### **Proxy call integration**

Leverages the GeniusProxyCall contract for executing complex swap operations and ensuring secure token transfers.

#### **Immutable architecture**

Uses immutable state variables for critical contract addresses, ensuring security and preventing unauthorized modifications.

#### **User-friendly interface**

Provides simple, intuitive functions that abstract away the complexity of the underlying protocol while maintaining full functionality.

#### **Comprehensive error handling**

Implements detailed error messages and validation to help users understand and resolve any issues with their transactions.

### Understanding the workflow of GeniusRouter

1. **Token Input**: Users provide input tokens either through direct transfers or Permit2 permits.
2. **Token Swapping**: The router executes swaps using the proxy call contract to convert input tokens to stablecoins.
3. **Fee Calculation**: The fee collector calculates the appropriate fees for the destination chain and order size.
4. **Order Creation**: The router creates a cross-chain order with the vault using the swapped stablecoins.
5. **Order Execution**: The order is then executed by orchestrators on the destination chain.

### Core functions and their purposes

#### **Swap and Create Order**

{% code title="GeniusRouter.sol" %}

```solidity
function swapAndCreateOrder(
    bytes32 seed,
    address[] calldata tokensIn,
    uint256[] calldata amountsIn,
    address target,
    address toApprove,
    bytes calldata data,
    address owner,
    uint256 destChainId,
    uint256 feeSurplus,
    bytes32 receiver,
    uint256 minAmountOut,
    bytes32 tokenOut
) public payable override {
    if (tokensIn.length != amountsIn.length)
        revert GeniusErrors.ArrayLengthsMismatch();

    // Transfer input tokens to proxy call
    for (uint256 i = 0; i < tokensIn.length; i++) {
        if (msg.sender != address(PROXYCALL)) {
            IERC20(tokensIn[i]).safeTransferFrom(
                msg.sender,
                address(PROXYCALL),
                amountsIn[i]
            );
        }
    }

    // Execute swap operation
    if (target == address(PROXYCALL))
        PROXYCALL.execute{value: msg.value}(target, data);
    else
        PROXYCALL.approveAddressAndExecute{value: msg.value}(
            tokensIn,
            target,
            data,
            toApprove
        );

    uint256 delta = STABLECOIN.balanceOf(address(this));

    // Calculate fees
    IFeeCollector.FeeBreakdown memory feeBreakdown = FEE_COLLECTOR
        .getOrderFees(delta, destChainId);

    // Create order
    IGeniusVault.Order memory order = IGeniusVault.Order({
        seed: seed,
        trader: VAULT.addressToBytes32(owner),
        receiver: receiver,
        tokenIn: VAULT.addressToBytes32(address(STABLECOIN)),
        tokenOut: tokenOut,
        amountIn: delta,
        minAmountOut: minAmountOut,
        destChainId: destChainId,
        srcChainId: block.chainid,
        fee: feeBreakdown.totalFee + feeSurplus
    });

    VAULT.createOrder(order);
}
```

{% endcode %}

#### **Permit2 Swap and Create Order**

{% code title="GeniusRouter.sol" %}

```solidity
function swapAndCreateOrderPermit2(
    bytes32 seed,
    IAllowanceTransfer.PermitBatch calldata permitBatch,
    bytes calldata permitSignature,
    address target,
    address toApprove,
    bytes calldata data,
    uint256 destChainId,
    uint256 feeSurplus,
    bytes32 receiver,
    uint256 minAmountOut,
    bytes32 tokenOut
) public payable override {
    address owner = msg.sender;

    // Handle Permit2 token transfers
    address[] memory tokensIn = _permitAndBatchTransfer(
        permitBatch,
        permitSignature,
        owner
    );

    // Execute swap operation
    if (target == address(PROXYCALL))
        PROXYCALL.execute{value: msg.value}(target, data);
    else
        PROXYCALL.approveAddressAndExecute{value: msg.value}(
            tokensIn,
            target,
            data,
            toApprove
        );

    uint256 delta = STABLECOIN.balanceOf(address(this));

    // Calculate fees and create order
    IFeeCollector.FeeBreakdown memory feeBreakdown = FEE_COLLECTOR
        .getOrderFees(delta, destChainId);

    IGeniusVault.Order memory order = IGeniusVault.Order({
        seed: seed,
        trader: VAULT.addressToBytes32(owner),
        receiver: receiver,
        tokenIn: VAULT.addressToBytes32(address(STABLECOIN)),
        tokenOut: tokenOut,
        amountIn: delta,
        minAmountOut: minAmountOut,
        destChainId: destChainId,
        srcChainId: block.chainid,
        fee: feeBreakdown.totalFee + feeSurplus
    });

    VAULT.createOrder(order);
}
```

{% endcode %}

#### **Permit2 Order Creation**

{% code title="GeniusRouter.sol" %}

```solidity
function createOrderPermit2(
    bytes32 seed,
    IAllowanceTransfer.PermitBatch calldata permitBatch,
    bytes calldata permitSignature,
    uint256 destChainId,
    uint256 fee,
    bytes32 receiver,
    uint256 minAmountOut,
    bytes32 tokenOut
) external payable override {
    address owner = msg.sender;
    if (permitBatch.details.length != 0)
        revert GeniusErrors.ArrayLengthsMismatch();
    if (permitBatch.details[0].token != address(STABLECOIN))
        revert GeniusErrors.InvalidTokenIn();

    // Transfer stablecoins using Permit2
    _permitAndBatchTransfer(permitBatch, permitSignature, owner);

    uint256 delta = STABLECOIN.balanceOf(address(this));

    // Create order directly with stablecoins
    IGeniusVault.Order memory order = IGeniusVault.Order({
        seed: seed,
        trader: VAULT.addressToBytes32(owner),
        receiver: receiver,
        tokenIn: VAULT.addressToBytes32(address(STABLECOIN)),
        tokenOut: tokenOut,
        amountIn: delta,
        minAmountOut: minAmountOut,
        destChainId: destChainId,
        srcChainId: block.chainid,
        fee: fee
    });

    VAULT.createOrder(order);
}
```

{% endcode %}

#### **Permit2 Token Transfer Helper**

{% code title="GeniusRouter.sol" %}

```solidity
function _permitAndBatchTransfer(
    IAllowanceTransfer.PermitBatch calldata permitBatch,
    bytes calldata permitSignature,
    address owner
) private returns (address[] memory tokensIn) {
    tokensIn = new address[](permitBatch.details.length);
    if (permitBatch.spender != address(this))
        revert GeniusErrors.InvalidSpender();

    // Execute permit
    PERMIT2.permit(owner, permitBatch, permitSignature);

    // Prepare transfer details
    IAllowanceTransfer.AllowanceTransferDetails[]
        memory transferDetails = new IAllowanceTransfer.AllowanceTransferDetails[](
            permitBatch.details.length
        );
    for (uint i; i < permitBatch.details.length; i++) {
        tokensIn[i] = permitBatch.details[i].token;
        transferDetails[i] = IAllowanceTransfer.AllowanceTransferDetails({
            from: owner,
            to: address(PROXYCALL),
            amount: permitBatch.details[i].amount,
            token: permitBatch.details[i].token
        });
    }

    // Execute transfers
    PERMIT2.transferFrom(transferDetails);
}
```

{% endcode %}

### Function types and use cases

#### **Traditional Token Approvals**

* **Function**: `swapAndCreateOrder()`
* **Use case**: Users who prefer traditional token approvals
* **Process**: Direct token transfers followed by swap and order creation

#### **Gasless Permit2 Operations**

* **Function**: `swapAndCreateOrderPermit2()`
* **Use case**: Users wanting gasless token approvals
* **Process**: Permit2 signature validation followed by swap and order creation

#### **Direct Stablecoin Orders**

* **Function**: `createOrderPermit2()`
* **Use case**: Users with stablecoins wanting direct bridge orders
* **Process**: Permit2 stablecoin transfer followed by order creation

### Integration with other contracts

The GeniusRouter integrates with several core contracts in the Genius ecosystem:

* **GeniusVault**: Creates cross-chain orders
* **GeniusProxyCall**: Executes swap operations
* **FeeCollector**: Calculates order fees
* **Permit2**: Handles gasless token approvals
* **Stablecoin**: The underlying stablecoin for bridge operations

### Key state variables

* `STABLECOIN`: The stablecoin token used for bridge operations
* `VAULT`: The GeniusVault contract for order creation
* `PERMIT2`: The Permit2 contract for gasless approvals
* `PROXYCALL`: The GeniusProxyCall contract for swap execution
* `FEE_COLLECTOR`: The FeeCollector contract for fee calculation

### Security features

#### **Immutable Architecture**

All critical contract addresses are immutable, preventing unauthorized modifications and ensuring contract integrity.

#### **Input Validation**

Comprehensive validation of input parameters including:

* Array length matching
* Valid token addresses
* Proper spender addresses
* Sufficient token amounts

#### **Safe Token Transfers**

All token transfers use SafeERC20 to prevent common token-related vulnerabilities.

#### **Permit2 Security**

Proper validation of Permit2 signatures and spender addresses to prevent unauthorized token transfers.

#### **Native Token Protection**

The contract rejects direct native token transfers to prevent accidental fund loss.

### User experience features

#### **Single Transaction Operations**

Users can swap tokens and create bridge orders in a single transaction, reducing gas costs and improving convenience.

#### **Gasless Approvals**

Permit2 integration allows users to create orders without requiring pre-approved token allowances, saving gas and improving user experience.

#### **Flexible Token Support**

Supports multiple input tokens, allowing users to bridge various assets by first converting them to stablecoins.

#### **Automatic Fee Handling**

Fees are automatically calculated and included, eliminating the need for users to manually determine appropriate fee amounts.

#### **Clear Error Messages**

Comprehensive error handling provides clear feedback when transactions fail, helping users understand and resolve issues.

### Order creation process

#### **Step 1: Token Input**

* Users provide input tokens through direct transfers or Permit2 permits
* Multiple tokens can be provided in a single transaction

#### **Step 2: Token Swapping**

* Input tokens are transferred to the proxy call contract
* Swaps are executed to convert tokens to stablecoins
* Swap operations can target any DEX or DeFi protocol

#### **Step 3: Fee Calculation**

* The fee collector calculates appropriate fees based on:
  * Destination chain
  * Order amount
  * Current fee tiers

#### **Step 4: Order Creation**

* A cross-chain order is created with the vault
* Order includes all necessary parameters for execution
* Order is queued for processing by orchestrators

### Error handling and validation

#### **Input Validation**

* Array lengths must match
* Token addresses must be valid
* Spender addresses must be correct
* Permit signatures must be valid

#### **Operation Validation**

* Token transfers must succeed
* Swap operations must complete
* Fee calculations must be valid
* Order creation must succeed

#### **Security Checks**

* Native tokens are rejected
* Unauthorized spenders are blocked
* Invalid permits are rejected

The GeniusRouter is a critical user-facing component of the Genius bridge protocol, providing a simple and efficient interface for creating cross-chain orders. Its integration with Permit2, support for complex swaps, and automatic fee handling make it accessible to users of all technical levels while maintaining the security and functionality of the underlying protocol.


# Solana Smart Contract

Contract Overview

The contract is designed with modularity in mind, separating concerns across different instruction handlers while maintaining a unified state management system. It supports multiple orchestrators with granular permissions, implements tiered fee structures, and provides robust error handling throughout all operations.

### Key Features

#### **Decentralized Cross-Chain Orders**

Users can create cross-chain orders by depositing USDC on Solana, which are then fulfilled by orchestrators on destination chains. The system ensures atomic execution and provides strong guarantees for cross-chain transfers.

#### **Multi-Orchestrator Architecture**

The contract supports multiple orchestrators with configurable permissions, allowing for distributed order fulfillment while maintaining security through role-based access control.

#### **Dynamic Fee Structure**

Implements tiered fee structures based on order amounts, with separate fee categories for operational costs, liquidity provider rewards, protocol revenue, and insurance coverage.

#### **Flexible Liquidity Management**

Orchestrators can manage bridge liquidity through controlled deposit and withdrawal mechanisms, with balance thresholds to ensure sufficient reserves for order fulfillment.

#### **Governance Controls**

Administrative functions for managing orchestrators, fee structures, and emergency controls including the ability to freeze and thaw contract operations.

#### **Comprehensive Error Handling**

Detailed error messages and validation checks throughout all operations to help users understand transaction failures and resolve issues quickly.

### Understanding the Workflow

#### **Order Creation Process**

1. **Price Validation**: The contract validates USDC price stability using Pyth Network feeds
2. **Fee Calculation**: Dynamic fees are calculated based on order amount and destination chain
3. **Token Transfer**: USDC is transferred from user to the vault
4. **Order Recording**: Order details are stored on-chain with unique identifiers
5. **Event Emission**: Order creation event is emitted for orchestrator monitoring

#### **Order Fulfillment Process**

1. **Order Validation**: Orchestrators validate order parameters and check permissions
2. **Liquidity Check**: System ensures sufficient vault balance for order fulfillment
3. **Token Transfer**: USDC is transferred from vault to orchestrator
4. **Completion Recording**: Order status is updated to fulfilled

The orchestrator swaps the USDC for the desired token, and deposits the token to the receiver. This action is handled off-chain in Lit Actions.

#### **Fee Distribution Process**

1. **Fee Collection**: Fees are automatically collected during order creation
2. **Fee Categorization**: Fees are split into base, LP, protocol, and insurance categories
3. **Fee Claiming**: Authorized orchestrators can claim fees based on their permissions
4. **Balance Management**: Unclaimed fees are tracked separately from operational liquidity

### Core Instructions and Their Purposes

#### **Create Order**

```rust
pub fn create_order(
    ctx: Context<CreateOrder>,
    amount: u64,
    seed: [u8; 32],
    order_hash: [u8; 32],
    receiver: [u8; 32],
    src_chain_id: u32,
    dest_chain_id: u32,
    token_in: [u8; 32],
    fee: u64,
    min_amount_out: String,
    token_out: [u8; 32],
) -> Result<()>
```

Creates a new cross-chain order by transferring USDC to the vault and recording order details.

**Process:**

1. Validates USDC price stability using Pyth price feeds
2. Calculates required fees based on amount and destination chain
3. Transfers USDC from user to vault
4. Records order details in on-chain storage
5. Emits order creation event

**Fee Structure:**

* **Base Fee**: Minimum fee based on destination chain
* **BPS Fee**: Percentage fee based on order amount (tiered)
* **Insurance Fee**: Additional fee for risk coverage
* **Protocol Fee**: Portion of BPS fee for protocol revenue

#### **Fill Order**

```rust
pub fn fill_order(
    ctx: Context<FillOrder>,
    amount: u64,
    seed: [u8; 32],
    order_hash: [u8; 32],
    trader: [u8; 32],
    src_chain_id: u32,
    dest_chain_id: u32,
    token_in: [u8; 32],
    fee: u64,
    min_amount_out: String,
) -> Result<()>
```

Allows authorized orchestrators to fulfill cross-chain orders by withdrawing USDC from the vault.

**Process:**

1. Validates orchestrator permissions
2. Checks vault balance sufficiency
3. Transfers USDC to orchestrator
4. Updates order status to filled
5. Emits order fulfillment event

#### **Fill Order Token Transfer**

```rust
pub fn fill_order_token_transfer(
    ctx: Context<FillOrderTokenTransfer>,
    min_amount_out: u64,
    orchestrator_prev_balance: u64,
) -> Result<()>
```

Handles the final token transfer to the receiver on the destination chain, with special handling for wrapped SOL.

**Features:**

* Validates minimum output amount
* Supports both regular SPL tokens and wrapped SOL
* Automatically unwraps SOL when transferring native tokens

#### **Revert Order**

```rust
pub fn revert_order(
    ctx: Context<RevertOrder>, 
    order_hash: [u8; 32]
) -> Result<()>
```

Allows authorized orchestrators to revert orders and refund users minus the collected fees.

**Process:**

1. Validates order status and orchestrator permissions
2. Calculates refund amount (original amount minus fees)
3. Transfers refund to original trader
4. Updates order status to reverted

#### **Claim Fees**

```rust
pub fn claim_fees(
    ctx: Context<ClaimFees>, 
    amount: u64, 
    fee_type: FeeType
) -> Result<()>
```

Allows authorized orchestrators to claim accumulated fees based on their permissions.

**Fee Types:**

* **Base**: Operational fees for maintaining the bridge
* **LP**: Liquidity provider rewards
* **Protocol**: Protocol revenue

#### **Liquidity Management**

rust

```rust
pub fn remove_bridge_liquidity(
    ctx: Context<RemoveBridgeLiquidity>, 
    amount: u64
) -> Result<()>
```

Allows authorized orchestrators to remove bridge liquidity while maintaining minimum balance requirements. This instruction is used for rabalancing vaults (solana and EVM protocols).

### State Management

#### **Global State**

The `GlobalState` account stores system-wide configuration:

```rust
pub struct GlobalState {
    pub admin: Pubkey,
    pub pending_admin: Option<Pubkey>,
    pub rebalance_threshold: u16,
    pub cross_chain_fee_bps: u16,
    pub base_mint: Pubkey,
    pub frozen: bool,
    pub max_order_amount: u64,
}
```

#### **Asset State**

The `Asset` account tracks fee collection and distribution:

```rust
pub struct Asset {
    pub total_fee_collected: u64,
    pub base_fee_collected: u64,
    pub lp_fee_collected: u64,
    pub protocol_fee_collected: u64,
    pub insurance_fee_collected: u64,
    pub unclaimed_base_fee: u64,
    pub unclaimed_lp_fee: u64,
    pub unclaimed_protocol_fee: u64,
    pub unclaimed_insurance_fee: u64,
}
```

#### **Order State**

Individual orders are stored in `Order` accounts:

```rust
pub struct Order {
    pub seed: [u8; 32],
    pub amount_in: u64,
    pub trader: [u8; 32],
    pub receiver: [u8; 32],
    pub src_chain_id: u32,
    pub dest_chain_id: u32,
    pub token_in: [u8; 32],
    pub status: OrderStatus,
    pub fee: u64,
    pub min_amount_out: String,
    pub token_out: [u8; 32],
    pub order_hash: [u8; 32],
}
```

#### **Orchestrator State**

Orchestrator permissions are managed in `OrchestratorState` accounts:

```rust
pub struct OrchestratorState {
    pub orchestrator: Pubkey,
    pub authorized: bool,
    pub fill_order_permission: bool,
    pub revert_order_permission: bool,
    pub remove_bridge_liquidity_permission: bool,
    pub claim_base_fee_permission: bool,
    pub claim_lp_fee_permission: bool,
    pub claim_protocol_fee_permission: bool,
}
```

### Security Features

#### **Program Derived Addresses (PDAs)**

All critical accounts use PDAs with specific seeds for security:

* **Global State**: `b"genius-global-state-seed"`
* **Vault**: `b"genius-vault"`
* **Orders**: `order_hash + b"genius-order"`
* **Orchestrators**: `orchestrator_pubkey + b"genius-orchestrator-seed"`

#### **Permission-Based Access Control**

Granular permissions for different operations:

* Admin-only functions for critical configuration
* Orchestrator permissions for operational tasks
* User permissions for order creation and management

#### **Price Validation**

Integration with Pyth Network for USDC price validation:

* Ensures price stability within acceptable bounds (0.99-1.10 USD)
* Prevents orders during extreme market volatility
* Uses confidence intervals for robust price checking

#### **Balance Validation**

Comprehensive balance checks:

* Ensures sufficient vault liquidity for operations
* Validates minimum balance requirements
* Prevents over-withdrawal scenarios

#### **Input Validation**

Extensive input validation throughout:

* Array length matching for batch operations
* Valid address and amount checks
* Status validation for state transitions

### Error Handling

The contract implements comprehensive error handling with descriptive messages:

```rust
#[error_code]
pub enum GeniusError {
    #[msg("Admin address dismatch")]
    InvalidAdmin,
    #[msg("Orchestrator is not authorized")]
    IllegalOrchestrator,
    #[msg("Invalid withdraw amount")]
    InvalidAmount,
    #[msg("Order already exists")]
    OrderAlreadyExists,
    // ... additional error types
}
```

Common error scenarios and their handling:

* **Invalid permissions**: Clear error messages for unauthorized operations
* **Insufficient balance**: Detailed balance validation with helpful feedback
* **Price instability**: Specific errors for price-related failures
* **State validation**: Comprehensive state transition validation


# Support

## Support & Community

### Getting Help

#### Support Channels

**Community Support**

* **Discord**: [discord.gg/geniusbridge](https://discord.gg/geniusbridge)
* **Response Time**: Usually within 1-2 hours
* **Best For**: General questions, community help, real-time discussions
* **Languages**: English, with community translations

**Technical Support**

* **Email**: <dev@geniusbridge.com>
* **Response Time**: Within 12 hours
* **Best For**: Integration help, API issues, developer questions
* **Include**: error messages, code snippets


