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
use {
    crate::state::*,
    anchor_lang::prelude::*,
    anchor_spl::token::{self, CloseAccount, Mint, Token, TokenAccount},
    hpl_currency_manager::{
        cpi::{
            accounts::{FundAccount, TransferCurrency},
            fund_account, transfer_currency,
        },
        program::HplCurrencyManager,
        state::{Currency, HolderAccount},
    },
    hpl_hive_control::state::{DelegateAuthority, Project},
};

/// Accounts used in withdraw rewards instruction
#[derive(Accounts)]
pub struct WithdrawRewards<'info> {
    /// StakingPool state account
    #[account(mut, has_one = project, has_one = currency)]
    pub staking_pool: Box<Account<'info, StakingPool>>,

    #[account(has_one = mint)]
    pub currency: Box<Account<'info, Currency>>,

    #[account()]
    pub mint: Box<Account<'info, Mint>>,

    #[account(mut, has_one = currency, constraint = vault_holder_account.token_account == vault_token_account.key() && vault_holder_account.owner == staking_pool.key())]
    pub vault_holder_account: Box<Account<'info, HolderAccount>>,

    #[account(mut)]
    pub vault_token_account: Box<Account<'info, TokenAccount>>,

    #[account(has_one = currency, has_one = token_account)]
    pub holder_account: Account<'info, HolderAccount>,

    #[account(mut)]
    pub token_account: Account<'info, TokenAccount>,

    /// The wallet that holds authority for this action
    #[account()]
    pub authority: Signer<'info>,

    /// The wallet that pays for the rent
    #[account(mut)]
    pub payer: Signer<'info>,

    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(address = anchor_lang::solana_program::sysvar::instructions::ID)]
    pub instructions_sysvar: AccountInfo<'info>,

    /// NATIVE SYSTEM PROGRAM
    pub system_program: Program<'info, System>,

    /// NATIVE TOKEN PROGRAM
    pub token_program: Program<'info, Token>,

    // HIVE CONTROL
    #[account(mut)]
    pub project: Box<Account<'info, Project>>,
    #[account(has_one = authority)]
    pub delegate_authority: Option<Account<'info, DelegateAuthority>>,
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(mut)]
    pub vault: AccountInfo<'info>,
    pub currency_manager_program: Program<'info, HplCurrencyManager>,
}

/// Withdraw rewards
pub fn withdraw_rewards(ctx: Context<WithdrawRewards>, amount: u64) -> Result<()> {
    let pool_seeds = &[
        b"staking_pool".as_ref(),
        ctx.accounts.staking_pool.project.as_ref(),
        ctx.accounts.staking_pool.key.as_ref(),
        &[ctx.accounts.staking_pool.bump],
    ];
    let pool_signer = &[&pool_seeds[..]];
    transfer_currency(
        CpiContext::new_with_signer(
            ctx.accounts.currency_manager_program.to_account_info(),
            TransferCurrency {
                project: ctx.accounts.project.to_account_info(),
                currency: ctx.accounts.currency.to_account_info(),
                mint: ctx.accounts.mint.to_account_info(),
                sender_holder_account: ctx.accounts.vault_holder_account.to_account_info(),
                sender_token_account: ctx.accounts.vault_token_account.to_account_info(),
                receiver_holder_account: ctx.accounts.holder_account.to_account_info(),
                receiver_token_account: ctx.accounts.token_account.to_account_info(),
                owner: ctx.accounts.staking_pool.to_account_info(),
                authority: ctx.accounts.staking_pool.to_account_info(),
                vault: ctx.accounts.vault.to_account_info(),
                instructions_sysvar: ctx.accounts.instructions_sysvar.to_account_info(),
                system_program: ctx.accounts.system_program.to_account_info(),
                token_program: ctx.accounts.token_program.to_account_info(),
            },
            pool_signer,
        ),
        amount,
    )?;
    Ok(())
}

/// Accounts used in withdraw rewards instruction
#[derive(Accounts)]
pub struct MigrateVault<'info> {
    // HIVE CONTROL
    #[account(mut, has_one = authority)]
    pub project: Box<Account<'info, Project>>,

    /// StakingPool state account
    #[account(mut, has_one = project)]
    pub staking_pool: Box<Account<'info, StakingPool>>,

    #[account(has_one = project, has_one = mint)]
    pub currency: Box<Account<'info, Currency>>,

    /// Mint address of the reward token
    #[account(mut, constraint = mint.key() == staking_pool.currency)]
    pub mint: Box<Account<'info, Mint>>,

    /// Reward Vault
    #[account(mut, constraint = reward_vault.key() == staking_pool.temp_place_holder_2)]
    pub reward_vault: Account<'info, TokenAccount>,

    #[account(has_one = currency, constraint = vault_holder_account.token_account == vault_token_account.key() && vault_holder_account.owner == staking_pool.key())]
    pub vault_holder_account: Box<Account<'info, HolderAccount>>,

    #[account(mut)]
    pub vault_token_account: Box<Account<'info, TokenAccount>>,

    /// The wallet that holds authority for this action
    #[account()]
    pub authority: Signer<'info>,

    /// The wallet that pays for the rent
    #[account(mut)]
    pub payer: Signer<'info>,

    /// NATIVE SYSTEM PROGRAM
    pub system_program: Program<'info, System>,

    /// NATIVE TOKEN PROGRAM
    pub token_program: Program<'info, Token>,

    #[account(has_one = authority)]
    pub delegate_authority: Option<Account<'info, DelegateAuthority>>,
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(mut)]
    pub vault: AccountInfo<'info>,
    pub currency_manager_program: Program<'info, HplCurrencyManager>,
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(address = anchor_lang::solana_program::sysvar::instructions::ID)]
    pub instructions_sysvar: AccountInfo<'info>,
}

