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
use anchor_lang::prelude::*;
use gmsol_utils::InitSpace;

use crate::{
    events::{EventEmitter, GtBuyback, GtUpdated},
    states::{
        gt::{GtExchange, GtExchangeVault},
        user::UserHeader,
        Seed, Store,
    },
    utils::internal,
    CoreError,
};

/// The accounts definitions for the [`initialize_gt`](crate::gmsol_store::initialize_gt) instruction.
#[derive(Accounts)]
pub struct InitializeGt<'info> {
    /// Authority
    #[account(mut)]
    pub authority: Signer<'info>,
    /// Store.
    #[account(mut)]
    pub store: AccountLoader<'info, Store>,
    pub system_program: Program<'info, System>,
}

/// CHECK: only MARKET_KEEPER is allowed to use this instruction.
pub(crate) fn unchecked_initialize_gt(
    ctx: Context<InitializeGt>,
    decimals: u8,
    initial_minting_cost: u128,
    grow_factor: u128,
    grow_step: u64,
    ranks: &[u64],
) -> Result<()> {
    ctx.accounts.initialize_gt_state(
        decimals,
        initial_minting_cost,
        grow_factor,
        grow_step,
        ranks,
    )?;
    Ok(())
}

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

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

impl InitializeGt<'_> {
    fn initialize_gt_state(
        &self,
        decimals: u8,
        initial_minting_cost: u128,
        grow_factor: u128,
        grow_step: u64,
        ranks: &[u64],
    ) -> Result<()> {
        let mut store = self.store.load_mut()?;
        store.gt_mut().init(
            decimals,
            initial_minting_cost,
            grow_factor,
            grow_step,
            ranks,
        )?;
        Ok(())
    }
}

/// The accounts definitions for GT configuration instructions.
#[derive(Accounts)]
pub struct ConfigureGt<'info> {
    /// Authority.
    pub authority: Signer<'info>,
    /// Store.
    #[account(
        mut,
        constraint = store.load()?.gt().is_initialized() @ CoreError::PreconditionsAreNotMet,
    )]
    pub store: AccountLoader<'info, Store>,
}

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

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

/// CHECK: only MARKET_KEEPER is authorized to use this instruction.
pub(crate) fn unchecked_gt_set_order_fee_discount_factors(
    ctx: Context<ConfigureGt>,
    factors: &[u128],
) -> Result<()> {
    ctx.accounts
        .store
        .load_mut()?
        .gt_mut()
        .set_order_fee_discount_factors(factors)
}

/// CHECK: only GT_CONTROLLER is authorized to use this instruction.
pub(crate) fn unchecked_gt_set_referral_reward_factors(
    ctx: Context<ConfigureGt>,
    factors: &[u128],
) -> Result<()> {
    ctx.accounts
        .store
        .load_mut()?
        .gt_mut()
        .set_referral_reward_factors(factors)
}

/// CHECK: only GT_CONTROLLER is authorized to use this instruction.
#[cfg(feature = "test-only")]
pub(crate) fn unchecked_gt_set_exchange_time_window(
    ctx: Context<ConfigureGt>,
    window: u32,
) -> Result<()> {
    ctx.accounts
        .store
        .load_mut()?
        .gt_mut()
        .set_exchange_time_window(window)
}

/// The accounts definition for [`prepare_gt_exchange_vault`](crate::gmsol_store::prepare_gt_exchange_vault) instruction.
#[derive(Accounts)]
#[instruction(time_window_index: i64)]
pub struct PrepareGtExchangeVault<'info> {
    #[account(mut)]
    pub payer: Signer<'info>,
    #[account(constraint = store.load()?.validate_not_restarted()?.gt().is_initialized() @ CoreError::PreconditionsAreNotMet)]
    pub store: AccountLoader<'info, Store>,
    #[account(
        init_if_needed,
        space = 8 + GtExchangeVault::INIT_SPACE,
        payer = payer,
        seeds = [
            GtExchangeVault::SEED,
            store.key().as_ref(),
            &time_window_index.to_le_bytes(),
            &store.load()?.gt().exchange_time_window().to_le_bytes(),
        ],
        bump,
    )]
    pub vault: AccountLoader<'info, GtExchangeVault>,
    pub system_program: Program<'info, System>,
}

