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
//! Orders sub-client — submit, cancel, query, and on-chain order operations.

use super::wire::{UserSnapshotBalance, UserSnapshotOrder};
use crate::client::LightconeClient;
use crate::domain::order::UserOrderFillsResponse;
use crate::error::SdkError;
use crate::http::RetryPolicy;
#[cfg(feature = "trigger_orders")]
use crate::program::envelope::TriggerOrderEnvelope;
use crate::program::envelope::{LimitOrderEnvelope, OrderEnvelope};
use crate::program::error::{SdkError as ProgramSdkError, SdkResult};
use crate::program::instructions;
use crate::program::orders::OrderPayload;
use crate::program::types::CloseOrderStatusParams;
use crate::shared::{OrderBookId, PubkeyStr};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use solana_instruction::Instruction;
use solana_pubkey::Pubkey;
use solana_signature::Signature;
use solana_transaction::Transaction;

#[cfg(feature = "native-auth")]
use solana_keypair::Keypair;
#[cfg(feature = "native-auth")]
use solana_signer::Signer;

// ─── Request types ───────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelBody {
    pub order_hash: String,
    pub maker: PubkeyStr,
    pub signature: String,
}

impl CancelBody {
    /// Build a cancel request with a base58-encoded signature (from a wallet adapter).
    /// Converts base58 to the hex encoding the backend expects.
    pub fn from_base58(order_hash: String, maker: PubkeyStr, sig_bs58: &str) -> SdkResult<Self> {
        let sig = sig_bs58
            .parse::<Signature>()
            .map_err(|_| ProgramSdkError::InvalidSignature)?;
        Ok(Self {
            order_hash,
            maker,
            signature: hex::encode(sig.as_ref()),
        })
    }

