An open API service indexing awesome lists of open source software.

https://github.com/longcipher/suiflash

Flash Loan Aggregator for SUI blockchain
https://github.com/longcipher/suiflash

Last synced: 4 months ago
JSON representation

Flash Loan Aggregator for SUI blockchain

Awesome Lists containing this project

README

          

# SuiFlash


SuiFlash Logo

Capital‑light, multi‑protocol flash loan routing on Sui.

SuiFlash is a production‑grade, capital‑light flash loan aggregator for the Sui blockchain. It unifies access to multiple lending protocols (NAVI, Bucket, Scallop) behind a single, composable interface, performing smart routing, secure user callbacks, atomic settlement, and transparent fee capture in one programmable transaction.

## 📡 Current Deployment (Sui Devnet)

| Component | Address | Description |
|-----------|---------|-------------|
| Package ID | `0x0ea1cc59ece4c8c6ff7342dd89f192873303980efda1cb6d0e55beb93d13f7e3` | Main contract package |
| Config Object | `0x27695e4c7aa292b3f1bc712daf3a4a0d5548f7ca159010428b4bf92182d0552b` | Shared config object |
| Network | Sui Devnet | |
| Service Fee | 40 bps | 0.40% service fee |

## ✨ Key Features

- Unified API & Move entrypoint: one `flash_loan` call instead of three integrations.
- Smart routing strategies: explicit selection, lowest fee, or highest liquidity.
- Atomic user callback: borrow → execute custom logic → repay + fees, all or nothing.
- Protocol abstraction layer: isolated integration modules per protocol.
- Configurable service fee (basis points) with on‑chain admin controls (pause, fee update, asset allowlist).
- Deterministic fee model: `total_fee = protocol_fee + aggregator_service_fee`.
- Event emission for off‑chain indexing & analytics.
- Hardened settlement: repayment sufficiency checks and revert on shortfall.

## 🧱 Architecture Overview

| Layer | Component | Responsibility |
|-------|-----------|----------------|
| On‑chain | `suiflash::flash_router` | Entry `flash_loan` + routing + settlement + callback dispatch |
| On‑chain | `state` | AdminCap, Config (treasury, service_fee_bps, pause flag, allowlist) |
| On‑chain | `integrations::{navi,bucket,scallop}` | Borrow + repay wrappers, protocol fee surfaces |
| On‑chain | `interfaces` | Documented callback signature contract expectation |
| On‑chain | `errors` | Canonical error codes (protocol invalid, amount too low, insufficient repayment, paused) |
| Off‑chain | Collectors | Periodic fetching / caching of liquidity + fee data |
| Off‑chain | Strategy Engine | Route selection & plan generation |
| Off‑chain | Executor | Builds & signs PTB with router + user callback steps |
| Off‑chain | REST API | External interface: submit requests, query status |

## 🔄 Flash Loan Lifecycle

### Architecture Diagram

```mermaid
flowchart TD
User[User / Bot] --> REST[REST API
suiflash_bot]
REST --> Strategy[Strategy Engine]
Strategy --> Executor[Executor / PTB Builder]
Executor --> Router[On-chain Module
suiflash::flash_router]
Router -->|Borrow| Protocols{Underlying Protocols
NAVI / Bucket / Scallop}
Protocols -->|Loaned Funds| Router
Router --> Callback[User Callback Contract
execute_operation]
Callback --> Router
Router -->|Repay + Protocol Fee| Protocols
Router -->|Service Fee| Treasury[Treasury Address]
Router --> Event[FlashLoanExecuted Event]
Event --> Indexer[Observers / Indexers / Analytics]
Executor -->|Result / Digest| REST
REST --> User

classDef onchain fill:#e3f2fd,stroke:#1e88e5,stroke-width:1px
classDef offchain fill:#f1f8e9,stroke:#43a047,stroke-width:1px
classDef protocol fill:#fff3e0,stroke:#fb8c00,stroke-width:1px

class Router,Callback,Event,Treasury onchain
class User,REST,Strategy,Executor,Indexer offchain
class Protocols protocol
```

