gmsol-sdk 0.9.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
use std::{future::Future, ops::Deref, sync::Arc};

use gmsol_programs::{
    constants::roles,
    gmsol_timelock::{
        accounts::{Executor, InstructionHeader},
        client::{accounts, args},
    },
};
use gmsol_solana_utils::transaction_builder::TransactionBuilder;
use gmsol_utils::{instruction::InstructionAccess, oracle::PriceProviderKind, role::RoleKey};
use solana_sdk::{
    instruction::{AccountMeta, Instruction},
    pubkey::Pubkey,
    signer::Signer,
    system_program,
};

use crate::utils::zero_copy::ZeroCopy;

/// Timelock instructions.
pub trait TimelockOps<C> {
    /// Initialize [`TimelockConfig`](gmsol_programs::gmsol_timelock::accounts::TimelockConfig) account.
    fn initialize_timelock_config(
        &self,
        store: &Pubkey,
        initial_delay: u32,
    ) -> TransactionBuilder<C, Pubkey>;

    /// Increase timelock delay.
    fn increase_timelock_delay(&self, store: &Pubkey, delta: u32) -> TransactionBuilder<C>;

    /// Initialize [`Executor`] account.
    fn initialize_executor(
        &self,
        store: &Pubkey,
        role: &str,
    ) -> crate::Result<TransactionBuilder<C, Pubkey>>;

    /// Create a timelocked instruction buffer for the given instruction.
    fn create_timelocked_instruction(
        &self,
        store: &Pubkey,
        role: &str,
        buffer: impl Signer + 'static,
        instruction: Instruction,
    ) -> crate::Result<TransactionBuilder<C, Pubkey>>;

    /// Approve timelocked instruction.
    fn approve_timelocked_instruction(
        &self,
        store: &Pubkey,
        buffer: &Pubkey,
        role_hint: Option<&str>,
    ) -> impl Future<Output = crate::Result<TransactionBuilder<C>>>;

    /// Approve timelocked instruction.
    fn approve_timelocked_instructions(
        &self,
        store: &Pubkey,
        buffers: impl IntoIterator<Item = Pubkey>,
        role_hint: Option<&str>,
    ) -> impl Future<Output = crate::Result<TransactionBuilder<C>>>;

    /// Cancel timelocked instruction.
    fn cancel_timelocked_instruction(
        &self,
        store: &Pubkey,
        buffer: &Pubkey,
        executor_hint: Option<&Pubkey>,
        rent_receiver_hint: Option<&Pubkey>,
    ) -> impl Future<Output = crate::Result<TransactionBuilder<C>>>;

    /// Cancel timelocked instruction.
    fn cancel_timelocked_instructions(
        &self,
        store: &Pubkey,
        buffers: impl IntoIterator<Item = Pubkey>,
        executor_hint: Option<&Pubkey>,
        rent_receiver_hint: Option<&Pubkey>,
    ) -> impl Future<Output = crate::Result<TransactionBuilder<C>>>;

    /// Execute timelocked instruction.
    fn execute_timelocked_instruction(
        &self,
        store: &Pubkey,
        buffer: &Pubkey,
        hint: Option<ExecuteTimelockedInstructionHint<'_>>,
    ) -> impl Future<Output = crate::Result<TransactionBuilder<C>>>;

    /// Timelock-bypassed revoke role.
    fn timelock_bypassed_revoke_role(
        &self,
        store: &Pubkey,
        role: &str,
        address: &Pubkey,
    ) -> TransactionBuilder<C>;

    /// Timelock-bypassed set expected price provider.
    fn timelock_bypassed_set_epxected_price_provider(
        &self,
        store: &Pubkey,
        token_map: &Pubkey,
        token: &Pubkey,
        new_expected_price_provider: PriceProviderKind,
    ) -> TransactionBuilder<C>;
}

