lightcone 0.7.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! Type definitions for the Lightcone Pinocchio on-chain program.
//!
//! This module contains enums, parameter structs, and other type definitions
//! used for on-chain program interaction.

use solana_pubkey::Pubkey;

use crate::domain::market::Market;
use crate::program::constants::{MAX_OUTCOMES, MIN_OUTCOMES};
use crate::program::error::{SdkError, SdkResult};
use crate::program::orders::OrderPayload;
use crate::shared::DepositSource;

// ============================================================================
// Enums
// ============================================================================

/// Market status enum
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum MarketStatus {
    /// Market is pending activation
    Pending = 0,
    /// Market is active and trading is enabled
    Active = 1,
    /// Market has been resolved with payout numerators
    Resolved = 2,
    /// Market has been cancelled
    Cancelled = 3,
}

impl TryFrom<u8> for MarketStatus {
    type Error = SdkError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(MarketStatus::Pending),
            1 => Ok(MarketStatus::Active),
            2 => Ok(MarketStatus::Resolved),
            3 => Ok(MarketStatus::Cancelled),
            _ => Err(SdkError::InvalidMarketStatus(value)),
        }
    }
}

/// Order side enum
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum OrderSide {
    /// Bid/Buy - maker wants to buy base tokens, gives quote tokens
    Bid = 0,
    /// Ask/Sell - maker wants to sell base tokens, receives quote tokens
    Ask = 1,
}

impl TryFrom<u8> for OrderSide {
    type Error = SdkError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(OrderSide::Bid),
            1 => Ok(OrderSide::Ask),
            _ => Err(SdkError::InvalidSide(value)),
        }
    }
}

// ============================================================================
// Parameter Structs
// ============================================================================

/// Parameters for creating a market
#[derive(Debug, Clone)]
pub struct CreateMarketParams {
    /// Manager pubkey (must be exchange manager)
    pub manager: Pubkey,
    /// Number of outcomes (2-6)
    pub num_outcomes: u8,
    /// Oracle pubkey that can settle the market
    pub oracle: Pubkey,
    /// Question ID (32 bytes)
    pub question_id: [u8; 32],
    /// Maker fee in basis points. Must be in [-500, 500].
    pub maker_fee_bps: i16,
    /// Taker fee in basis points. Must be in [-500, 500].
    pub taker_fee_bps: i16,
}

/// Parameters for adding a deposit mint to a market
#[derive(Debug, Clone)]
pub struct AddDepositMintParams {
    /// Manager pubkey (must be exchange manager)
    pub manager: Pubkey,
    /// Deposit mint pubkey
    pub deposit_mint: Pubkey,
}

/// Parameters for minting a complete set
#[derive(Debug, Clone)]
pub struct BuildDepositParams {
    /// User pubkey (payer and recipient)
    pub user: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Deposit mint pubkey
    pub deposit_mint: Pubkey,
    /// Amount of collateral to deposit
    pub amount: u64,
}

/// Parameters for merging a complete set
#[derive(Debug, Clone)]
pub struct BuildMergeParams {
    /// User pubkey
    pub user: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Deposit mint pubkey
    pub deposit_mint: Pubkey,
    /// Amount of each outcome token to burn
    pub amount: u64,
}

/// Parameters for settling a market
#[derive(Debug, Clone)]
pub struct SettleMarketParams {
    /// Oracle pubkey (must match market oracle)
    pub oracle: Pubkey,
    /// Market ID
    pub market_id: u64,
    /// Payout numerators, one per market outcome.
    ///
    /// The program computes the denominator as the checked sum of these values.
    /// The SDK sends exactly this vector as u32 little-endian values.
    pub payout_numerators: Vec<u32>,
}

impl SettleMarketParams {
    /// Construct settlement params from an explicit payout vector.
    pub fn new(oracle: Pubkey, market_id: u64, payout_numerators: Vec<u32>) -> Self {
        Self {
            oracle,
            market_id,
            payout_numerators,
        }
    }

