gmsol-solana-utils 0.10.0

GMX-Solana is an extension of GMX on the Solana blockchain.
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
#![allow(clippy::result_large_err)]

#[cfg(all(feature = "jito", client))]
use futures_util::stream::{self, StreamExt};

#[cfg(feature = "jito")]
use solana_sdk::{
    hash::Hash, message::VersionedMessage, signer::Signer, transaction::VersionedTransaction,
};

#[cfg(all(feature = "jito", client))]
use base64::Engine;

#[cfg(feature = "jito")]
use crate::{
    instruction_group::ComputeBudgetOptions, transaction_builder::default_before_sign,
    transaction_group::TransactionGroup,
};

#[cfg(feature = "jito")]
/// Packing strategy for Jito bundles.
#[derive(Debug, Clone)]
pub enum BundleMode {
    /// One transaction per bundle.
    SingleTx,
    /// Pack multiple transactions into the same bundle within a single ParallelGroup,
    /// respecting `is_mergeable` flags and `max_txs_per_bundle`.
    PackWithinPG {
        /// Maximum number of transactions per bundle.
        max_txs_per_bundle: usize,
    },
    /// Pack across adjacent mergeable ParallelGroups, as long as all AGs are mergeable
    /// and the total count per bundle does not exceed the limit.
    PackAcrossMergeablePGs {
        /// Maximum number of transactions per bundle.
        max_txs_per_bundle: usize,
    },
}

#[cfg(feature = "jito")]
impl Default for BundleMode {
    fn default() -> Self {
        // Prefer packing as much as possible while respecting AG/PG mergeable semantics.
        Self::PackAcrossMergeablePGs {
            max_txs_per_bundle: 5,
        }
    }
}

#[cfg(feature = "jito")]
/// Options for sending Jito bundles.
#[derive(Debug, Clone, Default)]
pub struct JitoSendOptions {
    /// Whether to omit injecting compute budget instructions.
    pub without_compute_budget: bool,
    /// Compute unit price in micro-lamports.
    pub compute_unit_price_micro_lamports: Option<u64>,
    /// Minimum priority fee in lamports.
    pub compute_unit_min_priority_lamports: Option<u64>,
    /// Whether to continue submitting bundles within a batch when an error occurs.
    pub continue_on_error: bool,
    /// Jito Block Engine base url, e.g. https://ny.mainnet.block-engine.jito.wtf
    pub endpoint_url: String,
    /// Optional UUID query param attached by SDK (see scripts/jito-rust-rpc-master/src/lib.rs)
    pub uuid: Option<String>,
    /// Bundle packing strategy.
    pub bundle_mode: BundleMode,
    /// Optional concurrency for bundle submissions. If `None`, submissions are sequential.
    pub parallelism: Option<usize>,
}

#[cfg(feature = "jito")]
/// A Jito sending group built on `TransactionGroup` that encodes parallel/serial bundle topology.
#[derive(Debug, Clone)]
pub struct JitoGroup {
    inner: TransactionGroup,
}

#[cfg(feature = "jito")]
impl From<TransactionGroup> for JitoGroup {
    fn from(inner: TransactionGroup) -> Self {
        Self { inner }
    }
}

#[cfg(all(feature = "jito", feature = "client"))]
impl<'a, C> From<crate::bundle_builder::Bundle<'a, C>> for JitoGroup
where
    C: std::ops::Deref + Clone,
    C::Target: Signer + Sized,
{
    fn from(bundle: crate::bundle_builder::Bundle<'a, C>) -> Self {
        Self {
            inner: bundle.into_group(),
        }
    }
}

#[cfg(all(feature = "jito", client))]
impl JitoGroup {
    /// Returns the inner `TransactionGroup`.
    pub fn into_inner(self) -> TransactionGroup {
        self.inner
    }

