cosmic-cinder 0.1.10

Rust terminal UI for Phoenix perpetuals on Solana
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
//! Order cancellation — batches `CancelOrdersById` instructions per market
//! and stop-loss cancels per asset, staggering submission so a stack of
//! cancels lands without exceeding the per-tx instruction limit.

use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

use solana_keypair::Keypair;

use super::super::i18n::strings;
use super::super::state::TxStatusMsg;
use super::compute_budget::build_compute_budget_ixs;
use super::confirmation::{compile_and_sign, subscribe_send_confirm, ConfirmError};
use super::context::TxContext;
use super::error::{
    format_not_confirmed_error, log_tx_error, not_confirmed_is_onchain_execution_failure,
    parse_phoenix_tx_error,
};

/// One open order to cancel — the (`price_ticks`, `order_sequence_number`) pair
/// is the on-chain `CancelId`, `symbol` selects which market's IX it lives in.
///
/// When `is_stop_loss` is true, price_ticks/order_sequence_number are
/// ignored; the entry is routed through `cancel_stop_loss` instead and the
/// trigger is keyed by the market's `asset_id` + `stop_direction`.
pub struct CancelOrderEntry {
    pub symbol: String,
    pub subaccount_index: u8,
    pub price_ticks: u64,
    pub order_sequence_number: u64,
    pub is_stop_loss: bool,
    pub stop_direction: Option<phoenix_rise::Direction>,
    pub conditional_order_index: Option<u8>,
    pub conditional_trigger_direction: Option<phoenix_rise::Direction>,
}

/// One IX per symbol fits at most this many orders; mirrors
/// `MAX_CANCEL_ORDER_IDS` in `phoenix_rise::ix::cancel_orders`. We chunk per-symbol
/// orders into runs of this size.
const MAX_CANCELS_PER_IX: usize = 100;
/// Bundle this many cancel-orders IXs into a single transaction. Mirrors
/// `CLOSE_BATCH_SIZE` for closes; cancels touch the same write-set shape
/// (orderbook + spline collection + trader buffers), so the same conservative
/// budget applies.
const CANCEL_BATCH_SIZE: usize = 5;
const CANCEL_BATCH_STAGGER: Duration = Duration::from_millis(500);