impl<C: Deref<Target = impl Signer> + Clone> TimelockOps<C> for crate::Client<C> {
    fn initialize_timelock_config(
        &self,
        store: &Pubkey,
        initial_delay: u32,
    ) -> TransactionBuilder<C, Pubkey> {
        let config = self.find_timelock_config_address(store);
        let executor = self
            .find_executor_address(store, roles::ADMIN)
            .expect("must success");
        self.timelock_transaction()
            .anchor_args(args::InitializeConfig {
                delay: initial_delay,
            })
            .anchor_accounts(accounts::InitializeConfig {
                authority: self.payer(),
                store: *store,
                timelock_config: config,
                executor,
                wallet: self.find_executor_wallet_address(&executor),
                store_program: *self.store_program_id(),
                system_program: system_program::ID,
            })
            .output(config)
    }

    fn increase_timelock_delay(&self, store: &Pubkey, delta: u32) -> TransactionBuilder<C> {
        self.timelock_transaction()
            .anchor_args(args::IncreaseDelay { delta })
            .anchor_accounts(accounts::IncreaseDelay {
                authority: self.payer(),
                store: *store,
                timelock_config: self.find_timelock_config_address(store),
                store_program: *self.store_program_id(),
            })
    }

    fn initialize_executor(
        &self,
        store: &Pubkey,
        role: &str,
    ) -> crate::Result<TransactionBuilder<C, Pubkey>> {
        let executor = self.find_executor_address(store, role)?;
        let wallet = self.find_executor_wallet_address(&executor);
        Ok(self
            .timelock_transaction()
            .anchor_args(args::InitializeExecutor {
                role: role.to_string(),
            })
            .anchor_accounts(accounts::InitializeExecutor {
                payer: self.payer(),
                store: *store,
                executor,
                wallet,
                system_program: system_program::ID,
            })
            .output(executor))
    }

    fn create_timelocked_instruction(
        &self,
        store: &Pubkey,
        role: &str,
        buffer: impl Signer + 'static,
        mut instruction: Instruction,
    ) -> crate::Result<TransactionBuilder<C, Pubkey>> {
        let executor = self.find_executor_address(store, role)?;
        let instruction_buffer = buffer.pubkey();

        let mut signers = vec![];

        instruction
            .accounts
            .iter_mut()
            .enumerate()
            .for_each(|(idx, account)| {
                if account.is_signer {
                    signers.push(idx as u16);
                }
                account.is_signer = false;
            });

        let num_accounts = instruction
            .accounts
            .len()
            .try_into()
            .map_err(|_| crate::Error::custom("too many accounts"))?;

        let data_len = instruction
            .data
            .len()
            .try_into()
            .map_err(|_| crate::Error::custom("data too long"))?;

        let rpc = self
            .timelock_transaction()
            .anchor_args(args::CreateInstructionBuffer {
                num_accounts,
                data_len,
                data: instruction.data,
                signers,
            })
            .anchor_accounts(accounts::CreateInstructionBuffer {
                authority: self.payer(),
                store: *store,
                executor,
                instruction_buffer,
                instruction_program: instruction.program_id,
                store_program: *self.store_program_id(),
                system_program: system_program::ID,
            })
            .accounts(instruction.accounts)
            .owned_signer(Arc::new(buffer))
            .output(instruction_buffer);
        Ok(rpc)
    }

    async fn approve_timelocked_instruction(
        &self,
        store: &Pubkey,
        buffer: &Pubkey,
        role_hint: Option<&str>,
    ) -> crate::Result<TransactionBuilder<C>> {
        let role = match role_hint {
            Some(role) => role.to_string(),
            None => {
                let instruction_header = self
                    .account::<ZeroCopy<InstructionHeader>>(buffer)
                    .await?
                    .ok_or(crate::Error::NotFound)?
                    .0;
                let executor = &instruction_header.executor;
                let executor = self
                    .account::<ZeroCopy<Executor>>(executor)
                    .await?
                    .ok_or(crate::Error::NotFound)?
                    .0;
                executor.role_name()?.to_string()
            }
        };
        let executor = self.find_executor_address(store, &role)?;
        Ok(self
            .timelock_transaction()
            .anchor_args(args::ApproveInstruction { role })
            .anchor_accounts(accounts::ApproveInstruction {
                authority: self.payer(),
                store: *store,
                executor,
                instruction: *buffer,
                store_program: *self.store_program_id(),
            }))
    }