/// Withdraw rewards
pub fn migrate_vault(ctx: Context<MigrateVault>) -> Result<()> {
    let pool_seeds = &[
        b"staking_pool".as_ref(),
        ctx.accounts.staking_pool.project.as_ref(),
        ctx.accounts.staking_pool.key.as_ref(),
        &[ctx.accounts.staking_pool.bump],
    ];
    let pool_signer = &[&pool_seeds[..]];

    fund_account(
        CpiContext::new_with_signer(
            ctx.accounts.currency_manager_program.to_account_info(),
            FundAccount {
                project: ctx.accounts.project.to_account_info(),
                currency: ctx.accounts.currency.to_account_info(),
                mint: ctx.accounts.mint.to_account_info(),
                holder_account: ctx.accounts.vault_holder_account.to_account_info(),
                token_account: ctx.accounts.vault_token_account.to_account_info(),
                source_token_account: ctx.accounts.reward_vault.to_account_info(),
                wallet: ctx.accounts.staking_pool.to_account_info(),
                authority: ctx.accounts.staking_pool.to_account_info(),
                vault: ctx.accounts.vault.to_account_info(),
                system_program: ctx.accounts.system_program.to_account_info(),
                token_program: ctx.accounts.token_program.to_account_info(),
                instructions_sysvar: ctx.accounts.instructions_sysvar.to_account_info(),
            },
            pool_signer,
        ),
        ctx.accounts.reward_vault.amount,
    )?;

    token::close_account(CpiContext::new_with_signer(
        ctx.accounts.token_program.to_account_info(),
        CloseAccount {
            account: ctx.accounts.reward_vault.to_account_info(),
            destination: ctx.accounts.authority.to_account_info(),
            authority: ctx.accounts.staking_pool.to_account_info(),
        },
        pool_signer,
    ))?;

    ctx.accounts.staking_pool.currency = ctx.accounts.currency.key();

    Ok(())
}

/// Accounts used in fund rewards instruction
#[derive(Accounts)]
pub struct ClaimRewards<'info> {
    /// StakingPool state account
    #[account(mut, has_one = project, has_one = currency)]
    pub staking_pool: Box<Account<'info, StakingPool>>,

    /// Multpliers state account
    #[account(has_one = staking_pool)]
    pub multipliers: Option<Account<'info, Multipliers>>,

    /// NFT state account
    #[account(mut, has_one = staking_pool, has_one = staker)]
    pub nft: Box<Account<'info, NFT>>,

    #[account(has_one = mint)]
    pub currency: Box<Account<'info, Currency>>,

    #[account(mut)]
    pub mint: Box<Account<'info, Mint>>,

    #[account(mut, has_one = currency, constraint = vault_holder_account.token_account == vault_token_account.key() && vault_holder_account.owner == staking_pool.key())]
    pub vault_holder_account: Box<Account<'info, HolderAccount>>,

    #[account(mut)]
    pub vault_token_account: Box<Account<'info, TokenAccount>>,

    #[account(has_one = currency, has_one = token_account, constraint = holder_account.owner == wallet.key())]
    pub holder_account: Account<'info, HolderAccount>,

    #[account(mut)]
    pub token_account: Account<'info, TokenAccount>,

    /// Staker state account
    #[account(mut, has_one = staking_pool, has_one = wallet)]
    pub staker: Account<'info, Staker>,

    /// The wallet that pays for the rent
    #[account(mut)]
    pub wallet: Signer<'info>,

    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(address = anchor_lang::solana_program::sysvar::instructions::ID)]
    pub instructions_sysvar: AccountInfo<'info>,
    /// NATIVE SYSTEM PROGRAM
    pub system_program: Program<'info, System>,

    /// NATIVE TOKEN PROGRAM
    pub token_program: Program<'info, Token>,

    /// SYSVAR CLOCK
    pub clock: Sysvar<'info, Clock>,

    // HIVE CONTROL
    #[account(mut)]
    pub project: Box<Account<'info, Project>>,
    /// CHECK: This is not dangerous because we don't read or write from this account
    #[account(mut)]
    pub vault: AccountInfo<'info>,
    pub currency_manager_program: Program<'info, HplCurrencyManager>,
}