    /// Build a signed cancel request using a keypair.
    /// Signs `cancel_order_message(order_hash)` and hex-encodes the result.
    #[cfg(feature = "native-auth")]
    pub fn signed(order_hash: String, maker: PubkeyStr, keypair: &Keypair) -> Self {
        let message = crate::program::orders::cancel_order_message(&order_hash);
        let sig = keypair.sign_message(&message);
        Self {
            order_hash,
            maker,
            signature: hex::encode(sig.as_ref()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelAllBody {
    pub user_pubkey: PubkeyStr,
    #[serde(default)]
    pub orderbook_id: OrderBookId,
    pub signature: String,
    pub timestamp: i64,
    pub salt: String,
}

impl CancelAllBody {
    /// Build a cancel-all request with a base58-encoded signature (from a wallet adapter).
    /// Converts base58 to the hex encoding the backend expects.
    pub fn from_base58(
        user_pubkey: PubkeyStr,
        orderbook_id: OrderBookId,
        timestamp: i64,
        salt: String,
        sig_bs58: &str,
    ) -> SdkResult<Self> {
        let sig = sig_bs58
            .parse::<Signature>()
            .map_err(|_| ProgramSdkError::InvalidSignature)?;
        Ok(Self {
            user_pubkey,
            orderbook_id,
            signature: hex::encode(sig.as_ref()),
            timestamp,
            salt,
        })
    }

    /// Build a signed cancel-all request using a native keypair.
    /// Signs `cancel_all_message(user_pubkey, orderbook_id, timestamp, salt)` and hex-encodes the result.
    #[cfg(feature = "native-auth")]
    pub fn signed(
        user_pubkey: PubkeyStr,
        orderbook_id: OrderBookId,
        timestamp: i64,
        salt: String,
        keypair: &Keypair,
    ) -> Self {
        let message = crate::program::orders::cancel_all_message(
            user_pubkey.as_str(),
            orderbook_id.as_str(),
            timestamp,
            &salt,
        );
        let sig = keypair.sign_message(message.as_bytes());
        Self {
            user_pubkey,
            orderbook_id,
            signature: hex::encode(sig.as_ref()),
            timestamp,
            salt,
        }
    }
}

#[cfg(feature = "trigger_orders")]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelTriggerBody {
    pub trigger_order_id: String,
    pub maker: PubkeyStr,
    pub signature: String,
}

#[cfg(feature = "trigger_orders")]
impl CancelTriggerBody {
    /// Build a cancel-trigger request with a base58-encoded signature (from a wallet adapter).
    /// Converts base58 to the hex encoding the backend expects.
    pub fn from_base58(
        trigger_order_id: String,
        maker: PubkeyStr,
        sig_bs58: &str,
    ) -> SdkResult<Self> {
        let sig = sig_bs58
            .parse::<Signature>()
            .map_err(|_| ProgramSdkError::InvalidSignature)?;
        Ok(Self {
            trigger_order_id,
            maker,
            signature: hex::encode(sig.as_ref()),
        })
    }

    /// Build a signed cancel-trigger request using a native keypair.
    /// Signs `cancel_trigger_order_message(trigger_order_id)` and hex-encodes the result.
    #[cfg(feature = "native-auth")]
    pub fn signed(trigger_order_id: String, maker: PubkeyStr, keypair: &Keypair) -> Self {
        let message = crate::program::orders::cancel_trigger_order_message(&trigger_order_id);
        let sig = keypair.sign_message(&message);
        Self {
            trigger_order_id,
            maker,
            signature: hex::encode(sig.as_ref()),
        }
    }
}

// ─── Response types ──────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FillInfo {
    pub counterparty: PubkeyStr,
    pub counterparty_order_hash: String,
    pub fill_amount: Decimal,
    pub price: Decimal,
    pub is_maker: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SubmitOrderResponse {
    pub order_hash: String,
    pub remaining: Decimal,
    pub filled: Decimal,
    pub fills: Vec<FillInfo>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelSuccess {
    pub order_hash: String,
    pub remaining: Decimal,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelAllSuccess {
    pub cancelled_order_hashes: Vec<String>,
    pub count: u64,
    pub user_pubkey: PubkeyStr,
    pub orderbook_id: OrderBookId,
    pub message: String,
}

#[cfg(feature = "trigger_orders")]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TriggerOrderResponse {
    pub trigger_order_id: String,
    pub order_hash: String,
}

#[cfg(feature = "trigger_orders")]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelTriggerSuccess {
    pub trigger_order_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UserOrdersResponse {
    pub user_pubkey: PubkeyStr,
    /// All orders (both limit and trigger) in a single array.
    /// Discriminated by `order_type` field on each order.
    pub orders: Vec<UserSnapshotOrder>,
    pub balances: Vec<UserSnapshotBalance>,
    pub next_cursor: Option<String>,
    pub has_more: bool,
}

// ─── Sub-client ──────────────────────────────────────────────────────────────

pub struct Orders<'a> {
    pub(crate) client: &'a LightconeClient,
}

impl<'a> Orders<'a> {
    // ── PDA helpers ──────────────────────────────────────────────────────

    /// Get the Order Status PDA.
    pub fn status_pda(&self, order_hash: &[u8; 32]) -> Pubkey {
        crate::program::pda::get_order_status_pda(order_hash, &self.client.program_id).0
    }

    /// Get the User Nonce PDA.
    pub fn nonce_pda(&self, user: &Pubkey) -> Pubkey {
        crate::program::pda::get_user_nonce_pda(user, &self.client.program_id).0
    }

    // ── Envelope factories ────────────────────────────────────────────────

    /// Create a `LimitOrderEnvelope` pre-seeded with the client's deposit source.
    ///
    /// Users can still override the deposit source on the returned envelope
    /// by calling `.deposit_source()` before signing.
    pub async fn limit_order(&self) -> LimitOrderEnvelope {
        let deposit_source = self.client.deposit_source().await;
        LimitOrderEnvelope::new().deposit_source(deposit_source)
    }

    /// Create a `TriggerOrderEnvelope` pre-seeded with the client's deposit source.
    ///
    /// Users can still override the deposit source on the returned envelope
    /// by calling `.deposit_source()` before signing.
    #[cfg(feature = "trigger_orders")]
    pub async fn trigger_order(&self) -> TriggerOrderEnvelope {
        let deposit_source = self.client.deposit_source().await;
        TriggerOrderEnvelope::new().deposit_source(deposit_source)
    }

    // ── Helpers ──────────────────────────────────────────────────────────

    /// Generate a random salt for cancel-all replay protection.
    pub fn generate_cancel_all_salt(&self) -> String {
        crate::program::orders::generate_cancel_all_salt()
    }

    pub async fn submit(
        &self,
        request: &impl serde::Serialize,
    ) -> Result<SubmitOrderResponse, SdkError> {
        let url = format!("{}/api/orders/submit", self.client.http.base_url());
        self.client
            .http
            .post(&url, request, RetryPolicy::None)
            .await
    }

    pub async fn cancel(&self, body: &CancelBody) -> Result<CancelSuccess, SdkError> {
        let url = format!("{}/api/orders/cancel", self.client.http.base_url());
        self.client.http.post(&url, body, RetryPolicy::None).await
    }

    pub async fn cancel_all(&self, body: &CancelAllBody) -> Result<CancelAllSuccess, SdkError> {
        let url = format!("{}/api/orders/cancel-all", self.client.http.base_url());
        self.client.http.post(&url, body, RetryPolicy::None).await
    }

    #[cfg(feature = "trigger_orders")]
    pub async fn submit_trigger(
        &self,
        request: &impl serde::Serialize,
    ) -> Result<TriggerOrderResponse, SdkError> {
        let url = format!("{}/api/orders/submit", self.client.http.base_url());
        self.client
            .http
            .post(&url, request, RetryPolicy::None)
            .await
    }

    #[cfg(feature = "trigger_orders")]
    pub async fn cancel_trigger(
        &self,
        body: &CancelTriggerBody,
    ) -> Result<CancelTriggerSuccess, SdkError> {
        let url = format!("{}/api/orders/cancel", self.client.http.base_url());
        self.client.http.post(&url, body, RetryPolicy::None).await
    }

    /// Fetch the authenticated user's open orders. Wallet is resolved
    /// server-side from the auth cookie, so no parameter is required.
    pub async fn get_user_orders(
        &self,
        limit: Option<u32>,
        cursor: Option<&str>,
    ) -> Result<UserOrdersResponse, SdkError> {
        let url = format!("{}/api/users/orders", self.client.http.base_url());
        let mut query = Vec::new();
        if let Some(limit) = limit {
            query.push(("limit", limit.to_string()));
        }
        if let Some(cursor) = cursor {
            query.push(("cursor", cursor.to_string()));
        }
        self.client
            .http
            .get_with_query(&url, &query, RetryPolicy::Idempotent)
            .await
    }

    /// Same as [`Self::get_user_orders`], but forwards the supplied raw `Cookie`
    /// header (`privy-token` and/or `lightcone-token`) for this call instead of
    /// the SDK's process-wide token store. Intended for server-side cookie
    /// forwarding (SSR / server functions).
    pub async fn get_user_orders_with_cookies(
        &self,
        limit: Option<u32>,
        cursor: Option<&str>,
        cookie_header: &str,
    ) -> Result<UserOrdersResponse, SdkError> {
        let url = format!("{}/api/users/orders", self.client.http.base_url());
        let mut query = Vec::new();
        if let Some(limit) = limit {
            query.push(("limit", limit.to_string()));
        }
        if let Some(cursor) = cursor {
            query.push(("cursor", cursor.to_string()));
        }
        self.client
            .http
            .get_with_cookies_and_query(&url, &query, RetryPolicy::Idempotent, cookie_header)
            .await
    }

    /// Fetch the authenticated user's filled orders with nested fill events.
    /// Wallet is resolved server-side from the auth cookie.
    ///
    /// Includes orders where the user was either maker or taker.
    /// Optionally filter by market. Returns orders sorted by most recent fill first.
    pub async fn get_user_order_fills(
        &self,
        market_pubkey: Option<&str>,
        limit: Option<u32>,
        cursor: Option<&str>,
    ) -> Result<UserOrderFillsResponse, SdkError> {
        let url = format!("{}/api/users/order-fills", self.client.http.base_url());
        let mut query = Vec::new();
        if let Some(market_pubkey) = market_pubkey {
            query.push(("market_pubkey", market_pubkey.to_string()));
        }
        if let Some(limit) = limit {
            query.push(("limit", limit.to_string()));
        }
        if let Some(cursor) = cursor {
            query.push(("cursor", cursor.to_string()));
        }
        self.client
            .http
            .get_with_query(&url, &query, RetryPolicy::Idempotent)
            .await
    }

    /// Same as [`Self::get_user_order_fills`], but forwards the supplied raw
    /// `Cookie` header (`privy-token` and/or `lightcone-token`) for this call
    /// instead of the SDK's process-wide token store. Intended for server-side
    /// cookie forwarding (SSR / server functions).
    pub async fn get_user_order_fills_with_cookies(
        &self,
        market_pubkey: Option<&str>,
        limit: Option<u32>,
        cursor: Option<&str>,
        cookie_header: &str,
    ) -> Result<UserOrderFillsResponse, SdkError> {
        let url = format!("{}/api/users/order-fills", self.client.http.base_url());
        let mut query = Vec::new();
        if let Some(market_pubkey) = market_pubkey {
            query.push(("market_pubkey", market_pubkey.to_string()));
        }
        if let Some(limit) = limit {
            query.push(("limit", limit.to_string()));
        }
        if let Some(cursor) = cursor {
            query.push(("cursor", cursor.to_string()));
        }
        self.client
            .http
            .get_with_cookies_and_query(&url, &query, RetryPolicy::Idempotent, cookie_header)
            .await
    }

    /// Public variant of [`Self::get_user_order_fills`]. Takes the user's
    /// wallet via the URL path (`GET /api/users/{wallet}/order-fills`) and
    /// requires no auth.
    pub async fn get_user_order_fills_by_wallet(
        &self,
        wallet_address: &str,
        market_pubkey: Option<&str>,
        limit: Option<u32>,
        cursor: Option<&str>,
    ) -> Result<UserOrderFillsResponse, SdkError> {
        let url = format!(
            "{}/api/users/{}/order-fills",
            self.client.http.base_url(),
            wallet_address
        );
        let mut query = Vec::new();
        if let Some(market_pubkey) = market_pubkey {
            query.push(("market_pubkey", market_pubkey.to_string()));
        }
        if let Some(limit) = limit {
            query.push(("limit", limit.to_string()));
        }
        if let Some(cursor) = cursor {
            query.push(("cursor", cursor.to_string()));
        }
        self.client
            .http
            .get_with_query(&url, &query, RetryPolicy::Idempotent)
            .await
    }

    // ── Unified cancel (dispatches based on client signing strategy) ────

    /// Cancel an order using the client's signing strategy.
    ///
    /// Signs the cancel message and submits the cancellation request.
    pub async fn cancel_order_signed(
        &self,
        order_hash: &str,
        maker: &PubkeyStr,
    ) -> Result<CancelSuccess, SdkError> {
        use crate::shared::signing::SigningStrategy;

        let strategy = self.client.signing_strategy().await.ok_or_else(|| {
            SdkError::Validation("signing strategy is not set on the client".into())
        })?;

        match strategy {
            #[cfg(feature = "native-auth")]
            SigningStrategy::Native(keypair) => {
                let body = CancelBody::signed(order_hash.to_string(), maker.clone(), &keypair);
                self.cancel(&body).await
            }
            SigningStrategy::WalletAdapter(signer) => {
                let message = crate::program::orders::cancel_order_message(order_hash);
                let sig_bytes = signer
                    .sign_message(&message)
                    .await
                    .map_err(crate::shared::signing::classify_signer_error)?;
                let sig_bs58 = bs58::encode(&sig_bytes).into_string();
                let body =
                    CancelBody::from_base58(order_hash.to_string(), maker.clone(), &sig_bs58)
                        .map_err(|error| SdkError::Program(error))?;
                self.cancel(&body).await
            }
        }
    }

    /// Cancel all orders using the client's signing strategy.
    ///
    /// Signs the cancel-all message and submits the cancellation request.
    pub async fn cancel_all_signed(
        &self,
        user_pubkey: &PubkeyStr,
        timestamp: i64,
        salt: &str,
        // Optional: limit to specific orderbook
        orderbook_id: Option<&OrderBookId>,
    ) -> Result<CancelAllSuccess, SdkError> {
        use crate::shared::signing::SigningStrategy;

        let strategy = self.client.signing_strategy().await.ok_or_else(|| {
            SdkError::Validation("signing strategy is not set on the client".into())
        })?;

        let resolved_orderbook_id = orderbook_id
            .cloned()
            .unwrap_or_else(|| OrderBookId::from(""));
        let orderbook_id_str = resolved_orderbook_id.as_str();

        match strategy {
            #[cfg(feature = "native-auth")]
            SigningStrategy::Native(keypair) => {
                let body = CancelAllBody::signed(
                    user_pubkey.clone(),
                    resolved_orderbook_id.clone(),
                    timestamp,
                    salt.to_string(),
                    &keypair,
                );
                self.cancel_all(&body).await
            }
            SigningStrategy::WalletAdapter(signer) => {
                let message = crate::program::orders::cancel_all_message(
                    user_pubkey.as_str(),
                    orderbook_id_str,
                    timestamp,
                    salt,
                );
                let sig_bytes = signer
                    .sign_message(message.as_bytes())
                    .await
                    .map_err(crate::shared::signing::classify_signer_error)?;
                let sig_bs58 = bs58::encode(&sig_bytes).into_string();
                let body = CancelAllBody::from_base58(
                    user_pubkey.clone(),
                    resolved_orderbook_id.clone(),
                    timestamp,
                    salt.to_string(),
                    &sig_bs58,
                )
                .map_err(|error| SdkError::Program(error))?;
                self.cancel_all(&body).await
            }
        }
    }

    /// Cancel a trigger order using the client's signing strategy.
    ///
    /// Signs the cancel message and submits the cancellation request.
    #[cfg(feature = "trigger_orders")]
    pub async fn cancel_trigger_signed(
        &self,
        trigger_order_id: &str,
        maker: &PubkeyStr,
    ) -> Result<CancelTriggerSuccess, SdkError> {
        use crate::shared::signing::SigningStrategy;

        let strategy = self.client.signing_strategy().await.ok_or_else(|| {
            SdkError::Validation("signing strategy is not set on the client".into())
        })?;

        match strategy {
            #[cfg(feature = "native-auth")]
            SigningStrategy::Native(keypair) => {
                let body = CancelTriggerBody::signed(
                    trigger_order_id.to_string(),
                    maker.clone(),
                    &keypair,
                );
                self.cancel_trigger(&body).await
            }
            SigningStrategy::WalletAdapter(signer) => {
                let message =
                    crate::program::orders::cancel_trigger_order_message(trigger_order_id);
                let sig_bytes = signer
                    .sign_message(&message)
                    .await
                    .map_err(crate::shared::signing::classify_signer_error)?;
                let sig_bs58 = bs58::encode(&sig_bytes).into_string();
                let body = CancelTriggerBody::from_base58(
                    trigger_order_id.to_string(),
                    maker.clone(),
                    &sig_bs58,
                )
                .map_err(|error| SdkError::Program(error))?;
                self.cancel_trigger(&body).await
            }
        }
    }

    // ── On-chain instruction builders ───────────────────────────────────

    /// Build CancelOrder instruction (on-chain cancellation).
    pub fn cancel_order_ix(
        &self,
        operator: &Pubkey,
        market: &Pubkey,
        order: &OrderPayload,
    ) -> Instruction {
        let pid = &self.client.program_id;
        instructions::build_cancel_order_ix(operator, market, order, pid)
    }

    /// Build CancelOrder transaction (on-chain cancellation).
    pub fn cancel_order_tx(
        &self,
        operator: &Pubkey,
        market: &Pubkey,
        order: &OrderPayload,
    ) -> Result<Transaction, SdkError> {
        let ix = self.cancel_order_ix(operator, market, order);
        Ok(Transaction::new_with_payer(&[ix], Some(operator)))
    }

    /// Build IncrementNonce instruction.
    pub fn increment_nonce_ix(&self, user: &Pubkey) -> Instruction {
        let pid = &self.client.program_id;
        instructions::build_increment_nonce_ix(user, pid)
    }

    /// Build IncrementNonce transaction.
    pub fn increment_nonce_tx(&self, user: &Pubkey) -> Result<Transaction, SdkError> {
        let ix = self.increment_nonce_ix(user);
        Ok(Transaction::new_with_payer(&[ix], Some(user)))
    }

    /// Build CloseOrderStatus instruction.
    pub fn close_order_status_ix(&self, params: &CloseOrderStatusParams) -> Instruction {
        let pid = &self.client.program_id;
        instructions::build_close_order_status_ix(params, pid)
    }

    /// Build CloseOrderStatus transaction.
    pub fn close_order_status_tx(
        &self,
        params: CloseOrderStatusParams,
    ) -> Result<Transaction, SdkError> {
        let ix = self.close_order_status_ix(&params);
        Ok(Transaction::new_with_payer(&[ix], Some(&params.operator)))
    }

    // ── Order helpers ────────────────────────────────────────────────────

    /// Create an unsigned bid order.
    pub fn create_bid_order(&self, params: crate::program::types::BidOrderParams) -> OrderPayload {
        OrderPayload::new_bid(params)
    }

    /// Create an unsigned ask order.
    pub fn create_ask_order(&self, params: crate::program::types::AskOrderParams) -> OrderPayload {
        OrderPayload::new_ask(params)
    }

    /// Create and sign a bid order.
    #[cfg(feature = "native-auth")]
    pub fn create_signed_bid_order(
        &self,
        params: crate::program::types::BidOrderParams,
        keypair: &Keypair,
    ) -> OrderPayload {
        OrderPayload::new_bid_signed(params, keypair)
    }

    /// Create and sign an ask order.
    #[cfg(feature = "native-auth")]
    pub fn create_signed_ask_order(
        &self,
        params: crate::program::types::AskOrderParams,
        keypair: &Keypair,
    ) -> OrderPayload {
        OrderPayload::new_ask_signed(params, keypair)
    }

    /// Compute the hash of an order.
    pub fn hash_order(&self, order: &OrderPayload) -> [u8; 32] {
        order.hash()
    }

    /// Sign an order with the given keypair.
    #[cfg(feature = "native-auth")]
    pub fn sign_order(&self, order: &mut OrderPayload, keypair: &Keypair) {
        order.sign(keypair);
    }
}

// ═════════════════════════════════════════════════════════════════════════════
// On-chain account fetchers (require RPC)
// ═════════════════════════════════════════════════════════════════════════════

#[cfg(feature = "solana-rpc")]
impl<'a> Orders<'a> {
    /// Fetch an OrderStatus account (returns None if not found).
    pub async fn get_status(
        &self,
        order_hash: &[u8; 32],
    ) -> Result<Option<crate::program::accounts::OrderStatus>, SdkError> {
        let rpc = crate::rpc::resolve_solana_rpc(self.client).await?;
        let pda = self.status_pda(order_hash);
        match rpc.get_account(&pda).await {
            Ok(account) => Ok(Some(crate::program::accounts::OrderStatus::deserialize(
                &account.data,
            )?)),
            Err(_) => Ok(None),
        }
    }

    /// Fetch a user's current nonce (returns 0 if not initialized).
    pub async fn get_nonce(&self, user: &Pubkey) -> Result<u64, SdkError> {
        let rpc = crate::rpc::resolve_solana_rpc(self.client).await?;
        let pda = self.nonce_pda(user);
        match rpc.get_account(&pda).await {
            Ok(account) => {
                let user_nonce = crate::program::accounts::UserNonce::deserialize(&account.data)?;
                Ok(user_nonce.nonce)
            }
            Err(_) => Ok(0),
        }
    }

    /// Get the current on-chain nonce for a user as u32.
    pub async fn current_nonce(&self, user: &Pubkey) -> Result<u32, SdkError> {
        let nonce = self.get_nonce(user).await?;
        u32::try_from(nonce)
            .map_err(|_| SdkError::Program(crate::program::error::SdkError::Overflow))
    }
}