lightcone 0.6.1

Rust SDK for the Lightcone Protocol — unified native + WASM client
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
//! Pure conversion module for price/size to raw lamport amounts.
//!
//! All math uses `rust_decimal::Decimal` for exact integer arithmetic.
//! No async, no network calls.

use std::fmt;

use rust_decimal::prelude::*;
use rust_decimal::Decimal;

use crate::program::types::OrderSide;

/// Decimal metadata for an orderbook (cached permanently).
#[derive(Debug, Clone)]
pub struct OrderbookDecimals {
    pub orderbook_id: String,
    pub base_decimals: u8,
    pub quote_decimals: u8,
    pub price_decimals: u8,
    /// Minimum price increment in quote-token lamports (e.g. 1000 for 0.001 with 6 decimals).
    /// Set to 0 or 1 to disable tick alignment.
    pub tick_size: u64,
}

/// Snap a human-readable price to the nearest valid tick.
///
/// Converts the price to quote-token lamports, truncates to the nearest
/// `tick_size` multiple, and converts back to a `Decimal`.
/// Returns the original price unchanged if `tick_size` is 0 or 1.
pub fn align_price_to_tick(price: Decimal, decimals: &OrderbookDecimals) -> Decimal {
    if decimals.tick_size <= 1 {
        return price;
    }

    let quote_multiplier = Decimal::from(10u64.pow(decimals.quote_decimals as u32));
    let tick = Decimal::from(decimals.tick_size);

    let lamports = (price * quote_multiplier).trunc();
    let aligned_lamports = (lamports / tick).trunc() * tick;
    aligned_lamports / quote_multiplier
}

/// Result of converting price + size to raw u64 amounts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScaledAmounts {
    pub amount_in: u64,
    pub amount_out: u64,
}

/// Errors that can occur during price/size scaling.
#[derive(Debug, Clone)]
pub enum ScalingError {
    NonPositivePrice(String),
    NonPositiveSize(String),
    Overflow { context: String },
    ZeroAmount,
    FractionalAmount { value: String },
    InvalidDecimal { input: String, reason: String },
}

impl fmt::Display for ScalingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ScalingError::NonPositivePrice(v) => write!(f, "Price must be positive, got {}", v),
            ScalingError::NonPositiveSize(v) => write!(f, "Size must be positive, got {}", v),
            ScalingError::Overflow { context } => write!(f, "Overflow: {}", context),
            ScalingError::ZeroAmount => write!(f, "Computed amount is zero"),
            ScalingError::FractionalAmount { value } => {
                write!(f, "Fractional lamports not allowed: {}", value)
            }
            ScalingError::InvalidDecimal { input, reason } => {
                write!(f, "Invalid decimal '{}': {}", input, reason)
            }
        }
    }
}

impl std::error::Error for ScalingError {}