/// Builds and submits cancel-orders transactions for `entries`. Orders are
/// grouped by symbol (one IX per symbol, capped at `MAX_CANCELS_PER_IX`), then
/// those IXs are batched into transactions of `CANCEL_BATCH_SIZE`.
/// `summary` is a short label for the status line, e.g. "1 order on SOL" or "3
/// order(s)".
pub fn submit_cancel_orders(
    keypair: Arc<Keypair>,
    ctx: Arc<TxContext>,
    entries: Vec<CancelOrderEntry>,
    summary: String,
    tx_status: tokio::sync::mpsc::UnboundedSender<TxStatusMsg>,
) {
    tokio::spawn(async move {
        use phoenix_rise::ix::{
            create_cancel_conditional_order_ix, create_cancel_orders_by_id_ix,
            create_cancel_stop_loss_ix, CancelConditionalOrderParams, CancelOrdersByIdParams,
            CancelStopLossParams,
        };
        use phoenix_rise::CancelId;

        let s = strings();

        if entries.is_empty() {
            let _ = tx_status.send(TxStatusMsg::SetStatus {
                title: s.st_no_orders.to_string(),
                detail: String::new(),
            });
            return;
        }

        let _ = tx_status.send(TxStatusMsg::SetStatus {
            title: format!("{} {}", s.tx_building_cancel, summary),
            detail: String::new(),
        });

        // Split conditional rows first: position conditional orders live in the
        // trader conditional-orders account and cancel by account index +
        // trigger direction. Legacy stop-loss rows still route through
        // `cancel_stop_loss`; plain limits batch through `cancel_orders_by_id`.
        let (conditional_entries, remaining_entries): (Vec<_>, Vec<_>) = entries
            .into_iter()
            .partition(|e| e.conditional_order_index.is_some());
        let (stop_entries, limit_entries): (Vec<_>, Vec<_>) =
            remaining_entries.into_iter().partition(|e| e.is_stop_loss);

        // Group limit cancels by symbol: each symbol becomes (at most ceil(n/100))
        // cancel-orders IXs.
        let mut by_symbol: std::collections::BTreeMap<(String, u8), Vec<CancelId>> =
            std::collections::BTreeMap::new();
        for e in limit_entries.into_iter() {
            by_symbol
                .entry((e.symbol, e.subaccount_index))
                .or_default()
                .push(CancelId::new(e.price_ticks, e.order_sequence_number));
        }

        let mut all_ixs: Vec<(solana_instruction::Instruction, String)> = Vec::new();

        for e in conditional_entries.into_iter() {
            let Some(order_index) = e.conditional_order_index else {
                continue;
            };
            let Some(direction) = e.conditional_trigger_direction else {
                continue;
            };
            let Some(market) = ctx.metadata.get_market(&e.symbol) else {
                let _ = tx_status.send(TxStatusMsg::SetStatus {
                    title: format!(
                        "Build error (cancel conditional {}): unknown market",
                        e.symbol
                    ),
                    detail: String::new(),
                });
                continue;
            };
            let orderbook = match solana_pubkey::Pubkey::from_str(&market.market_pubkey) {
                Ok(pk) => pk,
                Err(err) => {
                    let _ = tx_status.send(TxStatusMsg::SetStatus {
                        title: format!("Build error (cancel conditional {}): {}", e.symbol, err),
                        detail: String::new(),
                    });
                    continue;
                }
            };
            let trader_account = ctx.trader_pda_for_subaccount(e.subaccount_index);
            let params = match CancelConditionalOrderParams::builder()
                .trader_account(trader_account)
                .position_authority(ctx.authority_v2)
                .orderbook(orderbook)
                .conditional_order_index(order_index)
                .disable_first(matches!(direction, phoenix_rise::Direction::GreaterThan))
                .disable_second(matches!(direction, phoenix_rise::Direction::LessThan))
                .build()
            {
                Ok(p) => p,
                Err(err) => {
                    let _ = tx_status.send(TxStatusMsg::SetStatus {
                        title: format!("Build error (cancel conditional {}): {}", e.symbol, err),
                        detail: String::new(),
                    });
                    continue;
                }
            };
            let ix: solana_instruction::Instruction =
                match create_cancel_conditional_order_ix(params) {
                    Ok(i) => i.into(),
                    Err(err) => {
                        let _ = tx_status.send(TxStatusMsg::SetStatus {
                            title: format!(
                                "IX build error (cancel conditional {}): {}",
                                e.symbol, err
                            ),
                            detail: String::new(),
                        });
                        continue;
                    }
                };
            all_ixs.push((ix, format!("{} {} STP", s.tx_cancel_label, e.symbol)));
        }

        // One `cancel_stop_loss` IX per (symbol, direction). Pending stops are
        // keyed on the (trader_account, asset_id, direction) triple so we never
        // need more than two per symbol (LessThan + GreaterThan).
        for e in stop_entries.into_iter() {
            let Some(direction) = e.stop_direction else {
                continue;
            };
            let Some(market) = ctx.metadata.get_market(&e.symbol) else {
                let _ = tx_status.send(TxStatusMsg::SetStatus {
                    title: format!("Build error (cancel stop {}): unknown market", e.symbol),
                    detail: String::new(),
                });
                continue;
            };
            let asset_id = market.asset_id as u64;
            let params = match CancelStopLossParams::builder()
                .funder(ctx.authority_v2)
                .trader_account(ctx.trader_pda_for_subaccount(e.subaccount_index))
                .position_authority(ctx.authority_v2)
                .asset_id(asset_id)
                .execution_direction(direction)
                .build()
            {
                Ok(p) => p,
                Err(err) => {
                    let _ = tx_status.send(TxStatusMsg::SetStatus {
                        title: format!("Build error (cancel stop {}): {}", e.symbol, err),
                        detail: String::new(),
                    });
                    continue;
                }
            };
            let ix: solana_instruction::Instruction = match create_cancel_stop_loss_ix(params) {
                Ok(i) => i.into(),
                Err(err) => {
                    let _ = tx_status.send(TxStatusMsg::SetStatus {
                        title: format!("IX build error (cancel stop {}): {}", e.symbol, err),
                        detail: String::new(),
                    });
                    continue;
                }
            };
            let mapped = vec![ix];
            let label = format!("{} {} STP", s.tx_cancel_label, e.symbol);
            for ix in mapped {
                all_ixs.push((ix, label.clone()));
            }
        }

        for ((symbol, subaccount_index), cancel_ids) in by_symbol.into_iter() {
            for chunk in cancel_ids.chunks(MAX_CANCELS_PER_IX) {
                let Some(addrs) = ctx.market_addrs_for_symbol(&symbol) else {
                    let _ = tx_status.send(TxStatusMsg::SetStatus {
                        title: format!("Build error (cancel {}): unknown market", symbol),
                        detail: String::new(),
                    });
                    continue;
                };
                let trader_account = ctx.trader_pda_for_subaccount(subaccount_index);
                let params = match CancelOrdersByIdParams::builder()
                    .trader(ctx.authority_v2)
                    .trader_account(trader_account)
                    .perp_asset_map(addrs.perp_asset_map)
                    .orderbook(addrs.orderbook)
                    .spline_collection(addrs.spline_collection)
                    .global_trader_index(addrs.global_trader_index)
                    .active_trader_buffer(addrs.active_trader_buffer)
                    .order_ids(chunk.to_vec())
                    .build()
                {
                    Ok(params) => params,
                    Err(e) => {
                        let _ = tx_status.send(TxStatusMsg::SetStatus {
                            title: format!("Build error (cancel {}): {}", symbol, e),
                            detail: String::new(),
                        });
                        continue;
                    }
                };
                let ix: solana_instruction::Instruction =
                    match create_cancel_orders_by_id_ix(params) {
                        Ok(ix) => ix.into(),
                        Err(e) => {
                            let _ = tx_status.send(TxStatusMsg::SetStatus {
                                title: format!("IX build error (cancel {}): {}", symbol, e),
                                detail: String::new(),
                            });
                            continue;
                        }
                    };
                let label = format!("{} {}×{}", s.tx_cancel_label, symbol, chunk.len());
                all_ixs.push((ix, label));
            }
        }

        if all_ixs.is_empty() {
            let _ = tx_status.send(TxStatusMsg::SetStatus {
                title: s.tx_cancel_aborted.to_string(),
                detail: String::new(),
            });
            return;
        }

        let batches: Vec<Vec<(solana_instruction::Instruction, String)>> = all_ixs
            .chunks(CANCEL_BATCH_SIZE)
            .map(|c| c.to_vec())
            .collect();

        let num_batches = batches.len();
        let mut last_sig = String::new();
        for (batch_idx, batch) in batches.into_iter().enumerate() {
            let labels: Vec<String> = {
                let mut seen = std::collections::HashSet::new();
                batch
                    .iter()
                    .filter_map(|(_, lbl)| {
                        if seen.insert(lbl.clone()) {
                            Some(lbl.clone())
                        } else {
                            None
                        }
                    })
                    .collect()
            };
            let batch_label = labels.join(", ");

            let mut ixs: Vec<solana_instruction::Instruction> =
                batch.into_iter().map(|(ix, _)| ix).collect();
            // One cancel-orders IX per item in the batch — scale CU the same way as closes.
            let ops_in_batch = ixs.len().max(1) as u32;
            ixs.extend(build_compute_budget_ixs(ops_in_batch));

            let _ = tx_status.send(TxStatusMsg::SetStatus {
                title: format!(
                    "{} {}/{}: {}",
                    s.tx_broadcasting_cancel_batch,
                    batch_idx + 1,
                    num_batches,
                    batch_label
                ),
                detail: String::new(),
            });

            let (tx, sig) = match compile_and_sign(&ctx, &keypair, &ixs).await {
                Ok(pair) => pair,
                Err(e) => {
                    let _ = tx_status.send(TxStatusMsg::SetStatus {
                        title: format!(
                            "{} {}/{}",
                            s.tx_failed_prepare_cancel_batch,
                            batch_idx + 1,
                            num_batches
                        ),
                        detail: e,
                    });
                    break;
                }
            };
            let sig_str = sig.to_string();
            last_sig = sig_str.clone();
            let _ = tx_status.send(TxStatusMsg::SetStatus {
                title: format!(
                    "{} {}/{}: {}",
                    s.tx_confirming_cancel_batch,
                    batch_idx + 1,
                    num_batches,
                    batch_label
                ),
                detail: sig_str.clone(),
            });

            match subscribe_send_confirm(&ctx, &tx, &sig).await {
                Ok(()) => {
                    let _ = tx_status.send(TxStatusMsg::SetStatus {
                        title: format!(
                            "{} {}/{} {} {}",
                            s.tx_cancel_batch,
                            batch_idx + 1,
                            num_batches,
                            s.tx_batch_confirmed_suf,
                            batch_label
                        ),
                        detail: sig_str,
                    });
                }
                Err(ConfirmError::Rejected(e)) => {
                    log_tx_error(
                        None,
                        &format!("cancel batch {}/{} rejected", batch_idx + 1, num_batches),
                        &e,
                    );
                    let _ = tx_status.send(TxStatusMsg::SetStatus {
                        title: format!(
                            "{} {}/{} {}",
                            s.tx_cancel_batch,
                            batch_idx + 1,
                            num_batches,
                            s.tx_batch_rejected_suf
                        ),
                        detail: parse_phoenix_tx_error(&e),
                    });
                }
                Err(ConfirmError::NotConfirmed(e)) => {
                    log_tx_error(
                        Some(&sig_str),
                        &format!(
                            "cancel batch {}/{} not confirmed",
                            batch_idx + 1,
                            num_batches
                        ),
                        &e,
                    );
                    let onchain_fail = not_confirmed_is_onchain_execution_failure(&e);
                    let mapped = format_not_confirmed_error(&e);
                    let (title, detail) = if onchain_fail {
                        (
                            format!(
                                "{} {}/{} {}",
                                s.tx_cancel_batch,
                                batch_idx + 1,
                                num_batches,
                                s.tx_batch_exec_failed_suf
                            ),
                            parse_phoenix_tx_error(&e),
                        )
                    } else {
                        (
                            format!(
                                "{} {}/{} {} ({})",
                                s.tx_cancel_batch,
                                batch_idx + 1,
                                num_batches,
                                s.tx_batch_not_confirmed_suf,
                                mapped
                            ),
                            sig_str,
                        )
                    };
                    let _ = tx_status.send(TxStatusMsg::SetStatus { title, detail });
                }
            }

            if batch_idx + 1 < num_batches {
                tokio::time::sleep(CANCEL_BATCH_STAGGER).await;
            }
        }

        let _ = tx_status.send(TxStatusMsg::SetStatus {
            title: format!("{} ({})", s.tx_cancel_complete, summary),
            detail: last_sig,
        });
    });
}