    async fn approve_timelocked_instructions(
        &self,
        store: &Pubkey,
        buffers: impl IntoIterator<Item = Pubkey>,
        role_hint: Option<&str>,
    ) -> crate::Result<TransactionBuilder<C>> {
        let mut buffers = buffers.into_iter().peekable();
        let buffer = buffers
            .peek()
            .ok_or_else(|| crate::Error::custom("no instructions to appove"))?;
        let role = match role_hint {
            Some(role) => role.to_string(),
            None => {
                let instruction_header = self
                    .account::<ZeroCopy<InstructionHeader>>(buffer)
                    .await?
                    .ok_or(crate::Error::NotFound)?
                    .0;
                let executor = &instruction_header.executor;
                let executor = self
                    .account::<ZeroCopy<Executor>>(executor)
                    .await?
                    .ok_or(crate::Error::NotFound)?
                    .0;
                executor.role_name()?.to_string()
            }
        };
        let executor = self.find_executor_address(store, &role)?;
        Ok(self
            .timelock_transaction()
            .anchor_args(args::ApproveInstructions { role })
            .anchor_accounts(accounts::ApproveInstructions {
                authority: self.payer(),
                store: *store,
                executor,
                store_program: *self.store_program_id(),
            })
            .accounts(
                buffers
                    .map(|pubkey| AccountMeta {
                        pubkey,
                        is_signer: false,
                        is_writable: true,
                    })
                    .collect::<Vec<_>>(),
            ))
    }

    async fn cancel_timelocked_instruction(
        &self,
        store: &Pubkey,
        buffer: &Pubkey,
        executor_hint: Option<&Pubkey>,
        rent_receiver_hint: Option<&Pubkey>,
    ) -> crate::Result<TransactionBuilder<C>> {
        let (executor, rent_receiver) = match (executor_hint, rent_receiver_hint) {
            (Some(executor), Some(rent_receiver)) => (*executor, *rent_receiver),
            _ => {
                let instruction_header = self
                    .account::<ZeroCopy<InstructionHeader>>(buffer)
                    .await?
                    .ok_or(crate::Error::NotFound)?
                    .0;
                (
                    instruction_header.executor,
                    instruction_header.rent_receiver,
                )
            }
        };
        Ok(self
            .timelock_transaction()
            .anchor_args(args::CancelInstruction {})
            .anchor_accounts(accounts::CancelInstruction {
                authority: self.payer(),
                store: *store,
                executor,
                rent_receiver,
                instruction: *buffer,
                store_program: *self.store_program_id(),
            }))
    }

    async fn cancel_timelocked_instructions(
        &self,
        store: &Pubkey,
        buffers: impl IntoIterator<Item = Pubkey>,
        executor_hint: Option<&Pubkey>,
        rent_receiver_hint: Option<&Pubkey>,
    ) -> crate::Result<TransactionBuilder<C>> {
        let mut buffers = buffers.into_iter().peekable();
        let buffer = buffers
            .peek()
            .ok_or_else(|| crate::Error::custom("no instructions to appove"))?;
        let (executor, rent_receiver) = match (executor_hint, rent_receiver_hint) {
            (Some(executor), Some(rent_receiver)) => (*executor, *rent_receiver),
            _ => {
                let instruction_header = self
                    .account::<ZeroCopy<InstructionHeader>>(buffer)
                    .await?
                    .ok_or(crate::Error::NotFound)?
                    .0;
                (
                    instruction_header.executor,
                    instruction_header.rent_receiver,
                )
            }
        };
        Ok(self
            .timelock_transaction()
            .anchor_args(args::CancelInstructions {})
            .anchor_accounts(accounts::CancelInstructions {
                authority: self.payer(),
                store: *store,
                executor,
                rent_receiver,
                store_program: *self.store_program_id(),
            })
            .accounts(
                buffers
                    .map(|pubkey| AccountMeta {
                        pubkey,
                        is_signer: false,
                        is_writable: true,
                    })
                    .collect::<Vec<_>>(),
            ))
    }