1. Client POSTs `/flashloan` with JSON payload (asset, amount, route_mode, optional explicit protocol, user callback metadata, payload bytes).
2. Bot validates request & reads freshest protocol metrics from in‑memory snapshot (collector feed).
3. Strategy selects protocol (or allocation) producing an `ExecutionPlan` with expected fees & total cost.
4. Executor builds a Sui Programmable Transaction Block invoking:
- `suiflash::flash_router::flash_loan(config, protocol_selector, amount, recipient_contract, payload)`
- (Within the same PTB) user callback function `execute_operation` in the recipient contract.
5. Underlying protocol funds are borrowed; user callback executes custom logic atomically.
6. Repayment + aggregator service fee returned to router.
7. Router verifies sufficiency, repays protocol, transfers service fee to treasury, emits `FlashLoanExecuted`.
8. API responds with transaction digest, protocol used, and fee breakdown.

## 🧩 Move Contract Surface (Conceptual)

```move
public entry fun flash_loan(
cfg: &Config,
protocol_selector: u64,
amount: u64,
recipient: address,
payload: vector,
ctx: &mut TxContext
);
```

Callback contract must implement:

```move
public entry fun execute_operation(
loaned_coin: Coin,
payload: vector,
ctx: &mut TxContext
): Coin; // returns principal + protocol fee + service fee
```

## 🧠 Routing Strategies

| Mode | Description |
|------|-------------|
| Explicit | User specifies target protocol. |
| BestCost | Minimizes fee (protocol fee + service fee) given current snapshots. |
| BestLiquidity | Prioritizes max available liquidity to reduce slippage & ensure fill. |

## ⚙️ Configuration

The bot now uses a layered configuration system (implemented with the `config` crate) that merges multiple sources with a deterministic priority.

Priority (highest → lowest):

1. Environment variables prefixed with `SUIFLASH_` (e.g. `SUIFLASH_PRIVATE_KEY`)
2. Legacy environment variables without prefix (backward compatibility)
3. `config.toml` file (if present in project root)
4. Built‑in defaults

Minimum required to run: signing key (`private_key` / `SUIFLASH_PRIVATE_KEY`), deployed package & config object IDs.

Supported keys / variables:

| Key / Env Var | Purpose | Default |
|---------------|---------|---------|
| `sui_rpc_url` / `SUIFLASH_SUI_RPC_URL` / `SUI_RPC_URL` | Fullnode RPC endpoint | `https://fullnode.testnet.sui.io:443` |
| `private_key` / `SUIFLASH_PRIVATE_KEY` / `PRIVATE_KEY` | Bot signing key (hex / Base64) | (required) |
| `sui_flash_package_id` / `SUIFLASH_SUI_FLASH_PACKAGE_ID` / `SUI_FLASH_PACKAGE_ID` | Published SuiFlash package ID | (required) |
| `sui_flash_config_object_id` / `SUIFLASH_SUI_FLASH_CONFIG_OBJECT_ID` / `SUI_FLASH_CONFIG_OBJECT_ID` | On‑chain Config object ID | (required) |
| `server_port` / `SUIFLASH_SERVER_PORT` / `SERVER_PORT` | REST server port | `3000` |
| `refresh_interval_ms` / `SUIFLASH_REFRESH_INTERVAL_MS` / `REFRESH_INTERVAL_MS` | Collector refresh cadence (ms) | `10000` |
| `strategy` / `SUIFLASH_STRATEGY` / `STRATEGY` | `cheapest` or `highest_liquidity` | `cheapest` |
| `contract_package_id` / `SUIFLASH_CONTRACT_PACKAGE_ID` / `CONTRACT_PACKAGE_ID` | Default user callback package (optional) | `0x1` |
| `navi_package_id` / `SUIFLASH_NAVI_PACKAGE_ID` / `NAVI_PACKAGE_ID` | NAVI protocol package id | `0x2` |
| `bucket_package_id` / `SUIFLASH_BUCKET_PACKAGE_ID` / `BUCKET_PACKAGE_ID` | Bucket protocol package id | `0x3` |
| `scallop_package_id` / `SUIFLASH_SCALLOP_PACKAGE_ID` / `SCALLOP_PACKAGE_ID` | Scallop protocol package id | `0x4` |
| `service_fee_bps` / `SUIFLASH_SERVICE_FEE_BPS` / `SERVICE_FEE_BPS` | Aggregator service fee (basis points) | `40` (0.40%) |