    /// Sends bundles according to the `TransactionGroup` parallel/serial semantics,
    /// mapping each transaction to a single-transaction bundle and submitting to the Jito endpoint.
    ///
    /// - Batches are processed sequentially; transactions within a batch are submitted concurrently.
    /// - Returns bundle ids (or raw JSON text) for successful submissions.
    pub async fn send_with_options(
        &self,
        signers: &crate::signer::TransactionSigners<impl std::ops::Deref<Target = dyn Signer>>,
        recent_blockhash: Hash,
        opts: JitoSendOptions,
    ) -> Result<Vec<String>, (Vec<String>, crate::Error)> {
        // Delegate to detailed API and aggregate per legacy signature.
        let cont = opts.continue_on_error;
        let detailed = self
            .send_detailed_with_options(signers, recent_blockhash, opts)
            .await;
        let mut ok_ids: Vec<String> = Vec::new();
        let mut errs: Vec<crate::Error> = Vec::new();
        for res in detailed {
            match res {
                Ok(id) => ok_ids.push(id),
                Err(err) => errs.push(err),
            }
        }
        if errs.is_empty() {
            return Ok(ok_ids);
        }
        // If only one error and not continuing, return first error with partial ids for backward compatibility.
        if !cont && errs.len() == 1 {
            return Err((ok_ids, errs.into_iter().next().unwrap()));
        }
        // Aggregate all errors into a single custom message.
        let preview = errs
            .iter()
            .map(|e| e.to_string())
            .take(3)
            .collect::<Vec<_>>()
            .join(" | ");
        let msg = if errs.len() <= 3 {
            format!("{} bundle(s) failed: {}", errs.len(), preview)
        } else {
            format!("{} bundle(s) failed: {} ...", errs.len(), preview)
        };
        Err((ok_ids, crate::Error::custom(msg)))
    }

    /// Submit bundles and return per-bundle results in order.
    pub async fn send_detailed_with_options(
        &self,
        signers: &crate::signer::TransactionSigners<impl std::ops::Deref<Target = dyn Signer>>,
        recent_blockhash: Hash,
        opts: JitoSendOptions,
    ) -> Vec<Result<String, crate::Error>> {
        let plan = match self
            .build_bundle_plan_staged(signers, recent_blockhash, &opts)
            .await
        {
            Ok(p) => p,
            Err(e) => return vec![Err(e)],
        };

        self.submit_bundles_staged(
            &plan,
            &opts.endpoint_url,
            opts.uuid.as_deref(),
            opts.parallelism,
        )
        .await
    }
}

