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
# Orders

Submit, cancel, and track limit and trigger orders.

[← Overview](../../../README.md#orders)

## Table of Contents

- [Types]#types
- [Client Methods]#client-methods
- [Order Envelope Builder]#order-envelope-builder
- [State Containers]#state-containers
- [Examples]#examples
- [Wire Types]#wire-types

## Types

### `Order` trait

Common interface shared by `LimitOrder` and `TriggerOrder`. Provides accessors for the six fields present on both types:

| Method | Returns | Description |
|--------|---------|-------------|
| `id()` | `&str` | Unique identifier (`order_hash` for limit, `trigger_order_id` for trigger) |
| `order_hash()` | `&str` | Underlying order hash |
| `market_pubkey()` | `&PubkeyStr` | Parent market |
| `orderbook_id()` | `&OrderBookId` | Which orderbook |
| `side()` | `Side` | `Bid` or `Ask` |
| `created_at()` | `DateTime<Utc>` | Creation timestamp |

Also implemented on `AnyOrder` (delegates to the inner variant).

### `LimitOrder`

A validated, domain-level limit order.

| Field | Type | Description |
|-------|------|-------------|
| `order_hash` | `String` | Unique order identifier |
| `market_pubkey` | `PubkeyStr` | Parent market |
| `orderbook_id` | `OrderBookId` | Which orderbook |
| `side` | `Side` | `Bid` (buy) or `Ask` (sell) |
| `price` | `Decimal` | Order price |
| `size` | `Decimal` | Total size |
| `filled_size` | `Decimal` | Amount filled so far |
| `remaining_size` | `Decimal` | Amount remaining |
| `status` | `OrderStatus` | Current status |
| `base_mint` | `PubkeyStr` | Base token mint |
| `quote_mint` | `PubkeyStr` | Quote token mint |
| `outcome_index` | `i16` | Which outcome |
| `tx_signature` | `Option<String>` | On-chain transaction signature |
| `created_at` | `DateTime<Utc>` | Creation timestamp |

### `TriggerOrder`

A take-profit or stop-loss trigger order. Held server-side until the trigger price is hit, then submitted as a limit order.

| Field | Type | Description |
|-------|------|-------------|
| `trigger_order_id` | `String` | Trigger order ID |
| `order_hash` | `String` | Underlying order hash |
| `market_pubkey` | `PubkeyStr` | Parent market |
| `orderbook_id` | `OrderBookId` | Which orderbook |
| `trigger_price` | `Decimal` | Price threshold that fires the order |
| `trigger_type` | `TriggerType` | `TakeProfit` (`"TP"`) or `StopLoss` (`"SL"`) |
| `side` | `Side` | `Bid` or `Ask` |
| `amount_in` | `Decimal` | Amount the maker gives |
| `amount_out` | `Decimal` | Amount the maker receives |
| `time_in_force` | `TimeInForce` | Execution constraint when triggered |
| `created_at` | `DateTime<Utc>` | Creation timestamp |

### `OrderStatus`

| Variant | Description |
|---------|-------------|
| `Open` | Resting on the book |
| `Matching` | Currently being matched |
| `Filled` | Fully filled |
| `Cancelled` | Cancelled by user or system |
| `Pending` | Awaiting processing |

### `OrderType`

| Variant | Description |
|---------|-------------|
| `Limit` | Standard limit order |
| `Market` | Market order (immediate execution) |
| `Deposit` | Deposit operation |
| `Withdraw` | Withdrawal operation |

### `TimeInForce`

Execution constraint for trigger orders.

| Variant | Serializes as | Description |
|---------|---------------|-------------|
| `Gtc` | `"GTC"` | Good-til-cancelled (default) |
| `Ioc` | `"IOC"` | Immediate-or-cancel |
| `Fok` | `"FOK"` | Fill-or-kill |
| `Alo` | `"ALO"` | Add-liquidity-only (post-only) |

### `TriggerType`

| Variant | Serializes as | Description |
|---------|---------------|-------------|
| `TakeProfit` | `"TP"` | Fires when price rises above trigger |
| `StopLoss` | `"SL"` | Fires when price falls below trigger |

### `UserOrderFill`

An order the user participated in (as maker or taker), with nested fill events.

| Field | Type | Description |
|-------|------|-------------|
| `order_hash` | `String` | Unique order identifier |
| `market_pubkey` | `PubkeyStr` | Parent market |
| `orderbook_id` | `OrderBookId` | Which orderbook |
| `side` | `Side` | User's side: `Bid` or `Ask` |
| `role` | `Role` | `Maker` or `Taker` |
| `price` | `Decimal` | Order price |
| `size` | `Decimal` | Total order size |
| `filled_size` | `Decimal` | Amount filled |
| `remaining_size` | `Decimal` | Amount remaining |
| `base_mint` | `PubkeyStr` | Base token mint |
| `quote_mint` | `PubkeyStr` | Quote token mint |
| `outcome_index` | `i16` | Which outcome |
| `status` | `OrderStatus` | `Filled`, `Cancelled`, or partially filled |
| `created_at` | `DateTime<Utc>` | Order creation timestamp |
| `fills` | `Vec<OrderFillEvent>` | Individual fill events |

### `OrderFillEvent`

| Field | Type | Description |
|-------|------|-------------|
| `fill_amount` | `Decimal` | Amount filled in this event |
| `tx_signature` | `String` | On-chain transaction signature |
| `filled_at` | `DateTime<Utc>` | When the fill occurred |

### `Role`

| Variant | Description |
|---------|-------------|
| `Maker` | User placed the order |
| `Taker` | User filled against the order |

## Client Methods

Access via `client.orders()`.

### `limit_order`

```rust
async fn limit_order(&self) -> LimitOrderEnvelope
```

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.

### `trigger_order`

```rust
async fn trigger_order(&self) -> TriggerOrderEnvelope
```

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.

### `submit`

```rust
async fn submit(&self, request: &impl Serialize) -> Result<SubmitOrderResponse, SdkError>
```

Submit a signed limit order. The `request` is typically a `SubmitOrderRequest` produced by an order envelope's `.sign()` or `.finalize()` method. **Not retried** -- non-idempotent.

### `cancel`

```rust
async fn cancel(&self, body: &CancelBody) -> Result<CancelSuccess, SdkError>
```

Cancel a single order by its hash. **Not retried.**

### `cancel_all`

```rust
async fn cancel_all(&self, body: &CancelAllBody) -> Result<CancelAllSuccess, SdkError>
```

Cancel all open orders, optionally scoped to a specific orderbook. **Not retried.**

`CancelAllBody` must include:
- `orderbook_id` in the signed message, using `""` to mean all markets
- `salt`, a unique UUID-like string for replay protection

### `submit_trigger`

```rust
async fn submit_trigger(&self, request: &impl Serialize) -> Result<TriggerOrderResponse, SdkError>
```

Submit a signed trigger order (take-profit or stop-loss). **Not retried.**

### `cancel_trigger`

```rust
async fn cancel_trigger(&self, body: &CancelTriggerBody) -> Result<CancelTriggerSuccess, SdkError>
```

Cancel a trigger order by its ID. **Not retried.**

### `get_user_orders`

```rust
async fn get_user_orders(
    &self,
    limit: Option<u32>,
    cursor: Option<&str>,
) -> Result<UserOrdersResponse, SdkError>
```

Fetch the **authenticated** user's open orders (both limit and trigger) with cursor-based pagination. Wallet is resolved from the `auth_token` cookie. See `get_user_orders_with_cookies` for the SSR variant.

### `get_user_order_fills`

```rust
async fn get_user_order_fills(
    &self,
    market_pubkey: Option<&str>,
    limit: Option<u32>,
    cursor: Option<&str>,
) -> Result<UserOrderFillsResponse, SdkError>
```

Fetch the **authenticated** user's filled orders (with nested fill events). See `get_user_order_fills_with_cookies` for the SSR variant and `get_user_order_fills_by_wallet` for the public path-based variant.

### `get_user_orders_with_cookies` / `get_user_order_fills_with_cookies`

SSR / server-function variants — accept an explicit `auth_token: &str` instead of using the SDK's process-wide token store. Same wire contract, different credentials path. See [the top-level Authentication section](../../../README.md#authentication).

### `get_user_order_fills_by_wallet`

```rust
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>
```

Public path-based variant. Hits `GET /api/users/{wallet_address}/order-fills` and requires no auth.

Fetch a user's filled orders with nested fill events. Includes orders where the user was either maker or taker. Optionally filter by market. Returns orders sorted by most recent fill first.

### On-Chain Instruction & Transaction Builders

Each operation has an `_ix` method returning an `Instruction` and a `_tx` convenience method returning `Result<Transaction, SdkError>`.

#### `cancel_order_ix` / `cancel_order_tx`

```rust
fn cancel_order_ix(&self, maker: &Pubkey, market: &Pubkey, order: &OrderPayload) -> Instruction
fn cancel_order_tx(&self, maker: &Pubkey, market: &Pubkey, order: &OrderPayload) -> Result<Transaction, SdkError>
```

Build a CancelOrder instruction/transaction for on-chain order cancellation.

#### `increment_nonce_ix` / `increment_nonce_tx`

```rust
fn increment_nonce_ix(&self, user: &Pubkey) -> Instruction
fn increment_nonce_tx(&self, user: &Pubkey) -> Result<Transaction, SdkError>
```

Build an IncrementNonce instruction/transaction — invalidates all orders with a nonce lower than the new value.

#### `close_order_status_ix` / `close_order_status_tx`

```rust
fn close_order_status_ix(&self, params: &CloseOrderStatusParams) -> Instruction
fn close_order_status_tx(&self, params: CloseOrderStatusParams) -> Result<Transaction, SdkError>
```

Build a CloseOrderStatus instruction/transaction — close a fully-filled order status PDA.

### Order Helpers

#### `create_bid_order` / `create_ask_order`

```rust
fn create_bid_order(&self, params: BidOrderParams) -> OrderPayload
fn create_ask_order(&self, params: AskOrderParams) -> OrderPayload
```

Create unsigned bid or ask orders from raw parameters.

#### `create_signed_bid_order` / `create_signed_ask_order`

```rust
fn create_signed_bid_order(&self, params: BidOrderParams, keypair: &Keypair) -> OrderPayload
fn create_signed_ask_order(&self, params: AskOrderParams, keypair: &Keypair) -> OrderPayload
```

Create and sign orders in one step. Requires the `native-auth` feature.

#### `hash_order`

```rust
fn hash_order(&self, order: &OrderPayload) -> [u8; 32]
```

Compute the Keccak256 hash of an order (excludes the signature field).

#### `sign_order`

```rust
fn sign_order(&self, order: &mut OrderPayload, keypair: &Keypair)
```

Sign an order in place with the given keypair. Requires the `native-auth` feature.

## Order Envelope Builder

The SDK provides a fluent builder API for constructing and signing orders. The envelope handles field validation, price/size scaling to raw amounts, and signature generation.

### `LimitOrderEnvelope`

For standard limit orders:

```rust
use lightcone::prelude::*;

// Recommended: factory method pre-seeds client deposit source
let request = client.orders().limit_order().await
    .maker(keypair.pubkey())
    .market(market_pubkey)
    .base_mint(base_mint)
    .quote_mint(quote_mint)
    .bid()                          // or .ask()
    .price("0.55")                  // human-readable price
    .size("100")                    // human-readable size
    .nonce(nonce)
    .expiration(0)                  // 0 = no expiration
    // .deposit_source(DepositSource::Global) // override if needed
    .apply_scaling(&decimals)?      // convert to raw amounts
    .sign(&keypair, orderbook_id)?; // sign and produce SubmitOrderRequest

// Alternative: standalone use without a client
let request = LimitOrderEnvelope::new()
    .maker(keypair.pubkey())
    // ... same chain as above
    .sign(&keypair, orderbook_id)?;
```

### `TriggerOrderEnvelope`

> **Feature-gated** (`trigger_orders`): The types and methods below require the `trigger_orders` Cargo feature, which is disabled by default. Trigger orders are under development and not yet available. For internal use only.

For take-profit and stop-loss orders:

```rust
use lightcone::prelude::*;

// Recommended: factory method pre-seeds client deposit source
let request = client.orders().trigger_order().await
    .maker(keypair.pubkey())
    .market(market_pubkey)
    .base_mint(base_mint)
    .quote_mint(quote_mint)
    .bid()
    .price("0.55")
    .size("100")
    .nonce(nonce)
    .take_profit(0.65)              // or .stop_loss(0.45)
    .gtc()                          // or .ioc(), .fok(), .alo()
    // .deposit_source(DepositSource::Global) // override if needed
    .apply_scaling(&decimals)?
    .sign(&keypair, orderbook_id)?;

// Alternative: standalone use without a client
let request = TriggerOrderEnvelope::new()
    .maker(keypair.pubkey())
    // ... same chain as above
    .sign(&keypair, orderbook_id)?;
```

### `OrderEnvelope` trait

Both envelope types implement the `OrderEnvelope` trait with these shared methods:

| Method | Description |
|--------|-------------|
| `.new()` | Create a new envelope (prefer factory methods) |
| `.maker(pubkey)` | Set the maker public key |
| `.market(pubkey)` | Set the market public key |
| `.base_mint(pubkey)` | Set the base token mint |
| `.quote_mint(pubkey)` | Set the quote token mint |
| `.bid()` / `.ask()` | Set the order side |
| `.price(str)` | Set the human-readable price |
| `.size(str)` | Set the human-readable size |
| `.nonce(u32)` | Set the order nonce. When using `submit()`, auto-populated from `client.order_nonce()` if omitted (falls back to 0). |
| `.expiration(i64)` | Set expiration (0 = none) |
| `.deposit_source(ds)` | Set collateral source (`Global` or `Market`). Pre-seeded by factory methods. |
| `.apply_scaling(&decimals)` | Convert price/size to raw amounts using orderbook decimals |
| `.sign(&keypair, orderbook_id)` | Sign with a keypair and produce `SubmitOrderRequest` |
| `.finalize(sig_bs58, orderbook_id)` | Attach an external signature (for Privy/wallet adapter) |
| `.payload()` | Get the raw `OrderPayload` (for manual signing) |

`TriggerOrderEnvelope` adds:

| Method | Description |
|--------|-------------|
| `.take_profit(price)` | Set trigger type to take-profit at the given price |
| `.stop_loss(price)` | Set trigger type to stop-loss at the given price |
| `.gtc()` / `.ioc()` / `.fok()` / `.alo()` | Set time-in-force |

### Scaling

`apply_scaling()` converts human-readable price and size strings into the raw `amount_in` / `amount_out` values the matching engine expects. You **must** call this before signing. The `DecimalsResponse` from `client.orderbooks().decimals()` provides the required precision.

## State Containers

### `AnyOrder`

Enum wrapping either a `LimitOrder` or `TriggerOrder`. Implements the `Order` trait by delegating to the inner type.

```rust
pub enum AnyOrder {
    Limit(LimitOrder),
    Trigger(TriggerOrder),
}
```

| Method | Description |
|--------|-------------|
| `vec_from(limit_orders, trigger_orders)` | Combine both types into a sorted `Vec<AnyOrder>` |

### `UserOpenLimitOrders`

Tracks a user's open limit orders grouped by market pubkey and orderbook ID. Updated from WebSocket user events.

| Method | Description |
|--------|-------------|
| `new()` | Create empty tracker |
| `get(&market_pubkey, &orderbook_id)` | Get orders for a specific orderbook |
| `get_by_market(&market_pubkey)` | Get orders for a market, grouped by orderbook |
| `upsert(&order_update)` | Insert or update an order from a WS event |
| `remove(order_hash)` | Remove a cancelled/filled order |
| `clear()` | Remove all tracked orders |

### `UserTriggerOrders`

Tracks trigger orders grouped by market pubkey and orderbook ID.

| Method | Description |
|--------|-------------|
| `new()` | Create empty tracker |
| `get(&market_pubkey, &orderbook_id)` | Get trigger orders for a specific orderbook |
| `get_by_market(&market_pubkey)` | Get trigger orders for a market, grouped by orderbook |
| `get_by_id(trigger_order_id)` | Find a specific trigger order |
| `insert(order)` | Add a trigger order |
| `remove(trigger_order_id)` | Remove a trigger order |
| `all()` | Iterator over all trigger orders |
| `len()` / `is_empty()` | Count helpers |

## Examples

### Full order lifecycle

```rust
use lightcone::prelude::*;
use lightcone::auth::native::sign_login_message;
use solana_keypair::Keypair;
use futures_util::StreamExt;

async fn market_make(client: &LightconeClient, keypair: &Keypair) -> Result<(), SdkError> {
    // 1. Authenticate
    let nonce = client.auth().get_nonce().await?;
    let signed = sign_login_message(keypair, &nonce);
    client.auth().login_with_message(
        &signed.message, &signed.signature_bs58, &signed.pubkey_bytes, None,
    ).await?;

    // 2. Find a market and its orderbook
    let market = client.markets().get(None, Some(1)).await?.markets.into_iter().next().unwrap();
    let ob = &market.orderbook_pairs[0];
    let decimals = client.orderbooks().decimals(ob.orderbook_id.as_str()).await?;

    // 3. Place a bid
    let order_nonce = 1u32;
    let bid_request = client.orders().limit_order().await
        .maker(keypair.pubkey())
        .market(market.pubkey.to_pubkey().unwrap())
        .base_mint(ob.base.mint.to_pubkey().unwrap())
        .quote_mint(ob.quote.mint.to_pubkey().unwrap())
        .bid()
        .price("0.50")
        .size("100")
        .nonce(order_nonce)
        .apply_scaling(&decimals)?
        .sign(keypair, ob.orderbook_id.as_str())?;

    let response = client.orders().submit(&bid_request).await?;
    println!("Bid placed: {:?}", response);

    // 4. Monitor via WebSocket
    let mut ws = client.ws_native();
    ws.connect().await.unwrap();
    ws.subscribe(SubscribeParams::User {
        wallet_address: PubkeyStr::from(keypair.pubkey()),
    }).unwrap();

    let mut open_orders = UserOpenLimitOrders::new();
    let mut stream = ws.events();

    while let Some(event) = stream.next().await {
        match event {
            WsEvent::Message(Kind::User(UserUpdate::Order(OrderEvent::Limit(update)))) => {
                open_orders.upsert(&update);
                println!("Order update: {} -> {:?}", update.order.order_hash, update.order.status);
            }
            _ => {}
        }
    }

    // 5. Cancel all orders
    client.orders().cancel_all(&CancelAllBody {
        user_pubkey: keypair.pubkey().into(),
        orderbook_id: OrderBookId::from(""),
        signature: "...".into(),
        timestamp: 1_710_300_000,
        salt: generate_cancel_all_salt(),
    }).await?;

    Ok(())
}
```

### Place a take-profit trigger order

```rust
use lightcone::prelude::*;

async fn place_take_profit(
    client: &LightconeClient,
    keypair: &solana_keypair::Keypair,
    ob: &OrderBookPair,
    decimals: &impl lightcone::shared::scaling::OrderbookDecimals,
) -> Result<(), SdkError> {
    let request = client.orders().trigger_order().await
        .maker(keypair.pubkey())
        .market(ob.market_pubkey.to_pubkey().unwrap())
        .base_mint(ob.base.mint.to_pubkey().unwrap())
        .quote_mint(ob.quote.mint.to_pubkey().unwrap())
        .ask()
        .price("0.70")
        .size("50")
        .nonce(2)
        .take_profit(0.65)
        .gtc()
        .apply_scaling(decimals)?
        .sign(keypair, ob.orderbook_id.as_str())?;

    let response = client.orders().submit_trigger(&request).await?;
    println!("Trigger order placed: {:?}", response);
    Ok(())
}
```

### Fetch filled orders with pagination

```rust
use lightcone::prelude::*;

async fn show_fill_history(
    client: &LightconeClient,
    market_pubkey: &str,
) -> Result<(), SdkError> {
    // Authenticated user — wallet from JWT cookie. (For a public lookup of
    // another wallet, use `get_user_order_fills_by_wallet(wallet, ...)`.)
    let response = client.orders().get_user_order_fills(
        Some(market_pubkey),
        Some(20),
        None,
    ).await?;

    for order in &response.orders {
        println!("{} {} ({:?}) @ {} — {}/{} filled",
            order.side, order.role, order.status,
            order.price, order.filled_size, order.size);
        for fill in &order.fills {
            println!("  fill: {} at {}", fill.fill_amount, fill.filled_at);
        }
    }

    // Paginate
    if response.has_more {
        let next_page = client.orders().get_user_order_fills(
            Some(market_pubkey),
            Some(20),
            response.next_cursor.as_deref(),
        ).await?;
    }

    Ok(())
}
```

## Wire Types

Raw types in `lightcone::domain::order::wire` include `OrderUpdate`, `UserUpdate`, `UserSnapshot`, `UserSnapshotOrder`, `TriggerOrderUpdate`, `OrderEvent`, `ConditionalBalance`, `GlobalDepositBalance`, `AuthUpdate`, `UserOrderFillsResponse`, `UserOrderFill`, `OrderFillEvent`, and `Role`. These are the WebSocket and REST wire formats before domain conversion.

---

[← Overview](../../../README.md#orders)