# Spot Advanced Swap Orders [Health: Active]

**Category:** 💻 Developer Tools  
**Repository:** https://github.com/orbs-network/spot  
**GitHub Stars:** 2  
**Views:** 0  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/spot-advanced-swap-orders

## Description
Create gasless market, limit, TWAP, stop-loss, take-profit, and delayed-start swap orders.

## Claude Desktop Quick Installation
Heuristic fallback — verify the package name and runner against the repository README before running it. Uses `npx` (confidence: low):

```json
"mcpServers": {
  "spot-advanced-swap-orders": {
    "command": "npx",
    "args": ["-y","spot-advanced-swap-orders"]
  }
}
```

## Documentation & README

# Spot — Limit, TWAP, Stop-Loss, Take-Profit Non-Custodial Decentralized DeFi Protocol

**Agent-ready decentralized DeFi protocol for non-custodial advanced order types on EVM chains.**

Spot provides non-custodial market, limit, TWAP, stop-loss, take-profit, and delayed-start orders on EVM chains, backed by immutable onchain contracts.

**🔒 Security Audit Reports:** [Initial AstraSec audit](https://github.com/orbs-network/spot/blob/HEAD/Audit-AstraSec.pdf) and [updated AstraSec audit](https://github.com/orbs-network/spot/blob/HEAD/Audit2-AstraSec.pdf)

## Why Spot

1. ✅ **Non-custodial**: RePermit binds spend authorization to exact order hashes instead of handing custody to the protocol.
2. 🔒 **Oracle-protected**: Trigger checks, slippage caps, freshness windows, and deadlines constrain execution.
3. 🛡️ **Battle-tested**: Contracts are audited and covered by an extensive Foundry test suite.
4. 🏗️ **Production-ready**: Spot is built for multi-chain deployment with repo-shipped config, ABIs, skill files, and a hosted MCP endpoint.

## Supported Order Types

1. Market swaps
2. Limit orders
3. TWAP orders
4. Stop-loss orders
5. Take-profit orders
6. Delayed-start orders
7. Chunked recurring execution

## Supported Chains

Spot supports multiple EVM chains. See [`config.json`](https://github.com/orbs-network/spot/blob/HEAD/config.json) as the canonical source for supported chains and runtime addresses.

Orvex uses Spot's universal integration on Robinhood Chain (`4663`), with execution routing selected at fill time. No other Orvex mainnet deployment is listed in its [official contract directory](https://docs.orvex.fi/developer-resources/contract-addresses).

Robinhood's solver adapters cover Kyber, Flytrade (`Magpie`), OpenOcean, and LI.FI (`LiFi`).

## How It Works

Each Spot order combines timing, sizing, trigger, and settlement rules in a single signed payload.

1. `input.amount` is the per-fill chunk size.
2. `input.maxAmount` is the total budget across fills.
3. `output.limit` is the minimum acceptable output per chunk.
4. `output.triggerLower` and `output.triggerUpper` define stop-loss and take-profit style trigger bands.
5. `epoch` controls recurrence: `0` for one-shot, `> 0` for recurring fills.
6. `start` and `deadline` define the execution window.

`output.limit`, `triggerLower`, and `triggerUpper` are encoded as per-chunk output-token amounts in the output token's decimals.

A typical order lifecycle is:

1. **Order creation**: The user signs one EIP-712 order with chunk size, total amount, limits, slippage tolerance, epoch interval, and deadline.
2. **Price attestation**: The cosigner signs both trigger-time and current market price data.
3. **Execution trigger**: A whitelisted executor calls `Executor.execute()` when the order is eligible.
4. **Validation**: `OrderReactor` validates signatures, checks `start`, enforces epoch windows, verifies timestamps, and applies slippage protection.
5. **Settlement**: The reactor transfers input tokens, validates the fill result, and enforces minimum output.
6. **Distribution**: Surplus output is distributed between the swapper and optional referrer according to configured shares.

## Security

Spot's contracts were professionally audited by AstraSec. See the **[initial security audit report](https://github.com/orbs-network/spot/blob/HEAD/Audit-AstraSec.pdf)** and **[updated security audit report](https://github.com/orbs-network/spot/blob/HEAD/Audit2-AstraSec.pdf)**.
Spot is also oracle-protected: execution depends on cosigned trigger and market price data, freshness windows, and slippage checks.

### Access Controls

1. **WM Allowlist**: WM-gated entrypoints restrict privileged admin operations, and order execution honors exclusivity rules.
2. **Two-Step Ownership**: `WM` uses OpenZeppelin `Ownable2Step` for secure ownership transfers.
3. **Executor Binding**: Orders specify an authorized executor; only that executor can fill the order.
4. **Non-Exclusive Fillers**: `exclusivity = 0` locks fills to the designated executor, while values above zero allow third-party fillers that satisfy the higher minimum output requirement.

### Validation Layers

1. **Order Validation**: `OrderValidationLib.validate()` checks all order fields for validity.
2. **Signature Verification**: RePermit validates EIP-712 signatures and witness data binding.
3. **Oracle Price Attestation**: The cosigner supplies trigger-time and current market price data used to gate execution.
4. **Epoch Enforcement**: `EpochLib.update()` prevents early or duplicate fills within time windows.
5. **Slippage Protection**: A maximum 50% slippage cap is enforced in `src/Constants.sol`.
6. **Freshness Windows**: Current cosignatures expire after configurable time periods.
7. **Trigger Timestamp Rules**: Trigger timestamps must be after `start` and no later than the current timestamp.

### Economic Security

1. **Witness-Bound Spending**: RePermit ties allowances to exact order hashes, preventing signature reuse.
2. **Surplus Distribution**: Excess tokens are distributed between the swapper and referrer.
3. **Exact Allowances**: `SafeERC20.forceApprove()` avoids allowance accumulation attacks.

### Operational Security

1. **Reentrancy Protection**: `OrderReactor` uses `ReentrancyGuard`; `Executor` and `Refinery` rely on WM gating and internal invariants.
2. **Safe Token Handling**: The system supports USDT-like tokens and ETH handling semantics.
3. **Emergency Pause**: `OrderReactor` can be paused by WM-allowed addresses.

## Examples

Plain-English examples:

1. Sell a fixed amount once, but only if the execution meets a minimum output.
2. Split a larger budget into equal chunks and execute one chunk every hour as a TWAP.
3. Move into a safer asset if price falls below a stop-loss threshold, or exit on strength if a take-profit threshold is reached.

### Single-Shot Limit Order

```solidity
Order memory order = Order({
    // ... standard fields
    epoch: 0,                    // Single execution
    input: Input({
        amount: 1000e6,          // Exact amount to spend
        maxAmount: 1000e6        // Same as amount
    }),
    output: Output({
        limit: 950 ether,        // Minimum acceptable output
        triggerLower: 0,         // No lower trigger gate
        triggerUpper: 0          // No upper trigger gate
    })
});
```

### TWAP Order

```solidity
Order memory order = Order({
    // ... standard fields
    epoch: 3600,                 // Execute every hour
    input: Input({
        amount: 100e6,           // 100 USDC per chunk
        maxAmount: 1000e6        // 1000 USDC total budget
    }),
    output: Output({
        limit: 95 ether,         // Minimum per chunk
        triggerLower: 0,
        triggerUpper: 0
    })
});
```

### Stop-Loss / Take-Profit Order

```solidity
Order memory order = Order({
    // ... standard fields
    epoch: 0,                    // Single execution
    start: block.timestamp,      // Order becomes active immediately
    output: Output({
        limit: 900 ether,        // Minimum per chunk output when executing
        triggerLower: 950 ether, // Stop-loss boundary per chunk
        triggerUpper: 1200 ether // Take-profit boundary per chunk
    })
});
```

## Technical Overview

### Core Components

1. 🧠 **OrderReactor** (`src/OrderReactor.sol`): Validates orders, checks epoch constraints, computes minimum output from cosigned prices, settles via inlined implementation with reentrancy protection, and supports emergency pause via the WM allowlist.
2. ✍️ **RePermit** (`src/RePermit.sol`): Permit2-style EIP-712 signatures with witness data that bind allowances to exact order hashes, preventing signature reuse.
3. 🧾 **Cosigner** (`src/ops/Cosigner.sol`): Attests to trigger-time and current market prices with token validation.
4. 🛠️ **Executor** (`src/Executor.sol`): Whitelisted fillers that execute eligible orders, enforce minimum output, and distribute surplus.
5. 🔐 **WM** (`src/ops/WM.sol`): Two-step ownership allowlist manager for executors and admin functions with event emission.
6. 🏭 **Refinery** (`src/ops/Refinery.sol`): Operations utility for batching multicalls and sweeping token balances by basis points.

### Order Structure

Based on `src/Structs.sol`, each order contains:

```solidity
struct Order {
    address reactor;           // OrderReactor contract address
    address executor;          // Authorized executor for this order
    Exchange exchange;         // Exchange parameters, referrer, and data
    address swapper;           // Order creator/signer
    uint256 nonce;             // Unique identifier
    uint256 start;             // Earliest execution timestamp
    uint256 deadline;          // Expiration timestamp
    uint256 chainid;           // Chain ID for cross-chain validation
    uint32 exclusivity;        // BPS-bounded exclusive execution
    uint32 epoch;              // Seconds between fills (0 = single-use)
    uint32 slippage;           // BPS applied to cosigned price
    uint32 freshness;          // Cosignature validity window in seconds
    Input input;               // Token to spend
    Output output;             // Token to receive
}

struct Input {
    address token;             // Input token address
    uint256 amount;            // Per-fill chunk amount
    uint256 maxAmount;         // Total amount across all fills
}

struct Output {
    address token;             // Output token address
    uint256 limit;             // Minimum acceptable output, in output-token decimals, per chunk
    uint256 triggerLower;      // Lower trigger boundary, in output-token decimals, per chunk
    uint256 triggerUpper;      // Upper trigger boundary, in output-token decimals, per chunk
    address recipient;         // Where to send output tokens
}
```

### Limits & Constants

1. **Maximum Slippage**: Up to 5,000 BPS, or 50%, inclusive, defined in `src/Constants.sol`.
2. **Basis Points**: 10,000 BPS equals 100%.
3. **Freshness Requirements**: Must be greater than 0 seconds and less than epoch duration when `epoch != 0`.
4. **Epoch Behavior**: `0` means single execution; values above `0` mean recurring execution with that interval.
5. **Gas Optimization**: Foundry optimizer runs are set to `1,000,000`.

### Multi-Chain Deployment

The protocol is designed for deployment across EVM-compatible chains with deterministic addresses via CREATE2. Configuration is managed through [`config.json`](https://github.com/orbs-network/spot/blob/HEAD/config.json).

## For Integrators

This repository ships these integration surfaces:

1. Root package `@orbs-network/spot` for config, build orchestration, contracts, and published metadata inputs.
2. Self-contained skill package [`skill/`](https://github.com/orbs-network/spot/blob/HEAD/skill/) published as `@orbs-network/spot-skill`.
3. Skills-only OpenAI plugin artifact generated with `npm run plugin:build` for marketplace testing and submission.
4. Hosted MCP endpoint at [`https://agents-sink.orbs.network/mcp`](https://agents-sink.orbs.network/mcp).
5. Hosted raw files at [`https://orbs-network.github.io/spot/`](https://orbs-network.github.io/spot/) for direct bundle consumption.
6. Hosted skill distribution on [Clawhub](https://clawhub.ai/eranp-orbs/spot-advanced-swap-orders) for direct skill discovery.

## Development

```bash
npm install
npm run build
npm test
npm run fmt
```

Notes:

1. `npm run build` runs `npm run sync` and then `forge build --extra-output-files abi`.
2. `npm run plugin:build` generates the untracked plugin bundle at `dist/spot/`.
3. Use `forge test` for the Foundry suite.

## Contributing

1. Make the smallest coherent change.
2. Keep `skill/`, hosted MCP references, and any affected published surfaces in sync.
3. Run `npm run build` after changes.
4. Run tests when behavior changes or when explicitly requested.

## Operational Notes

1. **Executor ETH Refunds**: Order execution returns the reactor's ETH balance to the filler. Keep executors funded, and treat unexpected reactor ETH as recoverable by WM-allowed addresses.
2. **Input Tokens**: Orders spend ERC-20 tokens; wrap native ETH before creating orders.

## Support

1. **Issues**: Use GitHub Issues for bug reports and feature requests.
2. **Documentation**: The repo includes inline code documentation and the canonical skill references.

## License

MIT. See [`LICENSE`](https://github.com/orbs-network/spot/blob/HEAD/LICENSE).