#[cfg(feature = "jito")]
impl JitoGroup {
    /// Build a staged bundle plan from the underlying TransactionGroup according to the bundle_mode.
    /// Staged plan expresses serial stages -> parallel bundles per stage -> transactions per bundle (<=5).
    pub async fn build_bundle_plan_staged(
        &self,
        signers: &crate::signer::TransactionSigners<impl std::ops::Deref<Target = dyn Signer>>,
        recent_blockhash: Hash,
        opts: &JitoSendOptions,
    ) -> crate::Result<Vec<Vec<Vec<VersionedTransaction>>>> {
        let compute_budget = ComputeBudgetOptions {
            without_compute_budget: opts.without_compute_budget,
            compute_unit_price_micro_lamports: opts.compute_unit_price_micro_lamports,
            compute_unit_min_priority_lamports: opts.compute_unit_min_priority_lamports,
        };

        let batches = self
            .inner
            .to_transactions_with_options(
                signers,
                recent_blockhash,
                false,
                compute_budget,
                default_before_sign as fn(&VersionedMessage) -> crate::Result<()>,
            )
            .collect::<crate::Result<Vec<_>>>()?;

        let pgs = self.inner.groups();
        if pgs.len() != batches.len() {
            return Err(crate::Error::custom("mismatched PG and batch lengths"));
        }

        struct PgTx {
            pg_mergeable: bool,
            ag_mergeable: Vec<bool>,
            txns: Vec<VersionedTransaction>,
        }

        let mut pg_txs: Vec<PgTx> = Vec::with_capacity(batches.len());
        for (pg, txs) in pgs.iter().zip(batches.into_iter()) {
            let ag_flags: Vec<bool> = pg.iter().map(|ag| ag.is_mergeable()).collect();
            if ag_flags.len() != txs.len() {
                return Err(crate::Error::custom("mismatched AG and tx counts in PG"));
            }
            pg_txs.push(PgTx {
                pg_mergeable: pg.is_mergeable(),
                ag_mergeable: ag_flags,
                txns: txs,
            });
        }

        let max_default = 5usize;
        let mut staged: Vec<Vec<Vec<VersionedTransaction>>> = Vec::new();

        match opts.bundle_mode.clone() {
            BundleMode::SingleTx => {
                for p in pg_txs.into_iter() {
                    let mut stage: Vec<Vec<VersionedTransaction>> = Vec::new();
                    for tx in p.txns.into_iter() {
                        stage.push(vec![tx]);
                    }
                    staged.push(stage);
                }
            }
            BundleMode::PackWithinPG { max_txs_per_bundle } => {
                let limit = if max_txs_per_bundle == 0 {
                    max_default
                } else {
                    max_txs_per_bundle
                };
                for mut p in pg_txs.into_iter() {
                    let mut stage: Vec<Vec<VersionedTransaction>> = Vec::new();
                    let mut cur: Vec<VersionedTransaction> = Vec::new();
                    for (tx, ag_ok) in p.txns.drain(..).zip(p.ag_mergeable.into_iter()) {
                        if ag_ok {
                            cur.push(tx);
                            if cur.len() >= limit {
                                stage.push(std::mem::take(&mut cur));
                            }
                        } else {
                            if !cur.is_empty() {
                                stage.push(std::mem::take(&mut cur));
                            }
                            stage.push(vec![tx]);
                        }
                    }
                    if !cur.is_empty() {
                        stage.push(cur);
                    }
                    staged.push(stage);
                }
            }
            BundleMode::PackAcrossMergeablePGs { max_txs_per_bundle } => {
                let limit = if max_txs_per_bundle == 0 {
                    max_default
                } else {
                    max_txs_per_bundle
                };
                let mut cur_stage: Vec<Vec<VersionedTransaction>> = Vec::new();
                for mut p in pg_txs.into_iter() {
                    if !p.pg_mergeable {
                        if !cur_stage.is_empty() {
                            staged.push(std::mem::take(&mut cur_stage));
                        }
                        let mut stage: Vec<Vec<VersionedTransaction>> = Vec::new();
                        let mut cur: Vec<VersionedTransaction> = Vec::new();
                        for (tx, ag_ok) in p.txns.drain(..).zip(p.ag_mergeable.into_iter()) {
                            if ag_ok {
                                cur.push(tx);
                                if cur.len() >= limit {
                                    stage.push(std::mem::take(&mut cur));
                                }
                            } else {
                                if !cur.is_empty() {
                                    stage.push(std::mem::take(&mut cur));
                                }
                                stage.push(vec![tx]);
                            }
                        }
                        if !cur.is_empty() {
                            stage.push(cur);
                        }
                        staged.push(stage);
                        continue;
                    }

                    let can_merge_into_current_stage = if cur_stage.len() == 1 {
                        cur_stage[0].len() < limit
                    } else {
                        false
                    };

                    if !can_merge_into_current_stage && !cur_stage.is_empty() {
                        staged.push(std::mem::take(&mut cur_stage));
                    }

                    let mut bundles: Vec<Vec<VersionedTransaction>> = Vec::new();
                    let mut cur: Vec<VersionedTransaction> = if can_merge_into_current_stage {
                        std::mem::take(&mut cur_stage[0])
                    } else {
                        Vec::new()
                    };

                    for (tx, ag_ok) in p.txns.drain(..).zip(p.ag_mergeable.into_iter()) {
                        if ag_ok {
                            cur.push(tx);
                            if cur.len() >= limit {
                                bundles.push(std::mem::take(&mut cur));
                            }
                        } else {
                            if !cur.is_empty() {
                                bundles.push(std::mem::take(&mut cur));
                            }
                            bundles.push(vec![tx]);
                        }
                    }

                    if !cur.is_empty() {
                        bundles.push(cur);
                    }

                    cur_stage = bundles;
                }
                if !cur_stage.is_empty() {
                    staged.push(cur_stage);
                }
            }
        }

        Ok(staged)
    }
}

#[cfg(all(feature = "jito", client))]
fn encode_txn_base64(txn: &VersionedTransaction) -> crate::Result<String> {
    let bytes = bincode::serialize(txn).map_err(|e| crate::Error::custom(e.to_string()))?;
    Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
}