/// Convert human-readable price and size into raw u64 maker/taker amounts.
///
/// # Conversion math
///
/// ```text
/// base_lamports  = size  * 10^base_decimals
/// quote_lamports = price * size * 10^quote_decimals
/// ```
///
/// Then assign based on side:
///
/// | Side | amount_in (gives) | amount_out (receives) |
/// |------|-------------------|----------------------|
/// | BID  | quote_lamports    | base_lamports        |
/// | ASK  | base_lamports     | quote_lamports       |
pub fn scale_price_size(
    price: Decimal,
    size: Decimal,
    side: OrderSide,
    decimals: &OrderbookDecimals,
) -> Result<ScaledAmounts, ScalingError> {
    // 1. Validate inputs
    if price <= Decimal::ZERO {
        return Err(ScalingError::NonPositivePrice(price.to_string()));
    }
    if size <= Decimal::ZERO {
        return Err(ScalingError::NonPositiveSize(size.to_string()));
    }

    // 2. Compute lamport amounts
    let base_multiplier = Decimal::from(
        10u64
            .checked_pow(decimals.base_decimals as u32)
            .ok_or_else(|| ScalingError::Overflow {
                context: format!("10^{} overflow", decimals.base_decimals),
            })?,
    );

    let quote_multiplier = Decimal::from(
        10u64
            .checked_pow(decimals.quote_decimals as u32)
            .ok_or_else(|| ScalingError::Overflow {
                context: format!("10^{} overflow", decimals.quote_decimals),
            })?,
    );

    // Truncate size to base_decimals — digits beyond the token's precision
    // are unrepresentable on-chain and are always f64 noise (e.g. 15.763000000000002)
    let size = size.trunc_with_scale(decimals.base_decimals as u32);

    let base_lamports =
        size.checked_mul(base_multiplier)
            .ok_or_else(|| ScalingError::Overflow {
                context: "size * 10^base_decimals".to_string(),
            })?;

    // Truncate quote_lamports to discard sub-lamport dust (analogous to the
    // size truncation above).  price * size can produce fractions beyond the
    // token's representable precision; these are meaningless on-chain.
    let quote_lamports = price
        .checked_mul(size)
        .ok_or_else(|| ScalingError::Overflow {
            context: "price * size".to_string(),
        })?
        .checked_mul(quote_multiplier)
        .ok_or_else(|| ScalingError::Overflow {
            context: "price * size * 10^quote_decimals".to_string(),
        })?
        .trunc();

    // 3. Validate whole numbers (no fractional lamports)
    if base_lamports.fract() != Decimal::ZERO {
        return Err(ScalingError::FractionalAmount {
            value: format!("base_lamports = {}", base_lamports),
        });
    }

    // 4. Convert to u64
    let base_u64 = base_lamports
        .to_u64()
        .ok_or_else(|| ScalingError::Overflow {
            context: format!("base_lamports {} does not fit in u64", base_lamports),
        })?;

    let quote_u64 = quote_lamports
        .to_u64()
        .ok_or_else(|| ScalingError::Overflow {
            context: format!("quote_lamports {} does not fit in u64", quote_lamports),
        })?;

    // 5. Validate non-zero
    if base_u64 == 0 || quote_u64 == 0 {
        return Err(ScalingError::ZeroAmount);
    }

    // 6. Assign based on side
    let (amount_in, amount_out) = match side {
        OrderSide::Bid => (quote_u64, base_u64),
        OrderSide::Ask => (base_u64, quote_u64),
    };

    Ok(ScaledAmounts {
        amount_in,
        amount_out,
    })
}

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

    fn decimals_6_6() -> OrderbookDecimals {
        OrderbookDecimals {
            orderbook_id: "test".to_string(),
            base_decimals: 6,
            quote_decimals: 6,
            price_decimals: 2,
            tick_size: 0,
        }
    }

    fn decimals_6_9() -> OrderbookDecimals {
        OrderbookDecimals {
            orderbook_id: "test".to_string(),
            base_decimals: 6,
            quote_decimals: 9,
            price_decimals: 2,
            tick_size: 0,
        }
    }

    #[test]
    fn test_bid_basic() {
        // BID: price=0.65, size=100, decimals=6/6
        // base_lamports  = 100 * 10^6 = 100_000_000
        // quote_lamports = 0.65 * 100 * 10^6 = 65_000_000
        // BID: maker gives quote, taker gives base
        let result = scale_price_size(
            Decimal::from_str("0.65").unwrap(),
            Decimal::from_str("100").unwrap(),
            OrderSide::Bid,
            &decimals_6_6(),
        )
        .unwrap();

        assert_eq!(result.amount_in, 65_000_000);
        assert_eq!(result.amount_out, 100_000_000);
    }

    #[test]
    fn test_ask_basic() {
        // ASK: price=0.65, size=100, decimals=6/6
        // base_lamports  = 100 * 10^6 = 100_000_000
        // quote_lamports = 0.65 * 100 * 10^6 = 65_000_000
        // ASK: maker gives base, taker gives quote
        let result = scale_price_size(
            Decimal::from_str("0.65").unwrap(),
            Decimal::from_str("100").unwrap(),
            OrderSide::Ask,
            &decimals_6_6(),
        )
        .unwrap();

        assert_eq!(result.amount_in, 100_000_000);
        assert_eq!(result.amount_out, 65_000_000);
    }

    #[test]
    fn test_different_decimals() {
        // base=6, quote=9
        // base_lamports  = 100 * 10^6 = 100_000_000
        // quote_lamports = 0.65 * 100 * 10^9 = 65_000_000_000
        let result = scale_price_size(
            Decimal::from_str("0.65").unwrap(),
            Decimal::from_str("100").unwrap(),
            OrderSide::Bid,
            &decimals_6_9(),
        )
        .unwrap();

        assert_eq!(result.amount_in, 65_000_000_000);
        assert_eq!(result.amount_out, 100_000_000);
    }

    #[test]
    fn test_zero_price_rejected() {
        let result = scale_price_size(
            Decimal::ZERO,
            Decimal::from_str("100").unwrap(),
            OrderSide::Bid,
            &decimals_6_6(),
        );
        assert!(matches!(result, Err(ScalingError::NonPositivePrice(_))));
    }

    #[test]
    fn test_negative_price_rejected() {
        let result = scale_price_size(
            Decimal::from_str("-0.5").unwrap(),
            Decimal::from_str("100").unwrap(),
            OrderSide::Bid,
            &decimals_6_6(),
        );
        assert!(matches!(result, Err(ScalingError::NonPositivePrice(_))));
    }

    #[test]
    fn test_zero_size_rejected() {
        let result = scale_price_size(
            Decimal::from_str("0.65").unwrap(),
            Decimal::ZERO,
            OrderSide::Bid,
            &decimals_6_6(),
        );
        assert!(matches!(result, Err(ScalingError::NonPositiveSize(_))));
    }

    #[test]
    fn test_negative_size_rejected() {
        let result = scale_price_size(
            Decimal::from_str("0.65").unwrap(),
            Decimal::from_str("-10").unwrap(),
            OrderSide::Bid,
            &decimals_6_6(),
        );
        assert!(matches!(result, Err(ScalingError::NonPositiveSize(_))));
    }

    #[test]
    fn test_sub_lamport_size_becomes_zero() {
        // size=0.0000001 with 6 decimals truncates to 0, yielding ZeroAmount
        let result = scale_price_size(
            Decimal::from_str("1").unwrap(),
            Decimal::from_str("0.0000001").unwrap(),
            OrderSide::Bid,
            &decimals_6_6(),
        );
        assert!(matches!(result, Err(ScalingError::ZeroAmount)));
    }

    #[test]
    fn test_f64_noise_in_size_is_truncated() {
        // Simulates f64 floating-point noise: 15.763000000000002 instead of 15.763
        // With base_decimals=6, truncates to 15.763000 and succeeds
        let result = scale_price_size(
            Decimal::from_str("1").unwrap(),
            Decimal::from_str("15.763000000000002").unwrap(),
            OrderSide::Bid,
            &decimals_6_6(),
        )
        .unwrap();

        assert_eq!(result.amount_in, 15_763_000);
        assert_eq!(result.amount_out, 15_763_000);
    }

    #[test]
    fn test_overflow_u64_rejected() {
        // Huge size that overflows u64
        let result = scale_price_size(
            Decimal::from_str("1").unwrap(),
            Decimal::from_str("99999999999999999999").unwrap(),
            OrderSide::Bid,
            &decimals_6_6(),
        );
        assert!(matches!(result, Err(ScalingError::Overflow { .. })));
    }

    #[test]
    fn test_small_valid_amounts() {
        // Minimum valid: 1 lamport each
        // size = 0.000001 (1 lamport with 6 decimals)
        // price = 1.0 -> quote = 0.000001 * 10^6 = 1
        let result = scale_price_size(
            Decimal::from_str("1").unwrap(),
            Decimal::from_str("0.000001").unwrap(),
            OrderSide::Bid,
            &decimals_6_6(),
        )
        .unwrap();

        assert_eq!(result.amount_in, 1); // quote
        assert_eq!(result.amount_out, 1); // base
    }

    #[test]
    fn test_whole_number_price_and_size() {
        // price=2, size=50, decimals=6/6
        // base = 50 * 10^6 = 50_000_000
        // quote = 2 * 50 * 10^6 = 100_000_000
        let result = scale_price_size(
            Decimal::from_str("2").unwrap(),
            Decimal::from_str("50").unwrap(),
            OrderSide::Ask,
            &decimals_6_6(),
        )
        .unwrap();

        assert_eq!(result.amount_in, 50_000_000);
        assert_eq!(result.amount_out, 100_000_000);
    }

    #[test]
    fn test_align_price_to_tick_basic() {
        let d = OrderbookDecimals {
            orderbook_id: "t".into(),
            base_decimals: 8,
            quote_decimals: 6,
            price_decimals: 2,
            tick_size: 1000,
        };
        // 0.6005 * 10^6 = 600500 lamports, tick=1000 -> 600 * 1000 = 600000 -> 0.6
        let aligned = align_price_to_tick(Decimal::from_str("0.6005").unwrap(), &d);
        assert_eq!(aligned, Decimal::from_str("0.6").unwrap());
    }

    #[test]
    fn test_align_price_to_tick_exact() {
        let d = OrderbookDecimals {
            orderbook_id: "t".into(),
            base_decimals: 8,
            quote_decimals: 6,
            price_decimals: 2,
            tick_size: 1000,
        };
        let aligned = align_price_to_tick(Decimal::from_str("0.65").unwrap(), &d);
        assert_eq!(aligned, Decimal::from_str("0.65").unwrap());
    }

    #[test]
    fn test_align_price_no_tick() {
        let d = OrderbookDecimals {
            orderbook_id: "t".into(),
            base_decimals: 6,
            quote_decimals: 6,
            price_decimals: 2,
            tick_size: 0,
        };
        let price = Decimal::from_str("0.12345").unwrap();
        assert_eq!(align_price_to_tick(price, &d), price);
    }
}