perpcity-sdk 0.2.1

Rust SDK for the PerpCity perpetual futures protocol on Base L2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! EIP-1559 gas fee caching with urgency-based scaling.
//!
//! Pre-computed gas limits eliminate `estimateGas` RPC calls on the hot path.
//! The [`FeeCache`] stores the latest base fee from block headers and
//! computes EIP-1559 fees scaled by [`Urgency`].
//!
//! # Example
//!
//! ```
//! use perpcity_sdk::hft::gas::{FeeCache, Urgency, GasLimits};
//!
//! let mut cache = FeeCache::new(2_000, 1_000_000_000);
//! cache.update(50_000_000, 1000); // base_fee from block header, at t=1000ms
//!
//! let fees = cache.fees_for(Urgency::Normal, 1500).unwrap(); // within TTL
//! assert!(fees.max_fee_per_gas >= fees.max_priority_fee_per_gas);
//! ```

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// 4-byte function selector (first 4 bytes of calldata).
type Selector = [u8; 4];

/// Pre-empirically derived gas limits for PerpCity operations.
///
/// Each limit includes ~20% margin over observed mainnet usage.
#[derive(Debug, Clone, Copy)]
pub struct GasLimits;

impl GasLimits {
    /// Simple ETH transfer — protocol-defined, always 21,000 gas.
    pub const ETH_TRANSFER: u64 = 21_000;
    /// ERC-20 `approve` call.
    pub const APPROVE: u64 = 60_000;
    /// Open a taker position (market order).
    pub const OPEN_TAKER: u64 = 700_000;
    /// Open a maker position (range order).
    pub const OPEN_MAKER: u64 = 800_000;
    /// Close any position.
    pub const CLOSE_POSITION: u64 = 600_000;
    /// Adjust position notional (add/remove exposure).
    pub const ADJUST_NOTIONAL: u64 = 500_000;
    /// Adjust position margin (add/remove collateral).
    pub const ADJUST_MARGIN: u64 = 500_000;
    /// ERC-20 `transfer` call.
    pub const TRANSFER: u64 = 65_000;
}

/// Cached gas estimates from `eth_estimateGas`, keyed by function selector.
///
/// On cache miss, the caller performs an `eth_estimateGas` RPC call and stores
/// the result with a safety buffer. On cache hit, the stored value is returned
/// with no RPC. Entries expire after a configurable TTL (default: 1 hour).
///
/// This replaces the hardcoded [`GasLimits`] as the default gas source. HFT
/// users can still bypass estimation by passing an explicit gas limit.
#[derive(Debug)]
pub struct GasLimitCache {
    estimates: HashMap<Selector, CachedEstimate>,
    ttl_ms: u64,
    /// Buffer multiplied onto raw estimates (e.g. 1.2 = 20% margin).
    buffer: f64,
}

#[derive(Debug, Clone, Copy)]
struct CachedEstimate {
    gas_limit: u64,
    cached_at_ms: u64,
}

/// Default gas estimate TTL: 1 hour.
const DEFAULT_ESTIMATE_TTL_MS: u64 = 3_600_000;

/// Default buffer: 20% above the raw estimate.
const DEFAULT_ESTIMATE_BUFFER: f64 = 1.2;

impl GasLimitCache {
    /// Create a new cache with default TTL (1 hour) and buffer (20%).
    pub fn new() -> Self {
        Self {
            estimates: HashMap::new(),
            ttl_ms: DEFAULT_ESTIMATE_TTL_MS,
            buffer: DEFAULT_ESTIMATE_BUFFER,
        }
    }

    /// Create a cache with custom TTL and buffer.
    pub fn with_config(ttl_ms: u64, buffer: f64) -> Self {
        Self {
            estimates: HashMap::new(),
            ttl_ms,
            buffer,
        }
    }

