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
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
use std::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet, HashSet},
    ops::Deref,
};

use smallvec::SmallVec;
use solana_sdk::{
    hash::Hash,
    instruction::Instruction,
    message::{v0, VersionedMessage},
    pubkey::Pubkey,
    signature::NullSigner,
    signer::Signer,
    transaction::VersionedTransaction,
};

use crate::{
    address_lookup_table::AddressLookupTables, compute_budget::ComputeBudget,
    signer::BoxClonableSigner, transaction_group::TransactionGroupOptions,
};

const ATOMIC_SIZE: usize = 3;
const PARALLEL_SIZE: usize = 2;

/// A trait representing types that can be converted into [`AtomicGroup`]s.
pub trait IntoAtomicGroup {
    /// Hint.
    type Hint;

    /// Convert into an [`AtomicGroup`].
    fn into_atomic_group(self, hint: &Self::Hint) -> crate::Result<AtomicGroup>;

    /// Convert into an [`AtomicGroup`] with RPC client.
    #[cfg(client_traits)]
    fn into_atomic_group_with_rpc_client(
        self,
        client: &impl crate::client_traits::RpcClient,
    ) -> impl std::future::Future<Output = crate::Result<AtomicGroup>>
    where
        Self: Sized,
        Self::Hint: crate::client_traits::FromRpcClientWith<Self>,
    {
        use crate::client_traits::FromRpcClientWith;

        async move {
            let hint = Self::Hint::from_rpc_client_with(&self, client).await?;
            self.into_atomic_group(&hint)
        }
    }
}

/// Options for getting instructions.
#[derive(Debug, Clone, Default)]
pub struct GetInstructionsOptions {
    /// Options for compute budget.
    pub compute_budget: ComputeBudgetOptions,
    /// If set, a memo will be included in the final transaction.
    pub memo: Option<String>,
    /// If set, the signer list for the memo instruction will be replaced.
    pub memo_signers: Option<Vec<Pubkey>>,
    /// Extra compute units.
    pub extra_compute_units: u32,
}

/// Options for compute budget.
#[derive(Debug, Clone, Default)]
pub struct ComputeBudgetOptions {
    /// Without compute budget instruction.
    pub without_compute_budget: bool,
    /// Compute unit price in micro lamports.
    pub compute_unit_price_micro_lamports: Option<u64>,
    /// Compute unit min priority lamports.
    pub compute_unit_min_priority_lamports: Option<u64>,
}

/// Options type for [`AtomicGroup`].
#[derive(Debug, Clone)]
pub struct AtomicGroupOptions {
    /// Indicates whether the group is mergeable.
    pub is_mergeable: bool,
}

impl Default for AtomicGroupOptions {
    fn default() -> Self {
        Self { is_mergeable: true }
    }
}

/// A group of instructions that are expected to be executed in the same transaction.
#[derive(Debug, Clone)]
pub struct AtomicGroup {
    payer: Pubkey,
    signers: BTreeMap<Pubkey, NullSigner>,
    owned_signers: BTreeMap<Pubkey, BoxClonableSigner<'static>>,
    instructions: SmallVec<[Instruction; ATOMIC_SIZE]>,
    compute_budget: ComputeBudget,
    options: AtomicGroupOptions,
}

impl AtomicGroup {
    /// Returns whether the atomic group is mergeable.
    pub fn is_mergeable(&self) -> bool {
        self.options().is_mergeable
    }

    /// Returns the options of the group.
    pub fn options(&self) -> &AtomicGroupOptions {
        &self.options
    }

    /// Create from an iterator of instructions and options.
    pub fn with_instructions_and_options(
        payer: &Pubkey,
        instructions: impl IntoIterator<Item = Instruction>,
        options: AtomicGroupOptions,
    ) -> Self {
        Self {
            payer: *payer,
            signers: BTreeMap::from([(*payer, NullSigner::new(payer))]),
            owned_signers: Default::default(),
            instructions: SmallVec::from_iter(instructions),
            compute_budget: Default::default(),
            options,
        }
    }

    /// Create from an iterator of instructions.
    pub fn with_instructions(
        payer: &Pubkey,
        instructions: impl IntoIterator<Item = Instruction>,
    ) -> Self {
        Self::with_instructions_and_options(payer, instructions, Default::default())
    }