/// Claim rewards
pub fn claim_rewards(ctx: Context<ClaimRewards>) -> Result<()> {
    let staking_pool = &ctx.accounts.staking_pool;
    let nft = &mut ctx.accounts.nft;

    let mut seconds_elapsed: u64 =
        u64::try_from(ctx.accounts.clock.unix_timestamp - nft.last_claim).unwrap();

    if seconds_elapsed < staking_pool.rewards_duration {
        msg!("Minimum Reward duration not reached yet so rewards not available yet");
        return Ok(());
    }

    if let Some(max_rewards_duration) = staking_pool.max_rewards_duration {
        if max_rewards_duration < seconds_elapsed {
            seconds_elapsed = max_rewards_duration;
        }
    }

    nft.last_claim = ctx.accounts.clock.unix_timestamp;

    let rewards_per_second = staking_pool.rewards_per_duration / staking_pool.rewards_duration;
    let mut rewards_amount = rewards_per_second * seconds_elapsed;

    let mut multplier_decimals: u64 = 1;
    let mut total_multipliers: u64 = multplier_decimals;
    if let Some(multipliers) = &ctx.accounts.multipliers {
        multplier_decimals = 10u64.pow(multipliers.decimals.into());
        total_multipliers = multplier_decimals;

        let mut duration_multiplier = multplier_decimals;
        for multiplier in multipliers.duration_multipliers.iter() {
            match multiplier.multiplier_type {
                MultiplierType::StakeDuration { min_duration } => {
                    if seconds_elapsed < min_duration {
                        duration_multiplier = multiplier.value;
                    } else {
                        break;
                    }
                }
                _ => {}
            }
        }
        duration_multiplier -= multplier_decimals;
        total_multipliers += duration_multiplier;

        let mut count_multiplier = multplier_decimals;
        for multiplier in multipliers.count_multipliers.iter() {
            match multiplier.multiplier_type {
                MultiplierType::NFTCount { min_count } => {
                    if min_count <= ctx.accounts.staker.total_staked {
                        count_multiplier = multiplier.value;
                    } else {
                        break;
                    }
                }
                _ => {}
            }
        }
        count_multiplier -= multplier_decimals;
        total_multipliers += count_multiplier;

        let mut creator_multiplier = multplier_decimals;
        for multiplier in multipliers.creator_multipliers.iter() {
            match multiplier.multiplier_type {
                MultiplierType::Creator { creator } => {
                    if creator == nft.creator {
                        creator_multiplier = multiplier.value;
                        break;
                    }
                }
                _ => {}
            }
        }
        creator_multiplier -= multplier_decimals;
        total_multipliers += creator_multiplier;

        let mut collection_multiplier = multplier_decimals;
        for multiplier in multipliers.collection_multipliers.iter() {
            match multiplier.multiplier_type {
                MultiplierType::Collection { collection } => {
                    if collection == nft.collection {
                        collection_multiplier = multiplier.value;
                        break;
                    }
                }
                _ => {}
            }
        }
        collection_multiplier -= multplier_decimals;
        total_multipliers += collection_multiplier;
    }

    rewards_amount = (rewards_amount * total_multipliers) / multplier_decimals;

    let pool_seeds = &[
        b"staking_pool".as_ref(),
        staking_pool.project.as_ref(),
        staking_pool.key.as_ref(),
        &[ctx.accounts.staking_pool.bump],
    ];
    let pool_signer = &[&pool_seeds[..]];

    transfer_currency(
        CpiContext::new_with_signer(
            ctx.accounts.currency_manager_program.to_account_info(),
            TransferCurrency {
                project: ctx.accounts.project.to_account_info(),
                currency: ctx.accounts.currency.to_account_info(),
                mint: ctx.accounts.mint.to_account_info(),
                sender_holder_account: ctx.accounts.vault_holder_account.to_account_info(),
                sender_token_account: ctx.accounts.vault_token_account.to_account_info(),
                receiver_holder_account: ctx.accounts.holder_account.to_account_info(),
                receiver_token_account: ctx.accounts.token_account.to_account_info(),
                owner: ctx.accounts.staking_pool.to_account_info(),
                authority: ctx.accounts.staking_pool.to_account_info(),
                vault: ctx.accounts.vault.to_account_info(),
                instructions_sysvar: ctx.accounts.instructions_sysvar.to_account_info(),
                system_program: ctx.accounts.system_program.to_account_info(),
                token_program: ctx.accounts.token_program.to_account_info(),
            },
            pool_signer,
        ),
        rewards_amount,
    )?;
    Ok(())
}