gmsol-store 0.6.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
use anchor_lang::prelude::*;
use anchor_spl::{
    associated_token::AssociatedToken,
    token::{Mint, Token, TokenAccount},
};
use gmsol_utils::{market::ordered_tokens, InitSpace};

use crate::{
    constants,
    events::EventEmitter,
    ops::{
        execution_fee::PayExecutionFeeOperation,
        glv::ExecuteGlvShiftOperation,
        shift::{CreateShiftOperation, CreateShiftParams},
    },
    states::{
        common::action::{Action, ActionExt},
        feature::{ActionDisabledFlag, DomainDisabledFlag},
        glv::{GlvMarketFlag, GlvShift},
        Chainlink, Glv, Market, NonceBytes, Oracle, RoleKey, Seed, Store, StoreWalletSigner,
        TokenMapHeader,
    },
    utils::internal,
    CoreError,
};

/// The accounts definition for [`create_glv_shift`](crate::create_glv_shift) instruction.
#[derive(Accounts)]
#[instruction(nonce: [u8; 32])]
pub struct CreateGlvShift<'info> {
    /// Authority.
    #[account(mut)]
    pub authority: Signer<'info>,
    /// Store.
    pub store: AccountLoader<'info, Store>,
    /// GLV.
    #[account(
        mut,
        has_one = store,
        constraint = glv.load()?.contains(&from_market_token.key()) @ CoreError::InvalidArgument,
        constraint = glv.load()?.contains(&to_market_token.key()) @ CoreError::InvalidArgument,
    )]
    pub glv: AccountLoader<'info, Glv>,
    /// From market.
    #[account(
        mut,
        has_one = store,
        constraint = from_market.load()?.meta().market_token_mint == from_market_token.key() @ CoreError::MarketTokenMintMismatched,
    )]
    pub from_market: AccountLoader<'info, Market>,
    /// To market.
    #[account(
        mut,
        has_one = store,
        constraint = to_market.load()?.meta().market_token_mint == to_market_token.key() @ CoreError::MarketTokenMintMismatched,
    )]
    pub to_market: AccountLoader<'info, Market>,
    /// GLV shift.
    #[account(
        init,
        payer = authority,
        space = 8 + GlvShift::INIT_SPACE,
        seeds = [GlvShift::SEED, store.key().as_ref(), authority.key().as_ref(), &nonce],
        bump,
    )]
    pub glv_shift: AccountLoader<'info, GlvShift>,
    /// From market token.
    #[account(
        constraint = from_market_token.key() != to_market_token.key() @ CoreError::InvalidShiftMarkets,
    )]
    pub from_market_token: Box<Account<'info, Mint>>,
    /// To market token.
    pub to_market_token: Box<Account<'info, Mint>>,
    /// Vault for from market tokens.
    #[account(
        associated_token::mint = from_market_token,
        associated_token::authority = glv,
    )]
    pub from_market_token_vault: Box<Account<'info, TokenAccount>>,
    /// Vault for to market tokens.
    #[account(
        associated_token::mint = to_market_token,
        associated_token::authority = glv,
    )]
    pub to_market_token_vault: Box<Account<'info, TokenAccount>>,
    /// The system program.
    pub system_program: Program<'info, System>,
    /// The token program.
    pub token_program: Program<'info, Token>,
    /// The associated token program.
    pub associated_token_program: Program<'info, AssociatedToken>,
}