    /// Look up a cached estimate by function selector.
    ///
    /// Returns `None` if no estimate exists or the cached value has expired.
    pub fn get(&self, selector: &Selector, now_ms: u64) -> Option<u64> {
        let entry = self.estimates.get(selector)?;
        if now_ms.saturating_sub(entry.cached_at_ms) < self.ttl_ms {
            Some(entry.gas_limit)
        } else {
            None
        }
    }

    /// Store an estimate. Applies the buffer (e.g. raw 580K → stored 696K at 1.2×).
    pub fn put(&mut self, selector: Selector, raw_estimate: u64, now_ms: u64) {
        let buffered = (raw_estimate as f64 * self.buffer) as u64;
        self.estimates.insert(
            selector,
            CachedEstimate {
                gas_limit: buffered,
                cached_at_ms: now_ms,
            },
        );
    }

    /// Override the TTL.
    pub fn set_ttl(&mut self, ttl_ms: u64) {
        self.ttl_ms = ttl_ms;
    }
}

impl Default for GasLimitCache {
    fn default() -> Self {
        Self::new()
    }
}

/// Transaction urgency level, controlling EIP-1559 fee scaling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Urgency {
    /// `maxFee = baseFee + priorityFee`. Cost-optimized, may be slow.
    Low,
    /// `maxFee = 2 * baseFee + priorityFee`. Standard EIP-1559 headroom.
    Normal,
    /// `maxFee = 3 * baseFee + 2 * priorityFee`. Faster inclusion.
    High,
    /// `maxFee = 4 * baseFee + 5 * priorityFee`. For liquidations / time-critical.
    Critical,
}

/// EIP-1559 gas fees ready to attach to a transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct GasFees {
    /// The block base fee this was computed from (wei).
    pub base_fee: u64,
    /// Miner tip (wei).
    pub max_priority_fee_per_gas: u64,
    /// Fee cap (wei). Always ≥ `base_fee + max_priority_fee_per_gas`.
    pub max_fee_per_gas: u64,
    /// Timestamp (ms) when the underlying base fee was observed.
    pub updated_at_ms: u64,
}

/// Cached EIP-1559 gas fees with TTL-based staleness detection.
///
/// Updated from block headers (typically via subscription or polling).
/// All methods that check freshness take an explicit `now_ms` parameter
/// for deterministic testing.
#[derive(Debug)]
pub struct FeeCache {
    current: Option<GasFees>,
    ttl_ms: u64,
    default_priority_fee: u64,
}

impl FeeCache {
    /// Create a new cache.
    ///
    /// - `ttl_ms`: how long cached fees are valid (2000 = 2 Base L2 blocks)
    /// - `default_priority_fee`: miner tip in wei (e.g. 1_000_000_000 = 1 gwei)
    pub fn new(ttl_ms: u64, default_priority_fee: u64) -> Self {
        Self {
            current: None,
            ttl_ms,
            default_priority_fee,
        }
    }

    /// Update the cache from a new block header's base fee.
    pub fn update(&mut self, base_fee: u64, now_ms: u64) {
        tracing::debug!(base_fee, "gas cache updated");
        self.current = Some(GasFees {
            base_fee,
            max_priority_fee_per_gas: self.default_priority_fee,
            // Store the "Normal" urgency as the default cached value
            max_fee_per_gas: 2u64
                .saturating_mul(base_fee)
                .saturating_add(self.default_priority_fee),
            updated_at_ms: now_ms,
        });
    }

    /// Check if the cache has valid (non-stale) fees.
    #[inline]
    pub fn is_valid(&self, now_ms: u64) -> bool {
        self.current
            .map(|f| now_ms.saturating_sub(f.updated_at_ms) < self.ttl_ms)
            .unwrap_or(false)
    }

    /// Get the raw cached fees if still within TTL.
    #[inline]
    pub fn get(&self, now_ms: u64) -> Option<&GasFees> {
        self.current
            .as_ref()
            .filter(|f| now_ms.saturating_sub(f.updated_at_ms) < self.ttl_ms)
    }