    /// Construct a binary or multi-outcome winner-takes-all payout vector.
    pub fn winner_takes_all(
        oracle: Pubkey,
        market_id: u64,
        winning_outcome: u8,
        num_outcomes: u8,
    ) -> SdkResult<Self> {
        let mut payout_numerators = vec![0; validate_num_outcomes(num_outcomes)? as usize];
        let max_index = num_outcomes.saturating_sub(1);
        if winning_outcome >= num_outcomes {
            return Err(SdkError::InvalidOutcomeIndex {
                index: winning_outcome,
                max: max_index,
            });
        }
        payout_numerators[winning_outcome as usize] = 1;
        Ok(Self::new(oracle, market_id, payout_numerators))
    }
}

/// Integer fixed-point scalar settlement metadata.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScalarResolutionParams {
    /// Lower scalar bound, in caller-defined fixed-point units.
    pub min_value: i128,
    /// Upper scalar bound, in caller-defined fixed-point units.
    pub max_value: i128,
    /// Resolved scalar value, in the same fixed-point units.
    pub resolved_value: i128,
    /// Outcome index that receives value at or below `min_value`.
    pub lower_outcome_index: u8,
    /// Outcome index that receives value at or above `max_value`.
    pub upper_outcome_index: u8,
    /// Market outcome count.
    pub num_outcomes: u8,
}

/// Convert a two-sided scalar resolution into payout numerators.
///
/// This uses only integer fixed-point arithmetic. The resolved value is clamped
/// into `[min_value, max_value]`, the two non-zero candidate numerators are
/// reduced by their greatest common divisor, and the result is checked against
/// the program's u32 payout representation.
pub fn scalar_to_payout_numerators(params: ScalarResolutionParams) -> SdkResult<Vec<u32>> {
    validate_num_outcomes(params.num_outcomes)?;
    validate_scalar_outcome_index(params.lower_outcome_index, params.num_outcomes)?;
    validate_scalar_outcome_index(params.upper_outcome_index, params.num_outcomes)?;

    if params.lower_outcome_index == params.upper_outcome_index {
        return Err(SdkError::DuplicateScalarOutcomes);
    }

    let range = params
        .max_value
        .checked_sub(params.min_value)
        .ok_or(SdkError::Overflow)?;
    if range <= 0 {
        return Err(SdkError::InvalidScalarRange);
    }

    let clamped = params
        .resolved_value
        .clamp(params.min_value, params.max_value);
    let lower_numerator = params
        .max_value
        .checked_sub(clamped)
        .ok_or(SdkError::Overflow)?;
    let upper_numerator = clamped
        .checked_sub(params.min_value)
        .ok_or(SdkError::Overflow)?;

    let mut numerators = vec![0u128; params.num_outcomes as usize];
    numerators[params.lower_outcome_index as usize] = lower_numerator as u128;
    numerators[params.upper_outcome_index as usize] = upper_numerator as u128;

    reduce_and_fit_payout_numerators(&numerators)
}

fn validate_num_outcomes(num_outcomes: u8) -> SdkResult<u8> {
    if !(MIN_OUTCOMES..=MAX_OUTCOMES).contains(&num_outcomes) {
        return Err(SdkError::InvalidOutcomeCount {
            count: num_outcomes,
        });
    }
    Ok(num_outcomes)
}

fn validate_scalar_outcome_index(index: u8, num_outcomes: u8) -> SdkResult<()> {
    if index >= num_outcomes {
        return Err(SdkError::InvalidOutcomeIndex {
            index,
            max: num_outcomes.saturating_sub(1),
        });
    }
    Ok(())
}

