Skip to content

Commit a6bef71

Browse files
committed
enhance repository with comprehensive documentation and tooling
1 parent 57bde16 commit a6bef71

5 files changed

Lines changed: 346 additions & 28 deletions

File tree

.github/workflows/test.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ on:
77

88
jobs:
99
check:
10-
name: Foundry project
10+
name: Foundry Tests
1111
runs-on: ubuntu-latest
1212
steps:
1313
- uses: actions/checkout@v4

README.md

Lines changed: 203 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,212 @@
1-
## HyperEVM Orderbook
1+
# HyperEVM Limit Order Book
22

3-
- HyperEVM uses cancun hardfork without blobs
4-
- Mainnet Chain ID: 999
5-
- JSON-RPC endpoint: https://rpc.hyperliquid.xyz/evm for mainnet
6-
- Testnet Chain ID: 998
7-
- JSON-RPC endpoint: https://rpc.hyperliquid-testnet.xyz/evm
3+
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4+
[![Solidity](https://img.shields.io/badge/Solidity-^0.8.25-blue.svg)](https://soliditylang.org/)
5+
[![Foundry](https://img.shields.io/badge/Built%20with-Foundry-FFDB1C.svg)](https://getfoundry.sh/)
6+
[![Test Coverage](https://img.shields.io/badge/Test%20Coverage-95.35%25-brightgreen.svg)](#testing)
87

9-
## Goal:
8+
A decentralized limit order book smart contract designed for HyperEVM, enabling users to place limit orders that are executed by off-chain bots when price conditions are met.
109

11-
- On-Chain limit order then off chain component to execute it
12-
- save orders on chain, once price hit, execute
13-
- so there's a bot that will execute it
14-
- If cannot execute, we don't execute and can have on chain revert
10+
## 🌟 Features
1511

16-
## UserFlow:
12+
- **On-chain Order Management**: Secure storage of limit orders on the blockchain
13+
- **Off-chain Execution**: Permissionless bot execution with optional authorization controls
14+
- **Flexible Authorization**: Support for both permissionless and authorized executor models
15+
- **Comprehensive Testing**: 95%+ test coverage with unit and fuzz tests
16+
- **Gas Optimized**: Efficient storage patterns and minimal gas consumption
17+
- **Reentrancy Protection**: Built-in security against reentrancy attacks
1718

18-
- User places order on-chain > emits OrderPlaced
19-
- Off-chain bots listens, tracks order
20-
- Once price meets condition, bot sends markExecuted
21-
- If slippage or gas fails, tx reverts
22-
- Successful tx emits OrderExecuted
19+
## 🏗️ Architecture
2320

24-
## SC design:
21+
### User Flow
2522

26-
- placeOrder
27-
- cancelOrder
28-
- markExecuted
29-
- Emit OrderPlaced, OrderExecuted, OrderCancelled
23+
1. **Order Placement**: Users place limit orders on-chain → emits `OrderPlaced` event
24+
2. **Off-chain Monitoring**: Bots listen to events and track order conditions
25+
3. **Price Monitoring**: Bots monitor price feeds (Hyperliquid or custom oracles)
26+
4. **Order Execution**: When price conditions are met, bots call `markExecuted(orderId)`
27+
5. **Failure Handling**: Failed transactions revert with appropriate error messages
28+
6. **Success Confirmation**: Successful execution emits `OrderExecuted` event
3029

31-
## Off-chain bot (Executor Service)
30+
### Contract Design
3231

33-
- Listen to the OrderPlaced events
34-
- Monitor Price Feed (Hyperliquid off-chain price or custom oracle)
35-
- When price hits, call markExecuted(orderId) via relayer
36-
- Handle failed tx reverts (e.g. order already filled, bad slippage, front-run etc.)
32+
- **placeOrder**: Create new limit orders with price and amount validation
33+
- **cancelOrder**: Cancel existing orders (owner-only)
34+
- **markExecuted**: Mark orders as executed (bot/executor function)
35+
- **Access Control**: Owner-controlled executor authorization system
36+
37+
## 🌐 HyperEVM Network
38+
39+
- **Mainnet Chain ID**: 999
40+
- **Mainnet RPC**: `https://rpc.hyperliquid.xyz/evm`
41+
- **Testnet Chain ID**: 998
42+
- **Testnet RPC**: `https://rpc.hyperliquid-testnet.xyz/evm`
43+
- **Hardfork**: Cancun (without blobs)
44+
45+
## 📋 Prerequisites
46+
47+
- [Foundry](https://getfoundry.sh/) (latest version)
48+
- [Git](https://git-scm.com/)
49+
- Node.js (for optional tooling)
50+
51+
## 🚀 Quick Start
52+
53+
### Installation
54+
55+
```bash
56+
# Clone the repository
57+
git clone https://github.com/hougangdev/hyperliquid-limit-order-sc.git
58+
cd hyperliquid-limit-order-sc
59+
60+
# Install dependencies
61+
forge install
62+
63+
# Build the project
64+
forge build
65+
```
66+
67+
### Testing
68+
69+
```bash
70+
# Run all tests
71+
forge test
72+
73+
# Run tests with coverage
74+
forge coverage --no-match-coverage "test/mocks/"
75+
76+
# Run specific test file
77+
forge test --match-path test/unit/LimitOrderBook.t.sol
78+
79+
# Run fuzz tests with more iterations
80+
forge test --match-path test/fuzz/ --fuzz-runs 1000
81+
```
82+
83+
### Deployment
84+
85+
```bash
86+
# Deploy to HyperEVM testnet
87+
forge script script/Deploy.s.sol --rpc-url https://rpc.hyperliquid-testnet.xyz/evm --broadcast
88+
89+
# Deploy to HyperEVM mainnet (replace with your key)
90+
forge script script/Deploy.s.sol --rpc-url https://rpc.hyperliquid.xyz/evm --broadcast --private-key $PRIVATE_KEY
91+
```
92+
93+
## 📖 Usage Examples
94+
95+
### Basic Order Operations
96+
97+
```solidity
98+
// Deploy the contract
99+
LimitOrderBook orderBook = new LimitOrderBook(owner);
100+
101+
// Place a limit order
102+
uint256 orderId = orderBook.placeOrder(1000e18, 100e18); // Price: 1000, Amount: 100
103+
104+
// Check order details
105+
LimitOrderBook.Order memory order = orderBook.getOrder(orderId);
106+
107+
// Cancel an order (owner only)
108+
orderBook.cancelOrder(orderId);
109+
110+
// Execute an order (bot/executor)
111+
orderBook.markExecuted(orderId);
112+
```
113+
114+
### Executor Authorization
115+
116+
```solidity
117+
// Authorize an executor (owner only)
118+
orderBook.authorizeExecutor(executorAddress);
119+
120+
// Require authorization for execution
121+
orderBook.setExecutorAuthRequired(true);
122+
123+
// Revoke executor authorization
124+
orderBook.revokeExecutor(executorAddress);
125+
```
126+
127+
## 🔧 API Reference
128+
129+
### Core Functions
130+
131+
#### `placeOrder(uint256 price, uint256 amount) → uint256 orderId`
132+
133+
Creates a new limit order.
134+
135+
- **Parameters**: `price` - Target execution price, `amount` - Order quantity
136+
- **Returns**: Unique order ID
137+
- **Events**: `OrderPlaced(orderId, user, price, amount)`
138+
139+
#### `cancelOrder(uint256 orderId)`
140+
141+
Cancels an existing order.
142+
143+
- **Parameters**: `orderId` - Order to cancel
144+
- **Requirements**: Must be order owner, order must not be executed
145+
- **Events**: `OrderCancelled(orderId)`
146+
147+
#### `markExecuted(uint256 orderId)`
148+
149+
Marks an order as executed.
150+
151+
- **Parameters**: `orderId` - Order to execute
152+
- **Requirements**: Order must exist and not be executed
153+
- **Events**: `OrderExecuted(orderId)`
154+
155+
### View Functions
156+
157+
- `getOrder(uint256 orderId) → Order` - Get order details
158+
- `isOrderActive(uint256 orderId) → bool` - Check if order is active
159+
- `getOrderCount() → uint256` - Get total number of orders
160+
- `s_authorizedExecutors(address) → bool` - Check executor authorization
161+
162+
### Admin Functions
163+
164+
- `authorizeExecutor(address executor)` - Authorize an executor
165+
- `revokeExecutor(address executor)` - Revoke executor authorization
166+
- `setExecutorAuthRequired(bool requireAuth)` - Toggle authorization requirement
167+
168+
## 🧪 Testing
169+
170+
The project includes comprehensive testing:
171+
172+
- **Unit Tests**: 26 tests covering all functionality
173+
- **Fuzz Tests**: 10 fuzz tests with 256 iterations each
174+
- **Coverage**: 95.35% line coverage, 95.12% statement coverage
175+
- **Mock Contracts**: Test utilities for executor bots and price oracles
176+
177+
### Test Structure
178+
179+
```
180+
test/
181+
├── unit/ # Unit tests for core functionality
182+
├── fuzz/ # Fuzz tests for edge cases
183+
└── mocks/ # Mock contracts for testing
184+
├── MockExecutorBot.sol
185+
└── MockPriceOracle.sol
186+
```
187+
188+
### Known Risks
189+
190+
- **Centralization**: Owner has admin privileges (intended design)
191+
- **Oracle Dependency**: Relies on external price feeds for execution
192+
193+
### Development Guidelines
194+
195+
- Follow Solidity style guide
196+
- Add comprehensive tests for new features
197+
- Update documentation for API changes
198+
- Ensure 100% test coverage for new code
199+
200+
## 📄 License
201+
202+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
203+
204+
## 🙏 Acknowledgments
205+
206+
- [Hyperliquid](https://hyperliquid.xyz/) for the HyperEVM network
207+
- [OpenZeppelin](https://openzeppelin.com/) for secure contract libraries
208+
- [Foundry](https://getfoundry.sh/) for the development framework
209+
210+
---
211+
212+
**⚠️ Disclaimer**: This software is provided "as is" without warranty. Use at your own risk. Always conduct thorough testing before deploying to mainnet.

SECURITY.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Security Policy
2+
3+
## Supported Versions
4+
5+
| Version | Supported |
6+
| ------- | ------------------ |
7+
| 1.0.x | :white_check_mark: |
8+
9+
## Reporting a Vulnerability
10+
11+
If you discover a security vulnerability, please follow these steps:
12+
13+
1. **DO NOT** create a public GitHub issue
14+
2. Email security details to: [security@yourdomain.com](mailto:security@yourdomain.com)
15+
3. Include:
16+
- Description of the vulnerability
17+
- Steps to reproduce
18+
- Potential impact
19+
- Suggested fixes (if any)
20+
21+
## Security Considerations
22+
23+
### Smart Contract Risks
24+
25+
- **Centralization Risk**: The contract owner has administrative privileges
26+
- **Oracle Dependency**: Relies on external price feeds for order execution
27+
- **Front-running**: Bots may compete for order execution
28+
- **MEV**: Order execution may be subject to MEV attacks
29+
30+
### Mitigation Strategies
31+
32+
- **Access Controls**: Proper owner and executor authorization
33+
- **Reentrancy Protection**: All external functions protected
34+
- **Input Validation**: Comprehensive parameter validation
35+
- **State Validation**: Order existence and ownership checks
36+
37+
### Audit Status
38+
39+
- **Static Analysis**: Aderyn analysis completed
40+
- **Code Review**: Internal review completed
41+
- **External Audit**: Not yet completed
42+
43+
## Best Practices
44+
45+
### For Users
46+
47+
- Verify contract addresses before interacting
48+
- Monitor your orders and execution status
49+
- Use reputable executor services
50+
- Understand gas costs and network conditions
51+
52+
### For Developers
53+
54+
- Follow secure coding practices
55+
- Implement proper access controls
56+
- Use established libraries (OpenZeppelin)
57+
- Conduct thorough testing
58+
59+
## Disclaimer
60+
61+
This software is provided "as is" without warranty. Users should conduct their own security assessment before using in production.

package.json

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
{
2+
"name": "hyperliquid-limit-order-sc",
3+
"version": "1.0.0",
4+
"description": "A decentralized limit order book smart contract for HyperEVM",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "forge test",
8+
"test:verbose": "forge test -vvv",
9+
"test:fuzz": "forge test --match-path test/fuzz/",
10+
"test:unit": "forge test --match-path test/unit/",
11+
"coverage": "forge coverage --no-match-coverage 'test/mocks/'",
12+
"build": "forge build",
13+
"clean": "forge clean",
14+
"fmt": "forge fmt",
15+
"fmt:check": "forge fmt --check",
16+
"deploy:testnet": "forge script script/Deploy.s.sol --rpc-url $HYPERLIQUID_TESTNET_RPC --broadcast",
17+
"deploy:mainnet": "forge script script/Deploy.s.sol --rpc-url $HYPERLIQUID_MAINNET_RPC --broadcast"
18+
},
19+
"repository": {
20+
"type": "git",
21+
"url": "git+https://github.com/your-username/hyperliquid-limit-order-sc.git"
22+
},
23+
"keywords": [
24+
"solidity",
25+
"smart-contracts",
26+
"limit-order",
27+
"orderbook",
28+
"hyperliquid",
29+
"hyperevm",
30+
"defi"
31+
],
32+
"author": "Your Name",
33+
"license": "MIT",
34+
"bugs": {
35+
"url": "https://github.com/your-username/hyperliquid-limit-order-sc/issues"
36+
},
37+
"homepage": "https://github.com/your-username/hyperliquid-limit-order-sc#readme",
38+
"devDependencies": {
39+
"@crytic/slither-analyzer": "^0.10.0"
40+
},
41+
"engines": {
42+
"node": ">=16.0.0"
43+
}
44+
}

script/Deploy.s.sol

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// SPDX-License-Identifier: MIT
2+
pragma solidity ^0.8.25;
3+
4+
import "lib/forge-std/src/Script.sol";
5+
import "../src/LimitOrderBook.sol";
6+
7+
/**
8+
* @title Deploy Script
9+
* @dev Script to deploy LimitOrderBook contract to HyperEVM
10+
* @notice Run with: forge script script/Deploy.s.sol --rpc-url <RPC_URL> --broadcast --private-key <PRIVATE_KEY>
11+
*/
12+
contract DeployScript is Script {
13+
function run() external {
14+
// Get deployer address
15+
address deployer = vm.addr(vm.envUint("PRIVATE_KEY"));
16+
17+
// Log deployment info
18+
console.log("Deploying LimitOrderBook...");
19+
console.log("Deployer address:", deployer);
20+
21+
// Start broadcasting transactions
22+
vm.startBroadcast();
23+
24+
// Deploy LimitOrderBook with deployer as initial owner
25+
LimitOrderBook orderBook = new LimitOrderBook(deployer);
26+
27+
// Stop broadcasting
28+
vm.stopBroadcast();
29+
30+
// Log deployment results
31+
console.log("LimitOrderBook deployed to:", address(orderBook));
32+
console.log("Owner:", orderBook.owner());
33+
console.log("Initial state:");
34+
console.log("- Permissionless execution:", orderBook.s_authorizedExecutors(address(0)));
35+
console.log("- Next order ID:", orderBook.s_nextOrderId());
36+
}
37+
}

0 commit comments

Comments
 (0)