impl<'info> internal::Create<'info, GlvShift> for CreateGlvShift<'info> {
    type CreateParams = CreateShiftParams;

    fn action(&self) -> AccountInfo<'info> {
        self.glv_shift.to_account_info()
    }

    fn payer(&self) -> AccountInfo<'info> {
        self.authority.to_account_info()
    }

    fn payer_seeds(&self) -> Result<Option<Vec<Vec<u8>>>> {
        Ok(Some(self.glv.load()?.vec_signer_seeds()))
    }

    fn system_program(&self) -> AccountInfo<'info> {
        self.system_program.to_account_info()
    }

    fn validate(&self, _params: &Self::CreateParams) -> Result<()> {
        self.store
            .load()?
            .validate_not_restarted()?
            .validate_feature_enabled(DomainDisabledFlag::GlvShift, ActionDisabledFlag::Create)?;
        let glv = self.glv.load()?;
        let market_token = self.to_market_token.key();
        let is_deposit_allowed = glv
            .market_config(&market_token)
            .ok_or_else(|| error!(CoreError::Internal))?
            .get_flag(GlvMarketFlag::IsDepositAllowed);
        require!(is_deposit_allowed, CoreError::GlvDepositIsNotAllowed);
        glv.validate_shift_interval()
    }

    fn create_impl(
        &mut self,
        params: &Self::CreateParams,
        nonce: &NonceBytes,
        bumps: &Self::Bumps,
        _remaining_accounts: &'info [AccountInfo<'info>],
        callback_version: Option<u8>,
    ) -> Result<()> {
        require_eq!(callback_version.is_none(), true, {
            msg!("[Callback] callback is not supported by this instruction.");
            CoreError::InvalidArgument
        });
        CreateShiftOperation::builder()
            .store(&self.store)
            .owner(self.glv.as_ref())
            .receiver(self.glv.as_ref())
            .shift(&self.glv_shift)
            .from_market(&self.from_market)
            .from_market_token_account(&self.from_market_token_vault)
            .to_market(&self.to_market)
            .to_market_token_account(&self.to_market_token_vault)
            .nonce(nonce)
            .bump(bumps.glv_shift)
            .params(params)
            .build()
            .execute()?;

        // Set the funder of the GLV shift.
        {
            self.glv_shift.exit(&crate::ID)?;
            self.glv_shift
                .load_mut()?
                .header_mut()
                .set_rent_receiver(self.authority.key());
        }

        Ok(())
    }
}

impl<'info> internal::Authentication<'info> for CreateGlvShift<'info> {
    fn authority(&self) -> &Signer<'info> {
        &self.authority
    }

    fn store(&self) -> &AccountLoader<'info, Store> {
        &self.store
    }
}

/// The accounts definition for [`close_glv_shift`](crate::close_glv_shift) instruction.
#[event_cpi]
#[derive(Accounts)]
pub struct CloseGlvShift<'info> {
    /// Authority.
    #[account(mut)]
    pub authority: Signer<'info>,
    /// Funder of the GLV shift.
    /// CHECK: only used to receive funds.
    #[account(mut)]
    pub funder: UncheckedAccount<'info>,
    /// The store.
    pub store: AccountLoader<'info, Store>,
    /// The store wallet.
    #[account(mut, seeds = [Store::WALLET_SEED, store.key().as_ref()], bump)]
    pub store_wallet: SystemAccount<'info>,
    /// GLV.
    #[account(
        has_one = store,
        constraint = glv.load()?.contains(&from_market_token.key()) @ CoreError::InvalidArgument,
        constraint = glv.load()?.contains(&to_market_token.key()) @ CoreError::InvalidArgument,
    )]
    pub glv: AccountLoader<'info, Glv>,
    /// The GLV shift to close.
    #[account(
        mut,
        constraint = glv_shift.load()?.header().owner == glv.key() @ CoreError::OwnerMismatched,
        constraint = glv_shift.load()?.header().store == store.key() @ CoreError::StoreMismatched,
        // The rent receiver of a GLV shift must be the funder.
        constraint = glv_shift.load()?.header().rent_receiver() == funder.key @ CoreError::RentReceiverMismatched,
    )]
    pub glv_shift: AccountLoader<'info, GlvShift>,
    /// From Market token.
    #[account(
        constraint = glv_shift.load()?.tokens().from_market_token() == from_market_token.key() @ CoreError::MarketTokenMintMismatched
    )]
    pub from_market_token: Box<Account<'info, Mint>>,
    /// To Market token.
    #[account(
        constraint = glv_shift.load()?.tokens().to_market_token() == to_market_token.key() @ CoreError::MarketTokenMintMismatched
    )]
    pub to_market_token: Box<Account<'info, Mint>>,
    /// The system program.
    pub system_program: Program<'info, System>,
    /// The token program.
    pub token_program: Program<'info, Token>,
    /// The associated token program.
    pub associated_token_program: Program<'info, AssociatedToken>,
}