fn reduce_and_fit_payout_numerators(numerators: &[u128]) -> SdkResult<Vec<u32>> {
    let gcd = numerators
        .iter()
        .copied()
        .filter(|n| *n > 0)
        .reduce(gcd_u128)
        .ok_or(SdkError::InvalidPayoutNumerators)?;

    let mut reduced = Vec::with_capacity(numerators.len());
    let mut sum = 0u128;
    for numerator in numerators {
        let value = if *numerator == 0 { 0 } else { numerator / gcd };
        if value > u32::MAX as u128 {
            return Err(SdkError::PayoutVectorExceedsU32);
        }
        sum = sum.checked_add(value).ok_or(SdkError::Overflow)?;
        reduced.push(value as u32);
    }

    if sum == 0 {
        return Err(SdkError::InvalidPayoutNumerators);
    }
    if sum > u32::MAX as u128 {
        return Err(SdkError::PayoutVectorExceedsU32);
    }

    Ok(reduced)
}

fn gcd_u128(mut a: u128, mut b: u128) -> u128 {
    while b != 0 {
        let remainder = a % b;
        a = b;
        b = remainder;
    }
    a
}

/// Parameters for redeeming winnings
#[derive(Debug, Clone)]
pub struct RedeemWinningsParams {
    /// User pubkey
    pub user: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Deposit mint pubkey
    pub deposit_mint: Pubkey,
    /// Amount of winning tokens to redeem
    pub amount: u64,
}

/// Parameters for withdrawing from a position
#[derive(Debug, Clone)]
pub struct WithdrawFromPositionParams {
    /// User pubkey (must be position owner)
    pub user: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Mint pubkey (deposit or conditional)
    pub mint: Pubkey,
    /// Amount to withdraw
    pub amount: u64,
    /// Outcome index (255 for collateral)
    pub outcome_index: u8,
}

/// Parameters for activating a market
#[derive(Debug, Clone)]
pub struct ActivateMarketParams {
    /// Manager pubkey (must be exchange manager)
    pub manager: Pubkey,
    /// Market ID
    pub market_id: u64,
}

/// Parameters for creating a bid order
#[derive(Debug, Clone)]
pub struct BidOrderParams {
    /// Order nonce (unique per user)
    pub nonce: u64,
    /// Random salt for order uniqueness
    pub salt: u64,
    /// Maker pubkey
    pub maker: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Base mint (token being bought)
    pub base_mint: Pubkey,
    /// Quote mint (token used for payment)
    pub quote_mint: Pubkey,
    /// Quote tokens to give (on-chain amount_in, maps to API `amount_in`)
    pub amount_in: u64,
    /// Base tokens to receive (on-chain amount_out, maps to API `amount_out`)
    pub amount_out: u64,
    /// Expiration timestamp (0 for no expiration)
    pub expiration: i64,
}

/// Parameters for creating an ask order
#[derive(Debug, Clone)]
pub struct AskOrderParams {
    /// Order nonce (unique per user)
    pub nonce: u64,
    /// Random salt for order uniqueness
    pub salt: u64,
    /// Maker pubkey
    pub maker: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Base mint (token being sold)
    pub base_mint: Pubkey,
    /// Quote mint (token to receive)
    pub quote_mint: Pubkey,
    /// Base tokens to give (on-chain amount_in, maps to API `amount_in`)
    pub amount_in: u64,
    /// Quote tokens to receive (on-chain amount_out, maps to API `amount_out`)
    pub amount_out: u64,
    /// Expiration timestamp (0 for no expiration)
    pub expiration: i64,
}

/// Parameters for matching orders
#[derive(Debug, Clone)]
pub struct MatchOrdersMultiParams {
    /// Operator pubkey (must be exchange operator)
    pub operator: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Base mint pubkey
    pub base_mint: Pubkey,
    /// Quote mint pubkey
    pub quote_mint: Pubkey,
    /// Current exchange fee receiver. Used to derive the quote ATA that collects fees.
    pub fee_receiver: Pubkey,
    /// Taker order (signed)
    pub taker_order: OrderPayload,
    /// Maker orders (signed)
    pub maker_orders: Vec<OrderPayload>,
    /// Fill amounts for each maker (maker side)
    pub maker_fill_amounts: Vec<u64>,
    /// Fill amounts for each maker (taker side)
    pub taker_fill_amounts: Vec<u64>,
    /// Bitmask indicating which orders require full fill (bit i = maker i, bit 7 = taker)
    pub full_fill_bitmask: u8,
}

