# 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.