impl<'info> internal::Close<'info, GlvShift> for CloseGlvShift<'info> {
    fn expected_keeper_role(&self) -> &str {
        RoleKey::ORDER_KEEPER
    }

    fn rent_receiver(&self) -> AccountInfo<'info> {
        debug_assert!(
            self.glv_shift.load().unwrap().header().rent_receiver() == self.funder.key,
            "The rent receiver must have been checked to be the owner"
        );
        self.funder.to_account_info()
    }

    fn skip_completion_check_for_keeper(&self) -> Result<bool> {
        // Allow the funder to close the GLV shift even if it has not reached a final state.
        Ok(*self.glv_shift.load()?.funder() == self.authority.key())
    }

    fn store_wallet_bump(&self, bumps: &Self::Bumps) -> u8 {
        bumps.store_wallet
    }

    fn validate(&self) -> Result<()> {
        let glv_shift = self.glv_shift.load()?;
        if glv_shift.header().action_state()?.is_pending() {
            self.store
                .load()?
                .validate_not_restarted()?
                .validate_feature_enabled(
                    DomainDisabledFlag::GlvShift,
                    ActionDisabledFlag::Cancel,
                )?;
        }
        Ok(())
    }

    fn process(
        &self,
        _init_if_needed: bool,
        _store_wallet_signer: &StoreWalletSigner,
        _event_emitter: &EventEmitter<'_, 'info>,
    ) -> Result<internal::Success> {
        Ok(true)
    }

    fn event_authority(&self, bumps: &Self::Bumps) -> (AccountInfo<'info>, u8) {
        (self.event_authority.clone(), bumps.event_authority)
    }

    fn action(&self) -> &AccountLoader<'info, GlvShift> {
        &self.glv_shift
    }
}

impl<'info> internal::Authentication<'info> for CloseGlvShift<'info> {
    fn authority(&self) -> &Signer<'info> {
        &self.authority
    }

    fn store(&self) -> &AccountLoader<'info, Store> {
        &self.store
    }
}

/// The accounts definition for [`execute_glv_shift`](crate::execute_glv_shift) instruction.
///
/// Remaining accounts expected by this instruction:
///
///   - 0..M. `[]` M feed accounts, where M represents the total number of unique tokens
///     of markets.
#[event_cpi]
#[derive(Accounts)]
pub struct ExecuteGlvShift<'info> {
    /// Authority.
    pub authority: Signer<'info>,
    /// Store.
    #[account(has_one = token_map)]
    pub store: AccountLoader<'info, Store>,
    /// Token Map.
    #[account(has_one = store)]
    pub token_map: AccountLoader<'info, TokenMapHeader>,
    /// Oracle buffer to use.
    #[account(mut, has_one = store)]
    pub oracle: AccountLoader<'info, Oracle>,
    /// GLV account.
    #[account(
        mut,
        has_one = store,
        constraint = glv.load()?.contains(&from_market_token.key()) @ CoreError::InvalidArgument,
        constraint = glv.load()?.contains(&to_market_token.key()) @ CoreError::InvalidArgument,
    )]
    pub glv: AccountLoader<'info, Glv>,
    /// From Market.
    #[account(
        mut,
        has_one = store,
        constraint = from_market.load()?.meta().market_token_mint == from_market_token.key() @ CoreError::MarketTokenMintMismatched,
    )]
    pub from_market: AccountLoader<'info, Market>,
    /// To Market.
    #[account(
        mut,
        has_one = store,
        constraint = to_market.load()?.meta().market_token_mint == to_market_token.key() @ CoreError::MarketTokenMintMismatched,
    )]
    pub to_market: AccountLoader<'info, Market>,
    /// The GLV shift to close.
    #[account(
        mut,
        constraint = glv_shift.load()?.header().owner == glv.key() @ CoreError::OwnerMismatched,
        constraint = glv_shift.load()?.header().store == store.key() @ CoreError::StoreMismatched,
        constraint = glv_shift.load()?.tokens().from_market_token_account() == from_market_token_glv_vault.key() @ CoreError::MarketTokenAccountMismatched,
        constraint = glv_shift.load()?.tokens().to_market_token_account() == to_market_token_glv_vault.key() @ CoreError::MarketTokenAccountMismatched,
    )]
    pub glv_shift: AccountLoader<'info, GlvShift>,
    /// From Market token.
    #[account(
        mut,
        constraint = glv_shift.load()?.tokens().from_market_token() == from_market_token.key() @ CoreError::MarketTokenMintMismatched
    )]
    pub from_market_token: Box<Account<'info, Mint>>,
    /// To Market token.
    #[account(
        mut,
        constraint = glv_shift.load()?.tokens().to_market_token() == to_market_token.key() @ CoreError::MarketTokenMintMismatched
    )]
    pub to_market_token: Box<Account<'info, Mint>>,
    /// The escrow account for from market tokens.
    #[account(
        mut,
        associated_token::mint = from_market_token,
        associated_token::authority = glv,
    )]
    pub from_market_token_glv_vault: Box<Account<'info, TokenAccount>>,
    /// The escrow account for to market tokens.
    #[account(
        mut,
        associated_token::mint = to_market_token,
        associated_token::authority = glv,
    )]
    pub to_market_token_glv_vault: Box<Account<'info, TokenAccount>>,
    /// From market token vault.
    #[account(
        mut,
        token::mint = from_market_token,
        seeds = [
            constants::MARKET_VAULT_SEED,
            store.key().as_ref(),
            from_market_token_vault.mint.as_ref(),
        ],
        bump,
    )]
    pub from_market_token_vault: Box<Account<'info, TokenAccount>>,
    /// The token program.
    pub token_program: Program<'info, Token>,
    /// Chainlink Program.
    pub chainlink_program: Option<Program<'info, Chainlink>>,
}