/// Parameters for creating an on-chain orderbook
#[derive(Debug, Clone)]
pub struct CreateOrderbookParams {
    /// Manager pubkey (must be exchange manager, pays for account creation)
    pub manager: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// First conditional mint pubkey. The builder canonicalizes account order.
    pub mint_a: Pubkey,
    /// Second conditional mint pubkey. The builder canonicalizes account order.
    pub mint_b: Pubkey,
    /// Current exchange fee receiver. The orderbook ALT records its quote ATA.
    pub fee_receiver: Pubkey,
    /// Deposit mint used to derive `mint_a`
    pub mint_a_deposit_mint: Pubkey,
    /// Deposit mint used to derive `mint_b`
    pub mint_b_deposit_mint: Pubkey,
    /// Recent slot for ALT creation
    pub recent_slot: u64,
    /// Which supplied mint is the base asset (0 = mint_a, 1 = mint_b)
    pub base_index: u8,
    /// Outcome index used to derive `mint_a`
    pub mint_a_outcome_index: u8,
    /// Outcome index used to derive `mint_b`
    pub mint_b_outcome_index: u8,
}

/// Parameters for setting a new authority
#[derive(Debug, Clone)]
pub struct SetAuthorityParams {
    /// Current authority pubkey
    pub current_authority: Pubkey,
    /// New authority pubkey
    pub new_authority: Pubkey,
}

/// Parameters for setting a new manager
#[derive(Debug, Clone)]
pub struct SetManagerParams {
    /// Current authority pubkey
    pub authority: Pubkey,
    /// New manager pubkey
    pub new_manager: Pubkey,
}

/// One per-market fee update.
#[derive(Debug, Clone)]
pub struct MarketFeeUpdate {
    /// Market account to update.
    pub market: Pubkey,
    /// Maker fee in basis points. Must be in [-500, 500].
    pub maker_fee_bps: i16,
    /// Taker fee in basis points. Must be in [-500, 500].
    pub taker_fee_bps: i16,
}

/// Parameters for setting fees on one or more markets.
#[derive(Debug, Clone)]
pub struct SetMarketFeesParams {
    /// Manager pubkey (must be exchange manager)
    pub manager: Pubkey,
    /// Fee updates, one account and one maker/taker pair per market.
    pub updates: Vec<MarketFeeUpdate>,
}

/// Parameters for setting the exchange fee receiver.
#[derive(Debug, Clone)]
pub struct SetFeeReceiverParams {
    /// Current authority pubkey
    pub authority: Pubkey,
    /// New fee receiver. Must not be the zero pubkey.
    pub new_fee_receiver: Pubkey,
}

/// Parameters for creating or updating Metaplex metadata for a conditional mint.
#[derive(Debug, Clone)]
pub struct ConditionalMetadataParams {
    /// Manager pubkey (must be exchange manager)
    pub manager: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Deposit mint backing the conditional mint
    pub deposit_mint: Pubkey,
    /// Outcome index for the conditional mint
    pub outcome_index: u8,
    /// Metadata name, max 32 UTF-8 bytes.
    pub name: String,
    /// Metadata symbol, max 10 UTF-8 bytes.
    pub symbol: String,
    /// Metadata URI, max 200 UTF-8 bytes.
    pub uri: String,
}

/// Parameters for whitelisting a deposit token for global deposits
#[derive(Debug, Clone)]
pub struct WhitelistDepositTokenParams {
    /// Authority pubkey (must be exchange authority)
    pub authority: Pubkey,
    /// Mint pubkey to whitelist
    pub mint: Pubkey,
}

/// Parameters for depositing tokens to a global deposit account
#[derive(Debug, Clone)]
pub struct DepositToGlobalParams {
    /// User pubkey (depositor)
    pub user: Pubkey,
    /// Deposit token mint pubkey
    pub mint: Pubkey,
    /// Amount to deposit
    pub amount: u64,
}