Quick start using a file (recommended): copy `suiflash-bot/config.example.toml` to `config.toml` and edit your real IDs / key.

Example minimal `config.toml`:

```toml
sui_rpc_url = "https://fullnode.testnet.sui.io:443"
private_key = ""
sui_flash_package_id = "0x..." # deployed package id
sui_flash_config_object_id = "0x..." # on-chain config object
service_fee_bps = 40 # 0.40%
strategy = "cheapest"
```

Override anything at runtime with a prefixed env var, e.g.:

```bash
export SUIFLASH_REFRESH_INTERVAL_MS=5000
export SUIFLASH_STRATEGY=highest_liquidity
```

For deeper detail (validation, examples) see `suiflash-bot/README.md`.

## 🛣 REST API

| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/flashloan` | Submit flash loan request |
| `GET` | `/health` | Liveness probe |
| `GET` | `/protocols` | Current protocol fee + liquidity snapshot (aggregated) |
| `GET` | `/status` | Aggregator status & metrics |

### Example Request

```bash
curl -X POST http://localhost:3000/flashloan \
-H 'Content-Type: application/json' \
-d '{
"asset": "SUI",
"amount": 1000000000,
"route_mode": "BestCost", // BestCost | BestLiquidity | Explicit
"explicit_protocol": null, // e.g. "Navi" when route_mode = "Explicit"
"user_operation": "arbitrage:DEXA->DEXB",
"callback_recipient": "0xabc...def", // optional contract handling callback
"callback_payload": "base64_or_hex" // optional opaque payload
}'
```

### Example Response

```json
{
"transaction_digest": "8J6...abc",
"protocol_used": "Scallop",
"protocol_fee": 500000,
"service_fee": 400000,
"total_fee": 900000
}
```

## 🔐 Security Model

| Control | Mechanism |
|---------|-----------|
| Atomicity | Single PTB; full revert on any failure |
| Fee Enforcement | On‑chain repayment check before releasing funds |
| Admin Controls | AdminCap: pause, adjust service_fee_bps, update treasury |
| Asset Allowlist | Config‑maintained permitted assets list |
| Protocol Isolation | Separate integration modules & receipt verification |
| Reentrancy Guard | Loan receipt & single active loan per execution flow |

## 🧪 Development & Testing

Run backend:

```bash
cargo run --bin suiflash_bot
```

Run tests:

```bash
cargo test
```

Build Move package:

```bash
sui move build
```

## 📦 Project Structure

```text
suiflash/
docs/DESIGN.md
suiflash-contract/ (Move package)
suiflash-bot/ (Rust Artemis backend)
```

## Navi Protocol

> **⚠️ Integration Status**: The Navi Protocol integration is currently in **MOCK/PLACEHOLDER** state.
> - ✅ **Working**: Fee configuration (6 bps), address setup, API integration, architecture
> - ❌ **Not Implemented**: Actual on-chain calls to Navi's `flash_loan_with_ctx` and `flash_repay_with_ctx`
> - 📊 **Completion**: ~30% (configuration and structure only)
>
> See `docs/NAVI_INTEGRATION_REVIEW.md` for complete status and required work for production.

### Navi Protocol Docs

-
-

### Navi Protocol Interfaces

-

### Navi Protocol SDKs

-

### SuiFlash Navi Integration Docs

- `docs/NAVI_ADDRESSES.md` - Mainnet addresses and API reference
- `docs/NAVI_INTEGRATION.md` - Integration guide (intended architecture)
- `docs/NAVI_INTEGRATION_REVIEW.md` - Current status and complete review
- `suiflash-contract/suiflash-router/sources/integrations/navi_real_example.move` - Reference implementation

## Scallop Protocol

### Scallop Protocol Docs

-

### Scallop Protocol Interfaces

-

### Protocol SDKs

*

## Bucket Protocol

### Protocol Docs

-
-

### Protocol Interfaces

-

### Bucket Protocol SDKs

-

## 📝 License

Apache-2.0 (or compatible) – ensure compliance when distributing derivatives.

## 🙌 Acknowledgements

Built on the Sui ecosystem & inspired by prior multi‑protocol aggregators in DeFi.

---

SuiFlash makes flash liquidity programmable, composable, and strategy‑driven on Sui.