/// Execute GLV shift.
///
/// # CHECK
/// - Only ORDER_KEEPER is allowed to execute shift.
pub fn unchecked_execute_glv_shift<'info>(
    ctx: Context<'_, '_, 'info, 'info, ExecuteGlvShift<'info>>,
    execution_lamports: u64,
    throw_on_execution_error: bool,
) -> Result<()> {
    let accounts = ctx.accounts;
    let remaining_accounts = ctx.remaining_accounts;

    // Validate feature enabled.
    accounts
        .store
        .load()?
        .validate_feature_enabled(DomainDisabledFlag::GlvShift, ActionDisabledFlag::Execute)?;

    let executed = accounts.perform_execution(
        remaining_accounts,
        throw_on_execution_error,
        ctx.bumps.event_authority,
    )?;

    if executed {
        accounts.glv_shift.load_mut()?.header_mut().completed()?;
    } else {
        accounts.glv_shift.load_mut()?.header_mut().cancelled()?;
    }

    // It must be placed at the end to be executed correctly.
    accounts.pay_execution_fee(execution_lamports)?;

    Ok(())
}

impl<'info> internal::Authentication<'info> for ExecuteGlvShift<'info> {
    fn authority(&self) -> &Signer<'info> {
        &self.authority
    }

    fn store(&self) -> &AccountLoader<'info, Store> {
        &self.store
    }
}

impl<'info> ExecuteGlvShift<'info> {
    #[inline(never)]
    fn pay_execution_fee(&self, execution_fee: u64) -> Result<()> {
        let execution_lamports = self.glv_shift.load()?.execution_lamports(execution_fee);
        PayExecutionFeeOperation::builder()
            .payer(self.glv_shift.to_account_info())
            .receiver(self.authority.to_account_info())
            .execution_lamports(execution_lamports)
            .build()
            .execute()?;
        Ok(())
    }

    #[inline(never)]
    fn ordered_tokens(&self) -> Result<Vec<Pubkey>> {
        let from = *self.from_market.load()?.meta();
        let to = *self.to_market.load()?.meta();

        Ok(ordered_tokens(&from, &to).into_iter().collect())
    }

    fn perform_execution(
        &mut self,
        remaining_accounts: &'info [AccountInfo<'info>],
        throw_on_execution_error: bool,
        event_authority_bump: u8,
    ) -> Result<bool> {
        let tokens = self.ordered_tokens()?;

        let builder = ExecuteGlvShiftOperation::builder()
            .glv_shift(&self.glv_shift)
            .token_program(self.token_program.to_account_info())
            .throw_on_execution_error(throw_on_execution_error)
            .store(&self.store)
            .glv(&self.glv)
            .from_market(&self.from_market)
            .from_market_token_mint(&mut self.from_market_token)
            .from_market_token_glv_vault(&self.from_market_token_glv_vault)
            .from_market_token_withdrawal_vault(self.from_market_token_vault.to_account_info())
            .to_market(&self.to_market)
            .to_market_token_mint(&mut self.to_market_token)
            .to_market_token_glv_vault(self.to_market_token_glv_vault.to_account_info())
            .event_emitter((&self.event_authority, event_authority_bump));

        self.oracle.load_mut()?.with_prices(
            &self.store,
            &self.token_map,
            &tokens,
            remaining_accounts,
            |oracle, _remaining_accounts| builder.oracle(oracle).build().unchecked_execute(),
        )
    }
}