/// Optional user deposit ALT behavior for `deposit_to_global`.
#[derive(Debug, Clone, Copy)]
pub enum DepositToGlobalAltContext {
    /// Create the user's deposit ALT at PDA([user_nonce, recent_slot]).
    Create {
        /// Recent slot for ALT address derivation.
        recent_slot: u64,
    },
    /// Extend an existing user deposit ALT.
    Extend {
        /// Existing lookup table address.
        lookup_table: Pubkey,
    },
}

/// Parameters for transferring from global deposit to a market vault
#[derive(Debug, Clone)]
pub struct GlobalToMarketDepositParams {
    /// User pubkey
    pub user: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Deposit mint pubkey (e.g., USDC)
    pub deposit_mint: Pubkey,
    /// Amount of collateral to transfer and mint
    pub amount: u64,
}

/// Parameters for initializing position token accounts and ALT.
///
/// Permissionless — anyone can pay to create positions/ATAs/ALTs for any user.
#[derive(Debug, Clone)]
pub struct InitPositionTokensParams {
    /// Payer for account creation (signer, does not need to be the user)
    pub payer: Pubkey,
    /// Position owner (does not need to sign)
    pub user: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Deposit mints to initialize (must be in ascending GDT index order)
    pub deposit_mints: Vec<Pubkey>,
    /// Recent slot for ALT address derivation
    pub recent_slot: u64,
}

/// Per-maker fill info for deposit_and_swap
#[derive(Debug, Clone)]
pub struct MakerFill {
    /// Maker order (signed)
    pub order: OrderPayload,
    /// Fill amount (maker side)
    pub maker_fill_amount: u64,
    /// Fill amount (taker side)
    pub taker_fill_amount: u64,
    /// Whether this maker requires full fill (skips order_status account)
    pub is_full_fill: bool,
    /// Whether this maker deposits from global (vs swapping existing tokens)
    pub is_deposit: bool,
    /// Deposit mint for this maker (only used when is_deposit is true)
    pub deposit_mint: Pubkey,
}

/// Parameters for deposit-and-swap (atomic deposit + mint + swap)
#[derive(Debug, Clone)]
pub struct DepositAndSwapParams {
    /// Operator pubkey (must be exchange operator)
    pub operator: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Base mint pubkey (conditional token A)
    pub base_mint: Pubkey,
    /// Quote mint pubkey (conditional token B)
    pub quote_mint: Pubkey,
    /// Current exchange fee receiver. Used to derive the quote ATA that collects fees.
    pub fee_receiver: Pubkey,
    /// Taker order (signed)
    pub taker_order: OrderPayload,
    /// Whether the taker requires full fill
    pub taker_is_full_fill: bool,
    /// Whether the taker deposits from global
    pub taker_is_deposit: bool,
    /// Taker's deposit mint (only used when taker_is_deposit is true)
    pub taker_deposit_mint: Pubkey,
    /// Number of outcomes for the market
    pub num_outcomes: u8,
    /// Per-maker fill info
    pub makers: Vec<MakerFill>,
}

/// Parameters for extending a position ALT with new deposit mints
#[derive(Debug, Clone)]
pub struct ExtendPositionTokensParams {
    /// Operator for account creation (signer)
    pub operator: Pubkey,
    /// Position owner (does not need to sign)
    pub user: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Existing ALT pubkey from init_position_tokens
    pub lookup_table: Pubkey,
    /// New deposit mints to add (must be in ascending GDT index order)
    pub deposit_mints: Vec<Pubkey>,
}

/// Parameters for withdrawing tokens from a global deposit account
#[derive(Debug, Clone)]
pub struct WithdrawFromGlobalParams {
    /// User pubkey (must be the depositor / signer)
    pub user: Pubkey,
    /// Deposit token mint pubkey
    pub mint: Pubkey,
    /// Amount to withdraw
    pub amount: u64,
}