#[cfg(all(feature = "jito", client))]
impl JitoGroup {
    /// Submit a bundle plan (flat list) to the Jito endpoint.
    /// By default, submissions are sequential; if `parallelism` is `Some(n)` and `n > 1`,
    /// bounded concurrency is used while preserving result order.
    pub(crate) async fn submit_bundles(
        &self,
        plan: &[Vec<VersionedTransaction>],
        endpoint_url: &str,
        uuid: Option<&str>,
        parallelism: Option<usize>,
    ) -> Vec<Result<String, crate::Error>> {
        if plan.is_empty() {
            return Vec::new();
        }

        let limit = parallelism.unwrap_or(1);
        if limit <= 1 {
            // Sequential path
            let mut results = Vec::with_capacity(plan.len());
            for bundle in plan.iter() {
                let mut tx_strings = Vec::with_capacity(bundle.len());
                for tx in bundle.iter() {
                    match encode_txn_base64(tx) {
                        Ok(s) => tx_strings.push(serde_json::Value::String(s)),
                        Err(e) => {
                            results.push(Err(e));
                            continue;
                        }
                    }
                }
                if tx_strings.is_empty() {
                    results.push(Err(crate::Error::custom("empty bundle after encoding")));
                    continue;
                }
                let params = serde_json::Value::Array(tx_strings);
                let res =
                    jito_sdk_rust::JitoJsonRpcSDK::new(endpoint_url, uuid.map(|s| s.to_string()))
                        .send_bundle(Some(params), uuid)
                        .await
                        .map_err(|e| crate::Error::custom(e.to_string()))
                        .map(|value| {
                            value
                                .get("result")
                                .and_then(|v| v.as_str())
                                .map(|s| s.to_string())
                                .unwrap_or_else(|| value.to_string())
                        });
                results.push(res);
            }
            return results;
        }

        // Concurrent path with ordered aggregation
        let total = plan.len();
        let jobs: Vec<(usize, Vec<VersionedTransaction>)> =
            plan.iter().cloned().enumerate().collect();

        let mut ordered: Vec<Option<Result<String, crate::Error>>> =
            (0..total).map(|_| None).collect();
        let mut s = stream::iter(jobs.into_iter().map(|(idx, bundle)| {
            let endpoint_url = endpoint_url.to_string();
            let uuid = uuid.map(|s| s.to_string());
            async move {
                let mut tx_strings = Vec::with_capacity(bundle.len());
                for tx in bundle.into_iter() {
                    match encode_txn_base64(&tx) {
                        Ok(s) => tx_strings.push(serde_json::Value::String(s)),
                        Err(e) => return (idx, Err(e)),
                    }
                }
                if tx_strings.is_empty() {
                    return (
                        idx,
                        Err(crate::Error::custom("empty bundle after encoding")),
                    );
                }
                let params = serde_json::Value::Array(tx_strings);
                let uuid_ref = uuid.as_deref();
                let uuid_for_new = uuid.clone();
                let res = jito_sdk_rust::JitoJsonRpcSDK::new(&endpoint_url, uuid_for_new)
                    .send_bundle(Some(params), uuid_ref)
                    .await
                    .map_err(|e| crate::Error::custom(e.to_string()))
                    .map(|value| {
                        value
                            .get("result")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string())
                            .unwrap_or_else(|| value.to_string())
                    });
                (idx, res)
            }
        }))
        .buffer_unordered(limit);

        while let Some((idx, res)) = s.next().await {
            ordered[idx] = Some(res);
        }

        ordered.into_iter().map(|x| x.unwrap()).collect()
    }
}

#[cfg(all(feature = "jito", client))]
impl JitoGroup {
    /// Submit a staged bundle plan to the Jito endpoint.
    /// Advances stages sequentially; inside each stage, bundles are sent with optional bounded concurrency.
    pub async fn submit_bundles_staged(
        &self,
        staged: &[Vec<Vec<VersionedTransaction>>],
        endpoint_url: &str,
        uuid: Option<&str>,
        per_stage_parallelism: Option<usize>,
    ) -> Vec<Result<String, crate::Error>> {
        let mut all = Vec::new();
        for bundles in staged.iter() {
            let part = self
                .submit_bundles(bundles, endpoint_url, uuid, per_stage_parallelism)
                .await;
            all.extend(part);
        }
        all
    }
}