pub(crate) fn prepare_gt_exchange_vault(
    ctx: Context<PrepareGtExchangeVault>,
    time_window_index: i64,
) -> Result<()> {
    let store = ctx.accounts.store.load()?;
    let time_window = store.gt().exchange_time_window();

    match ctx.accounts.vault.load_init() {
        Ok(mut vault) => {
            vault.init(ctx.bumps.vault, &ctx.accounts.store.key(), time_window)?;
            drop(vault);
            ctx.accounts.vault.exit(&crate::ID)?;
        }
        Err(Error::AnchorError(err)) => {
            if err.error_code_number != ErrorCode::AccountDiscriminatorAlreadySet as u32 {
                return Err(Error::AnchorError(err));
            }
        }
        Err(err) => {
            return Err(err);
        }
    }

    // Validate the vault.
    {
        let vault = ctx.accounts.vault.load()?;
        require!(vault.is_initialized(), CoreError::PreconditionsAreNotMet);
        require_keys_eq!(
            vault.store,
            ctx.accounts.store.key(),
            CoreError::StoreMismatched
        );
        require_eq!(
            vault.time_window_index(),
            time_window_index,
            CoreError::InvalidArgument
        );
        require_eq!(
            vault.time_window(),
            time_window as i64,
            CoreError::InvalidArgument
        );
    }

    Ok(())
}

/// The accounts definition for [`request_gt_exchange`](crate::gmsol_store::request_gt_exchange) instruction.
#[event_cpi]
#[derive(Accounts)]
pub struct RequestGtExchange<'info> {
    #[account(mut)]
    pub owner: Signer<'info>,
    #[account(
        mut,
        constraint = store.load()?.validate_not_restarted()?.gt().is_initialized() @ CoreError::PreconditionsAreNotMet,
    )]
    pub store: AccountLoader<'info, Store>,
    /// User Account.
    #[account(
        mut,
        constraint = user.load()?.is_initialized() @ CoreError::InvalidUserAccount,
        has_one = owner,
        has_one = store,
        seeds = [UserHeader::SEED, store.key().as_ref(), owner.key().as_ref()],
        bump = user.load()?.bump,
    )]
    pub user: AccountLoader<'info, UserHeader>,
    #[account(
        mut,
        constraint = vault.load()?.is_initialized() @ CoreError::InvalidArgument,
        has_one = store,
        seeds = [
            GtExchangeVault::SEED,
            store.key().as_ref(),
            &vault.load()?.time_window_index().to_le_bytes(),
            &vault.load()?.time_window_u32().to_le_bytes(),
        ],
        bump = vault.load()?.bump,
    )]
    pub vault: AccountLoader<'info, GtExchangeVault>,
    #[account(
        init_if_needed,
        payer = owner,
        space = 8 + GtExchange::INIT_SPACE,
        seeds = [GtExchange::SEED, vault.key().as_ref(), owner.key().as_ref()],
        bump,
    )]
    pub exchange: AccountLoader<'info, GtExchange>,
    pub system_program: Program<'info, System>,
}

pub(crate) fn request_gt_exchange(ctx: Context<RequestGtExchange>, amount: u64) -> Result<()> {
    let accounts = ctx.accounts;

    accounts.validate_and_init_exchange_if_needed(ctx.bumps.exchange)?;

    let mut store = accounts.store.load_mut()?;
    let mut vault = accounts.vault.load_mut()?;
    let mut user = accounts.user.load_mut()?;
    let mut exchange = accounts.exchange.load_mut()?;

    store
        .gt_mut()
        .unchecked_request_exchange(&mut user, &mut vault, &mut exchange, amount)?;

    let event_emitter = EventEmitter::new(&accounts.event_authority, ctx.bumps.event_authority);
    event_emitter.emit_cpi(&GtUpdated::burned(amount, store.gt(), Some(&user)))?;

    Ok(())
}

impl RequestGtExchange<'_> {
    fn validate_and_init_exchange_if_needed(&mut self, bump: u8) -> Result<()> {
        match self.exchange.load_init() {
            Ok(mut exchange) => {
                exchange.init(
                    bump,
                    &self.owner.key(),
                    &self.store.key(),
                    &self.vault.key(),
                )?;
                drop(exchange);
                self.exchange.exit(&crate::ID)?;
            }
            Err(Error::AnchorError(err)) => {
                if err.error_code_number != ErrorCode::AccountDiscriminatorAlreadySet as u32 {
                    return Err(Error::AnchorError(err));
                }
            }
            Err(err) => {
                return Err(err);
            }
        }
        require!(
            self.exchange.load()?.is_initialized(),
            CoreError::PreconditionsAreNotMet
        );
        require_keys_eq!(
            *self.exchange.load()?.owner(),
            self.owner.key(),
            CoreError::OwnerMismatched,
        );
        require_keys_eq!(
            *self.exchange.load()?.store(),
            self.store.key(),
            CoreError::StoreMismatched,
        );
        Ok(())
    }
}