/// Parameters for deactivating or closing a position ALT.
#[derive(Debug, Clone)]
pub struct ClosePositionAltParams {
    /// Operator pubkey (must be exchange operator)
    pub operator: Pubkey,
    /// Position PDA whose ALT authority controls the lookup table
    pub position: Pubkey,
    /// Resolved market pubkey
    pub market: Pubkey,
    /// Position lookup table pubkey
    pub lookup_table: Pubkey,
}

/// Parameters for closing a fully-filled order status PDA.
#[derive(Debug, Clone)]
pub struct CloseOrderStatusParams {
    /// Operator pubkey (must be exchange operator)
    pub operator: Pubkey,
    /// Order hash used to derive the order status PDA
    pub order_hash: [u8; 32],
}

/// Parameters for closing empty position-owned conditional token accounts.
#[derive(Debug, Clone)]
pub struct ClosePositionTokenAccountsParams {
    /// Operator pubkey (must be exchange operator)
    pub operator: Pubkey,
    /// Resolved market pubkey
    pub market: Pubkey,
    /// Position PDA
    pub position: Pubkey,
    /// Deposit mints whose conditional ATAs should be considered
    pub deposit_mints: Vec<Pubkey>,
}

/// Parameters for deactivating or closing an orderbook ALT.
#[derive(Debug, Clone)]
pub struct CloseOrderbookAltParams {
    /// Operator pubkey (must be exchange operator)
    pub operator: Pubkey,
    /// Orderbook PDA
    pub orderbook: Pubkey,
    /// Resolved market pubkey
    pub market: Pubkey,
    /// Lookup table stored on the orderbook account
    pub lookup_table: Pubkey,
}

/// Parameters for closing an orderbook PDA after its ALT has been closed.
#[derive(Debug, Clone)]
pub struct CloseOrderbookParams {
    /// Operator pubkey (must be exchange operator)
    pub operator: Pubkey,
    /// Orderbook PDA
    pub orderbook: Pubkey,
    /// Resolved market pubkey
    pub market: Pubkey,
    /// Lookup table stored on the orderbook account; must already be closed
    pub lookup_table: Pubkey,
}

// ============================================================================
// Unified Deposit/Withdraw Parameters
// ============================================================================

/// Unified deposit parameters — dispatches to global or market deposit
/// based on the client's deposit source setting.
///
/// Prefer using the builder via `client.positions().deposit().await` which
/// pre-seeds the client's deposit source. Direct construction is also available.
#[derive(Debug)]
pub struct DepositParams<'a> {
    /// User pubkey (depositor).
    pub user: Pubkey,
    /// Deposit token mint pubkey.
    pub mint: Pubkey,
    /// Amount to deposit.
    pub amount: u64,
    /// Required when deposit source is `Market`. Provides the market pubkey
    /// and outcome count.
    pub market: Option<&'a Market>,
    /// Per-call override. If `None`, uses the client-level deposit source.
    pub deposit_source: Option<DepositSource>,
}

/// Market-specific context required for withdrawals when deposit source is `Market`.
#[derive(Debug)]
pub struct MarketWithdrawContext<'a> {
    /// The market to withdraw from.
    pub market: &'a Market,
    /// Outcome index to withdraw. Use `255` for collateral.
    pub outcome_index: u8,
}

/// Unified withdraw parameters — dispatches to global or market withdrawal
/// based on the client's deposit source setting.
///
/// Prefer using the builder via `client.positions().withdraw().await` which
/// pre-seeds the client's deposit source. Direct construction is also available.
#[derive(Debug)]
pub struct WithdrawParams<'a> {
    /// User pubkey (must be the depositor / position owner).
    pub user: Pubkey,
    /// Token mint pubkey.
    pub mint: Pubkey,
    /// Amount to withdraw.
    pub amount: u64,
    /// Required when deposit source is `Market`.
    pub market_context: Option<MarketWithdrawContext<'a>>,
    /// Per-call override. If `None`, uses the client-level deposit source.
    pub deposit_source: Option<DepositSource>,
}