    /// Create a new empty group.
    pub fn new(payer: &Pubkey) -> Self {
        Self::with_instructions(payer, None)
    }

    /// Add an instruction.
    pub fn add(&mut self, instruction: Instruction) -> &mut Self {
        self.instructions.push(instruction);
        self
    }

    /// Add a signer.
    pub fn add_signer(&mut self, signer: &Pubkey) -> &mut Self {
        self.signers.insert(*signer, NullSigner::new(signer));
        self
    }

    /// Add an owned signer.
    pub fn add_owned_signer(&mut self, signer: impl Signer + Clone + 'static) -> &mut Self {
        self.owned_signers
            .insert(signer.pubkey(), BoxClonableSigner::new(signer));
        self
    }

    /// Get compute budget.
    pub fn compute_budget(&self) -> &ComputeBudget {
        &self.compute_budget
    }

    /// Get mutable reference to the compute budget.
    pub fn compute_budget_mut(&mut self) -> &mut ComputeBudget {
        &mut self.compute_budget
    }

    /// Returns the pubkey of the payer.
    pub fn payer(&self) -> &Pubkey {
        &self.payer
    }

    /// Returns signers that need to be provided externally including the payer.
    pub fn external_signers(&self) -> impl Iterator<Item = &Pubkey> + '_ {
        self.signers.keys()
    }

    fn compute_budget_instructions(
        &self,
        compute_unit_price_micro_lamports: Option<u64>,
        compute_unit_min_priority_lamports: Option<u64>,
        extra_compute_units: u32,
    ) -> Vec<Instruction> {
        self.compute_budget
            .compute_budget_instructions_with_extra_units(
                compute_unit_price_micro_lamports,
                compute_unit_min_priority_lamports,
                extra_compute_units,
            )
    }

    /// Returns instructions.
    pub fn instructions_with_options(
        &self,
        options: GetInstructionsOptions,
    ) -> impl Iterator<Item = Cow<'_, Instruction>> {
        let compute_budget_instructions = if options.compute_budget.without_compute_budget {
            Vec::default()
        } else {
            self.compute_budget_instructions(
                options.compute_budget.compute_unit_price_micro_lamports,
                options.compute_budget.compute_unit_min_priority_lamports,
                options.extra_compute_units,
            )
        };
        let memo_signers = match options.memo_signers.as_ref() {
            Some(signers) => signers.iter().collect(),
            None => Vec::from([&self.payer]),
        };
        let memo_instruction = options
            .memo
            .as_ref()
            .map(|s| spl_memo::build_memo(s.as_bytes(), &memo_signers));
        compute_budget_instructions
            .into_iter()
            .chain(memo_instruction)
            .map(Cow::Owned)
            .chain(self.instructions.iter().map(Cow::Borrowed))
    }

    /// Estimates the transaciton size.
    pub fn transaction_size(
        &self,
        is_versioned_transaction: bool,
        luts: Option<&AddressLookupTables>,
        options: GetInstructionsOptions,
    ) -> usize {
        crate::utils::transaction_size_with_luts(
            self.payer,
            &self.instructions_with_options(options).collect::<Vec<_>>(),
            is_versioned_transaction,
            luts,
        )
    }

    /// Estimates the transaction size after merge.
    pub fn transaction_size_after_merge(
        &self,
        other: &Self,
        is_versioned_transaction: bool,
        luts: Option<&AddressLookupTables>,
        options: GetInstructionsOptions,
    ) -> usize {
        crate::utils::transaction_size_with_luts(
            self.payer,
            &self
                .instructions_with_options(options)
                .chain(other.instructions_with_options(GetInstructionsOptions {
                    compute_budget: ComputeBudgetOptions {
                        without_compute_budget: true,
                        ..Default::default()
                    },
                    ..Default::default()
                }))
                .collect::<Vec<_>>(),
            is_versioned_transaction,
            luts,
        )
    }

    /// Merge two [`AtomicGroup`]s.
    ///
    /// # Note
    /// - Merging does not change the payer of the current [`AtomicGroup`].
    pub fn merge(&mut self, mut other: Self) -> &mut Self {
        self.signers.append(&mut other.signers);
        self.owned_signers.append(&mut other.owned_signers);
        self.instructions.extend(other.instructions);
        self.compute_budget += other.compute_budget;
        self
    }

    fn v0_message_with_blockhash_and_options(
        &self,
        recent_blockhash: Hash,
        options: GetInstructionsOptions,
        luts: Option<&AddressLookupTables>,
    ) -> crate::Result<v0::Message> {
        let instructions = self
            .instructions_with_options(options)
            .map(|ix| (*ix).clone())
            .collect::<Vec<_>>();
        let luts = luts
            .map(|t| t.accounts().collect::<Vec<_>>())
            .unwrap_or_default();
        Ok(v0::Message::try_compile(
            self.payer(),
            &instructions,
            &luts,
            recent_blockhash,
        )?)
    }

    /// Create versioned message with the given blockhash and options.
    pub fn message_with_blockhash_and_options(
        &self,
        recent_blockhash: Hash,
        options: GetInstructionsOptions,
        luts: Option<&AddressLookupTables>,
    ) -> crate::Result<VersionedMessage> {
        Ok(VersionedMessage::V0(
            self.v0_message_with_blockhash_and_options(recent_blockhash, options, luts)?,
        ))
    }

    /// Create partially signed transaction with the given blockhash and options.
    pub fn partially_signed_transaction_with_blockhash_and_options(
        &self,
        recent_blockhash: Hash,
        options: GetInstructionsOptions,
        luts: Option<&AddressLookupTables>,
        mut before_sign: impl FnMut(&VersionedMessage) -> crate::Result<()>,
    ) -> crate::Result<VersionedTransaction> {
        let mut memo_signers = vec![];
        if let Some(signers) = options.memo_signers.as_ref() {
            let signers: BTreeSet<_> = signers.iter().collect();
            for signer in signers {
                if !self.signers.contains_key(signer) && !self.owned_signers.contains_key(signer) {
                    memo_signers.push(NullSigner::new(signer));
                }
            }
        }
        let message = self.message_with_blockhash_and_options(recent_blockhash, options, luts)?;
        (before_sign)(&message)?;
        let signers = self
            .signers
            .values()
            .chain(memo_signers.iter())
            .map(|s| s as &dyn Signer)
            .chain(self.owned_signers.values().map(|s| s as &dyn Signer))
            .collect::<Vec<_>>();
        Ok(VersionedTransaction::try_new(message, &signers)?)
    }

    /// Estimates the execution fee of the result transaction.
    pub fn estimate_execution_fee(
        &self,
        compute_unit_price_micro_lamports: Option<u64>,
        compute_unit_min_priority_lamports: Option<u64>,
    ) -> u64 {
        self.estimate_execution_fee_with_extra_units(
            compute_unit_price_micro_lamports,
            compute_unit_min_priority_lamports,
            0,
        )
    }

    /// Estimates the execution fee of the result transaction with extra compute units.
    pub fn estimate_execution_fee_with_extra_units(
        &self,
        compute_unit_price_micro_lamports: Option<u64>,
        compute_unit_min_priority_lamports: Option<u64>,
        extra_compute_units: u32,
    ) -> u64 {
        let ixs = self
            .instructions_with_options(GetInstructionsOptions {
                compute_budget: ComputeBudgetOptions {
                    without_compute_budget: true,
                    ..Default::default()
                },
                ..Default::default()
            })
            .collect::<Vec<_>>();

        let num_signers = ixs
            .iter()
            .flat_map(|ix| ix.accounts.iter())
            .filter(|meta| meta.is_signer)
            .map(|meta| &meta.pubkey)
            .collect::<HashSet<_>>()
            .len() as u64;
        num_signers * 5_000
            + self.compute_budget.fee_with_extra_units(
                compute_unit_price_micro_lamports,
                compute_unit_min_priority_lamports,
                extra_compute_units,
            )
    }
}