    async fn execute_timelocked_instruction(
        &self,
        store: &Pubkey,
        buffer: &Pubkey,
        hint: Option<ExecuteTimelockedInstructionHint<'_>>,
    ) -> crate::Result<TransactionBuilder<C>> {
        let (executor, rent_receiver, mut accounts) = match hint {
            Some(hint) => (
                *hint.executor,
                *hint.rent_receiver,
                hint.accounts.to_owned(),
            ),
            None => {
                let buffer = self
                    .instruction_buffer(buffer)
                    .await?
                    .ok_or(crate::Error::NotFound)?;
                let executor = buffer.header.executor;
                let rent_receiver = buffer.header.rent_receiver;
                (
                    executor,
                    rent_receiver,
                    buffer.accounts().map(AccountMeta::from).collect(),
                )
            }
        };

        let wallet = self.find_executor_wallet_address(&executor);

        accounts
            .iter_mut()
            .filter(|a| a.pubkey == wallet)
            .for_each(|a| a.is_signer = false);

        Ok(self
            .timelock_transaction()
            .anchor_args(args::ExecuteInstruction {})
            .anchor_accounts(accounts::ExecuteInstruction {
                authority: self.payer(),
                store: *store,
                timelock_config: self.find_timelock_config_address(store),
                executor,
                wallet,
                rent_receiver,
                instruction: *buffer,
                store_program: *self.store_program_id(),
            })
            .accounts(accounts))
    }

    fn timelock_bypassed_revoke_role(
        &self,
        store: &Pubkey,
        role: &str,
        address: &Pubkey,
    ) -> TransactionBuilder<C> {
        let executor = self
            .find_executor_address(store, roles::ADMIN)
            .expect("must success");
        let wallet = self.find_executor_wallet_address(&executor);
        self.timelock_transaction()
            .anchor_args(args::RevokeRole {
                role: role.to_string(),
            })
            .anchor_accounts(accounts::RevokeRole {
                authority: self.payer(),
                store: *store,
                executor,
                wallet,
                user: *address,
                store_program: *self.store_program_id(),
            })
    }

    fn timelock_bypassed_set_epxected_price_provider(
        &self,
        store: &Pubkey,
        token_map: &Pubkey,
        token: &Pubkey,
        new_expected_price_provider: PriceProviderKind,
    ) -> TransactionBuilder<C> {
        let executor = self
            .find_executor_address(store, RoleKey::MARKET_KEEPER)
            .expect("must success");
        let wallet = self.find_executor_wallet_address(&executor);
        self.timelock_transaction()
            .anchor_args(args::SetExpectedPriceProvider {
                new_expected_price_provider: new_expected_price_provider.into(),
            })
            .anchor_accounts(accounts::SetExpectedPriceProvider {
                authority: self.payer(),
                store: *store,
                executor,
                wallet,
                token_map: *token_map,
                token: *token,
                store_program: *self.store_program_id(),
                system_program: system_program::ID,
            })
    }
}

/// Execute timelocked instruction hint.
#[derive(Debug)]
pub struct ExecuteTimelockedInstructionHint<'a> {
    /// Executor.
    pub executor: &'a Pubkey,
    /// Rent receiver.
    pub rent_receiver: &'a Pubkey,
    /// Accounts.
    pub accounts: &'a [AccountMeta],
}