/// The accounts definition for [`confirm_gt_exchange_vault_v2`](crate::confirm_gt_exchange_vault_v2) instruction.
#[event_cpi]
#[derive(Accounts)]
pub struct ConfirmGtExchangeVault<'info> {
    /// Authority.
    pub authority: Signer<'info>,
    /// Store.
    #[account(
        mut,
        constraint = store.load()?.gt().is_initialized() @ CoreError::PreconditionsAreNotMet,
    )]
    pub store: AccountLoader<'info, Store>,
    #[account(
        mut,
        constraint = vault.load()?.is_initialized() @ CoreError::InvalidUserAccount,
        has_one = store,
        seeds = [
            GtExchangeVault::SEED,
            store.key().as_ref(),
            &vault.load()?.time_window_index().to_le_bytes(),
            &vault.load()?.time_window_u32().to_le_bytes(),
        ],
        bump = vault.load()?.bump,
    )]
    pub vault: AccountLoader<'info, GtExchangeVault>,
}

/// CHECK: only GT_CONTROLLER is authorized to use this instruction.
pub(crate) fn unchecked_confirm_gt_exchange_vault(
    ctx: Context<ConfirmGtExchangeVault>,
    buyback_value: Option<u128>,
    buyback_price: Option<u128>,
) -> Result<()> {
    let mut store = ctx.accounts.store.load_mut()?;
    let mut vault = ctx.accounts.vault.load_mut()?;
    let buyback_amount = store
        .gt_mut()
        .unchecked_confirm_exchange_vault(&mut vault)?;

    let event_emitter = EventEmitter::new(&ctx.accounts.event_authority, ctx.bumps.event_authority);
    // Since no GT is minted, the rewarded amount is zero.
    event_emitter.emit_cpi(&GtUpdated::rewarded(0, store.gt(), None))?;
    event_emitter.emit_cpi(&GtBuyback::new(
        &vault.store,
        &ctx.accounts.vault.key(),
        ctx.accounts.authority.key,
        buyback_amount,
        buyback_value,
        buyback_price,
    )?)?;
    Ok(())
}

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

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

/// The accounts definition for [`close_gt_exchange`](crate::close_gt_exchange) instruction.
#[derive(Accounts)]
pub struct CloseGtExchange<'info> {
    pub authority: Signer<'info>,
    #[account(
        constraint = store.load()?.gt().is_initialized() @ CoreError::PreconditionsAreNotMet,
    )]
    pub store: AccountLoader<'info, Store>,
    /// CHECK: only used to receive the funds.
    #[account(mut)]
    pub owner: UncheckedAccount<'info>,
    #[account(
        mut,
        constraint = vault.load()?.is_initialized() @ CoreError::InvalidArgument,
        constraint = vault.load()?.is_confirmed() @ CoreError::PreconditionsAreNotMet,
        has_one = store,
    )]
    pub vault: AccountLoader<'info, GtExchangeVault>,
    #[account(
        mut,
        close = owner,
        constraint = exchange.load()?.is_initialized() @ CoreError::InvalidArgument,
        has_one = store,
        has_one = owner,
        has_one = vault,
        seeds = [GtExchange::SEED, vault.key().as_ref(), owner.key().as_ref()],
        bump = exchange.load()?.bump,
    )]
    pub exchange: AccountLoader<'info, GtExchange>,
}

/// CHECK: only GT_CONTROLLER is allowed to use this instruction.
pub(crate) fn unchecked_close_gt_exchange(ctx: Context<CloseGtExchange>) -> Result<()> {
    let vault = ctx.accounts.vault.load()?;
    let exchange = ctx.accounts.exchange.load()?;
    msg!(
        "[GT] Closing confirmed exchange: vault_index = {}, vault = {}, owner = {}, amount = {}",
        vault.time_window_index(),
        exchange.vault(),
        exchange.owner(),
        exchange.amount()
    );
    Ok(())
}

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

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