impl Extend<Instruction> for AtomicGroup {
    fn extend<T: IntoIterator<Item = Instruction>>(&mut self, iter: T) {
        self.instructions.extend(iter);
    }
}

impl Deref for AtomicGroup {
    type Target = [Instruction];

    fn deref(&self) -> &Self::Target {
        self.instructions.deref()
    }
}

/// The options type for [`ParallelGroup`].
#[derive(Debug, Clone)]
pub struct ParallelGroupOptions {
    /// Indicates whether the [`ParallelGroup`] is mergeable.
    pub is_mergeable: bool,
}

impl Default for ParallelGroupOptions {
    fn default() -> Self {
        Self { is_mergeable: true }
    }
}

/// A group of atomic instructions that can be executed in parallel.
#[derive(Debug, Clone, Default)]
pub struct ParallelGroup {
    groups: SmallVec<[AtomicGroup; PARALLEL_SIZE]>,
    options: ParallelGroupOptions,
}

impl ParallelGroup {
    /// Create a new [`ParallelGroup`] with the given options.
    pub fn with_options(
        groups: impl IntoIterator<Item = AtomicGroup>,
        options: ParallelGroupOptions,
    ) -> Self {
        Self {
            groups: FromIterator::from_iter(groups),
            options,
        }
    }