    /// Override the cache TTL (milliseconds).
    ///
    /// Use this when gas is managed externally (e.g. a shared poller
    /// distributing base fees via [`crate::PerpClient::set_base_fee`]). Set the
    /// TTL to match the poller's cadence with some headroom.
    pub fn set_ttl(&mut self, ttl_ms: u64) {
        self.ttl_ms = ttl_ms;
    }

    /// Return the current cached base fee (ignoring TTL).
    #[inline]
    pub fn base_fee(&self) -> Option<u64> {
        self.current.map(|f| f.base_fee)
    }

    /// Compute fees scaled for the given [`Urgency`], or `None` if stale/empty.
    ///
    /// Fee formulas:
    /// - **Low**: `base + priority`
    /// - **Normal**: `2*base + priority`
    /// - **High**: `3*base + 2*priority`
    /// - **Critical**: `4*base + 5*priority`
    #[inline]
    pub fn fees_for(&self, urgency: Urgency, now_ms: u64) -> Option<GasFees> {
        let base = self.get(now_ms)?;
        let bf = base.base_fee;
        let pf = self.default_priority_fee;

        let (max_fee, priority) = match urgency {
            Urgency::Low => (bf.saturating_add(pf), pf),
            Urgency::Normal => (2u64.saturating_mul(bf).saturating_add(pf), pf),
            Urgency::High => (
                3u64.saturating_mul(bf)
                    .saturating_add(2u64.saturating_mul(pf)),
                2u64.saturating_mul(pf),
            ),
            Urgency::Critical => (
                4u64.saturating_mul(bf)
                    .saturating_add(5u64.saturating_mul(pf)),
                5u64.saturating_mul(pf),
            ),
        };

        Some(GasFees {
            base_fee: bf,
            max_priority_fee_per_gas: priority,
            max_fee_per_gas: max_fee,
            updated_at_ms: base.updated_at_ms,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const BASE: u64 = 50_000_000; // 50 Mwei ~ typical Base L2
    const TIP: u64 = 1_000_000_000; // 1 gwei

    fn cache_with_fees(now_ms: u64) -> FeeCache {
        let mut c = FeeCache::new(2000, TIP);
        c.update(BASE, now_ms);
        c
    }

    #[test]
    fn empty_cache_is_invalid() {
        let c = FeeCache::new(2000, TIP);
        assert!(!c.is_valid(0));
        assert!(c.get(0).is_none());
        assert!(c.fees_for(Urgency::Normal, 0).is_none());
    }

    #[test]
    fn update_makes_cache_valid() {
        let c = cache_with_fees(1000);
        assert!(c.is_valid(1000));
        assert!(c.is_valid(2999)); // within 2000ms TTL
    }

    #[test]
    fn cache_expires_after_ttl() {
        let c = cache_with_fees(1000);
        assert!(c.is_valid(2999));
        assert!(!c.is_valid(3000)); // exactly at TTL boundary
        assert!(!c.is_valid(5000));
    }

    #[test]
    fn low_urgency_fees() {
        let c = cache_with_fees(0);
        let f = c.fees_for(Urgency::Low, 0).unwrap();
        assert_eq!(f.max_fee_per_gas, BASE + TIP);
        assert_eq!(f.max_priority_fee_per_gas, TIP);
        assert_eq!(f.base_fee, BASE);
    }

    #[test]
    fn normal_urgency_fees() {
        let c = cache_with_fees(0);
        let f = c.fees_for(Urgency::Normal, 0).unwrap();
        assert_eq!(f.max_fee_per_gas, 2 * BASE + TIP);
        assert_eq!(f.max_priority_fee_per_gas, TIP);
    }

    #[test]
    fn high_urgency_fees() {
        let c = cache_with_fees(0);
        let f = c.fees_for(Urgency::High, 0).unwrap();
        assert_eq!(f.max_fee_per_gas, 3 * BASE + 2 * TIP);
        assert_eq!(f.max_priority_fee_per_gas, 2 * TIP);
    }

    #[test]
    fn critical_urgency_fees() {
        let c = cache_with_fees(0);
        let f = c.fees_for(Urgency::Critical, 0).unwrap();
        assert_eq!(f.max_fee_per_gas, 4 * BASE + 5 * TIP);
        assert_eq!(f.max_priority_fee_per_gas, 5 * TIP);
    }

    #[test]
    fn urgency_ordering() {
        let c = cache_with_fees(0);
        let low = c.fees_for(Urgency::Low, 0).unwrap().max_fee_per_gas;
        let normal = c.fees_for(Urgency::Normal, 0).unwrap().max_fee_per_gas;
        let high = c.fees_for(Urgency::High, 0).unwrap().max_fee_per_gas;
        let critical = c.fees_for(Urgency::Critical, 0).unwrap().max_fee_per_gas;
        assert!(low < normal);
        assert!(normal < high);
        assert!(high < critical);
    }

    #[test]
    fn fees_for_stale_returns_none() {
        let c = cache_with_fees(0);
        assert!(c.fees_for(Urgency::Normal, 3000).is_none());
    }

    #[test]
    fn update_replaces_old_fees() {
        let mut c = cache_with_fees(0);
        c.update(100_000_000, 5000); // new base fee
        let f = c.fees_for(Urgency::Low, 5000).unwrap();
        assert_eq!(f.base_fee, 100_000_000);
    }

    #[test]
    fn saturating_arithmetic_on_huge_values() {
        let mut c = FeeCache::new(2000, u64::MAX / 2);
        c.update(u64::MAX / 2, 0);
        // Should not panic, uses saturating math
        let f = c.fees_for(Urgency::Critical, 0).unwrap();
        assert_eq!(f.max_fee_per_gas, u64::MAX);
    }

    #[test]
    fn preserves_timestamp_across_urgency() {
        let c = cache_with_fees(42);
        for urgency in [
            Urgency::Low,
            Urgency::Normal,
            Urgency::High,
            Urgency::Critical,
        ] {
            let f = c.fees_for(urgency, 42).unwrap();
            assert_eq!(f.updated_at_ms, 42);
        }
    }

    #[test]
    #[allow(clippy::assertions_on_constants)]
    fn gas_limits_are_reasonable() {
        // Ensure limits are in a sane range (not accidentally 0 or astronomical)
        assert!(GasLimits::APPROVE > 20_000 && GasLimits::APPROVE < 200_000);
        assert!(GasLimits::OPEN_TAKER > 200_000 && GasLimits::OPEN_TAKER < 2_000_000);
        assert!(GasLimits::CLOSE_POSITION > 100_000 && GasLimits::CLOSE_POSITION < 2_000_000);
        // Maker is more expensive than taker (more Uniswap V4 work)
        assert!(GasLimits::OPEN_MAKER > GasLimits::OPEN_TAKER);
    }

    // ── GasLimitCache tests ───────────────────────────────────────

    #[test]
    fn estimate_cache_applies_buffer_and_expires() {
        let mut cache = GasLimitCache::with_config(1000, 1.5);
        let selector = [0x01, 0x02, 0x03, 0x04];

        assert!(cache.get(&selector, 0).is_none());

        cache.put(selector, 100_000, 0);
        assert_eq!(cache.get(&selector, 0), Some(150_000)); // 1.5× buffer
        assert_eq!(cache.get(&selector, 999), Some(150_000)); // within TTL
        assert!(cache.get(&selector, 1000).is_none()); // expired
    }

    #[test]
    fn estimate_cache_selectors_are_independent() {
        let mut cache = GasLimitCache::new();
        let open = [0xAA, 0xBB, 0xCC, 0xDD];
        let close = [0x11, 0x22, 0x33, 0x44];

        cache.put(open, 500_000, 0);
        cache.put(close, 800_000, 0);

        assert_eq!(cache.get(&open, 0), Some(600_000));
        assert_eq!(cache.get(&close, 0), Some(960_000));
    }
}