    /// Returns the options.
    pub fn options(&self) -> &ParallelGroupOptions {
        &self.options
    }

    /// Returns whether the group is mergeable.
    pub fn is_mergeable(&self) -> bool {
        self.options().is_mergeable
    }

    /// Set whether the group is mergeable.
    pub fn set_is_mergeable(&mut self, is_mergeable: bool) -> &mut Self {
        self.options.is_mergeable = is_mergeable;
        self
    }

    /// Add an [`AtomicGroup`].
    pub fn add(&mut self, group: AtomicGroup) -> &mut Self {
        self.groups.push(group);
        self
    }

    pub(crate) fn optimize(
        &mut self,
        options: &TransactionGroupOptions,
        luts: &AddressLookupTables,
        allow_payer_change: bool,
    ) -> &mut Self {
        if options.optimize(&mut self.groups, luts, allow_payer_change) {
            self.groups = self
                .groups
                .drain(..)
                .filter(|group| !group.is_empty())
                .collect();
        }
        self
    }

    pub(crate) fn single(&self) -> Option<&AtomicGroup> {
        if self.groups.len() == 1 {
            Some(&self.groups[0])
        } else {
            None
        }
    }

    pub(crate) fn single_mut(&mut self) -> Option<&mut AtomicGroup> {
        if self.groups.len() == 1 {
            Some(&mut self.groups[0])
        } else {
            None
        }
    }

    pub(crate) fn into_single(mut self) -> Option<AtomicGroup> {
        if self.groups.len() == 1 {
            Some(self.groups.remove(0))
        } else {
            None
        }
    }

    /// Returns the total number of transactions.
    pub fn len(&self) -> usize {
        self.groups.len()
    }

    /// Returns whether the group is empty.
    pub fn is_empty(&self) -> bool {
        self.groups.is_empty()
    }

    /// Estiamtes the execution fee of the result transactions
    pub fn estimate_execution_fee(
        &self,
        compute_unit_price_micro_lamports: Option<u64>,
        compute_unit_min_priority_lamports: Option<u64>,
    ) -> u64 {
        self.estimate_execution_fee_with_extra_units(
            compute_unit_price_micro_lamports,
            compute_unit_min_priority_lamports,
            0,
        )
    }

    /// Estiamtes the execution fee of the result transactions with extra units.
    pub fn estimate_execution_fee_with_extra_units(
        &self,
        compute_unit_price_micro_lamports: Option<u64>,
        compute_unit_min_priority_lamports: Option<u64>,
        extra_compute_units: u32,
    ) -> u64 {
        self.groups
            .iter()
            .map(|ag| {
                ag.estimate_execution_fee_with_extra_units(
                    compute_unit_price_micro_lamports,
                    compute_unit_min_priority_lamports,
                    extra_compute_units,
                )
            })
            .sum()
    }
}

impl From<AtomicGroup> for ParallelGroup {
    fn from(value: AtomicGroup) -> Self {
        let mut this = Self::default();
        this.add(value);
        this
    }
}

impl FromIterator<AtomicGroup> for ParallelGroup {
    fn from_iter<T: IntoIterator<Item = AtomicGroup>>(iter: T) -> Self {
        Self::with_options(iter, Default::default())
    }
}

impl Deref for ParallelGroup {
    type Target = [AtomicGroup];

    fn deref(&self) -> &Self::Target {
        self.groups.deref()
    }
}