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
//! Holds tokens to allow one depositor to mine multiple quarries at the same time.
#![deny(rustdoc::all)]
#![allow(rustdoc::missing_doc_code_examples)]

#[macro_use]
mod macros;

mod account_validators;
mod processor;
use processor::*;

pub(crate) mod account_conversions;
pub(crate) mod mm_cpi;

pub mod events;
pub mod state;

use anchor_lang::prelude::*;
use anchor_spl::token::{Mint, Token, TokenAccount};
use vipers::prelude::*;

pub use state::*;

#[cfg(not(feature = "cpi"))]
solana_security_txt::security_txt! {
    name: "Quarry Merge Mine",
    project_url: "https://quarry.so",
    contacts: "email:team@quarry.so",
    policy: "https://github.com/QuarryProtocol/quarry/blob/master/SECURITY.md",

    source_code: "https://github.com/QuarryProtocol/quarry",
    auditors: "Quantstamp"
}

declare_id!("QMMD16kjauP5knBwxNUJRZ1Z5o3deBuFrqVjBVmmqto");

#[deny(clippy::integer_arithmetic, clippy::float_arithmetic)]
#[program]
/// Quarry merge mining program.
pub mod quarry_merge_mine {
    use super::*;

    /// Creates a new [MergePool].
    /// Anyone can call this.
    #[access_control(ctx.accounts.validate())]
    pub fn new_pool(ctx: Context<NewPool>, _bump: u8, _mint_bump: u8) -> Result<()> {
        processor::init::new_pool(ctx)
    }

    /// Creates a new [MergeMiner].
    /// Anyone can call this.
    #[access_control(ctx.accounts.validate())]
    pub fn init_merge_miner(ctx: Context<InitMergeMiner>, _bump: u8) -> Result<()> {
        processor::init::init_merge_miner(ctx)
    }

    /// Initializes a [quarry_mine::Miner] owned by the [MergeMiner].
    #[access_control(ctx.accounts.validate())]
    pub fn init_miner(ctx: Context<InitMiner>, bump: u8) -> Result<()> {
        processor::init::init_miner(ctx, bump)
    }

    // --------------------------------
    // Deposit
    // --------------------------------

    /// Deposits tokens into the [MergeMiner].
    /// Before calling this, the owner should call the [anchor_spl::token::transfer] instruction
    /// to transfer to the [MergeMiner]'s primary token ATA.
    #[access_control(ctx.accounts.validate())]
    pub fn stake_primary_miner(ctx: Context<QuarryStakePrimary>) -> Result<()> {
        processor::deposit::stake_primary_miner(ctx)
    }

    /// Stakes all possible replica tokens into a [quarry_mine::Quarry].
    /// Before calling this, the owner should call [stake_primary_miner] with the tokens
    /// they would like to stake.
    #[access_control(ctx.accounts.validate())]
    pub fn stake_replica_miner(ctx: Context<QuarryStakeReplica>) -> Result<()> {
        processor::deposit::stake_replica_miner(ctx)
    }

    // --------------------------------
    // Withdraw
    // --------------------------------

    /// Withdraws tokens from the [MergeMiner].
    #[access_control(ctx.accounts.validate())]
    pub fn unstake_primary_miner(ctx: Context<QuarryStakePrimary>, amount: u64) -> Result<()> {
        processor::withdraw::unstake_primary_miner(ctx, amount)
    }

    /// Unstakes all of a [MergeMiner]'s replica tokens for a [quarry_mine::Miner].
    #[access_control(ctx.accounts.validate())]
    pub fn unstake_all_replica_miner(ctx: Context<QuarryStakeReplica>) -> Result<()> {
        processor::withdraw::unstake_all_replica_miner(ctx)
    }

    /// Withdraws tokens from the [MergeMiner].
    #[access_control(ctx.accounts.validate())]
    pub fn withdraw_tokens(ctx: Context<WithdrawTokens>) -> Result<()> {
        processor::withdraw::withdraw_tokens(ctx)
    }

    /// Rescues stuck tokens in miners owned by a [MergeMiner].
    #[access_control(ctx.accounts.validate())]
    pub fn rescue_tokens(ctx: Context<RescueTokens>) -> Result<()> {
        processor::rescue_tokens::handler(ctx)
    }

    // --------------------------------
    // Claim
    // --------------------------------

    /// Claims [quarry_mine] rewards on behalf of the [MergeMiner].
    #[access_control(ctx.accounts.validate())]
    pub fn claim_rewards(ctx: Context<ClaimRewards>) -> Result<()> {
        processor::claim::claim_rewards(ctx)
    }
}

// --------------------------------
// Instruction account structs
// --------------------------------

/// [quarry_merge_mine::new_pool] accounts
#[derive(Accounts)]
pub struct NewPool<'info> {
    /// [MergePool].
    #[account(
        init,
        seeds = [
          b"MergePool".as_ref(),
          primary_mint.key().to_bytes().as_ref()
        ],
        bump,
        payer = payer,
        space = 8 + MergePool::LEN
    )]
    pub pool: Account<'info, MergePool>,

    /// [Mint] of the primary (underlying) token.
    pub primary_mint: Account<'info, Mint>,

    /// [Mint] of the replica token.
    #[account(
        init,
        seeds = [
            b"ReplicaMint".as_ref(),
            pool.key().to_bytes().as_ref()
        ],
        mint::decimals = primary_mint.decimals,
        mint::authority = pool,
        bump,
        payer = payer
    )]
    pub replica_mint: Account<'info, Mint>,

    /// Payer of the created [MergePool].
    #[account(mut)]
    pub payer: Signer<'info>,

    /// [Token] program.
    pub token_program: Program<'info, Token>,

    /// [System] program.
    pub system_program: Program<'info, System>,

    /// [Rent] sysvar.
    pub rent: Sysvar<'info, Rent>,
}

/// [quarry_merge_mine::init_merge_miner] accounts
#[derive(Accounts)]
pub struct InitMergeMiner<'info> {
    /// [MergePool] of the underlying LP token.
    pub pool: Account<'info, MergePool>,

    /// Owner of the [MergeMiner].
    /// CHECK: Ok
    pub owner: UncheckedAccount<'info>,

    /// [MergeMiner].
    #[account(
        init,
        seeds = [
          b"MergeMiner".as_ref(),
          pool.key().to_bytes().as_ref(),
          owner.key().to_bytes().as_ref()
        ],
        bump,
        payer = payer,
        space = 8 + MergeMiner::LEN
    )]
    pub mm: Account<'info, MergeMiner>,

    /// Payer of the created [MergeMiner].
    #[account(mut)]
    pub payer: Signer<'info>,

    /// System program.
    pub system_program: Program<'info, System>,
}

/// [quarry_merge_mine::init_miner] accounts
#[derive(Accounts)]
pub struct InitMiner<'info> {
    /// The [MergePool].
    pub pool: Account<'info, MergePool>,

    /// The [MergeMiner], aka the authority of the [quarry_mine::Miner].
    pub mm: Account<'info, MergeMiner>,

    /// [quarry_mine::Miner] to be created.
    #[account(mut)]
    pub miner: SystemAccount<'info>,

    /// [quarry_mine::Quarry] to create a [quarry_mine::Miner] for.
    #[account(mut)]
    pub quarry: Box<Account<'info, quarry_mine::Quarry>>,

    /// [quarry_mine::Rewarder].
    pub rewarder: Box<Account<'info, quarry_mine::Rewarder>>,

    /// [Mint] of the Quarry token.
    pub token_mint: Box<Account<'info, Mint>>,

    /// [TokenAccount] holding the token [Mint].
    pub miner_vault: Account<'info, TokenAccount>,

    /// Payer of [quarry_mine::Miner] creation.
    #[account(mut)]
    pub payer: Signer<'info>,

    /// The program at [quarry_mine::ID].
    pub mine_program: Program<'info, quarry_mine::program::QuarryMine>,

    /// System program.
    pub system_program: Program<'info, System>,

    /// SPL Token program.
    pub token_program: Program<'info, Token>,
}

/// [quarry_merge_mine::withdraw_tokens] accounts
#[derive(Accounts)]
pub struct WithdrawTokens<'info> {
    /// Owner of the [MergeMiner].
    pub owner: Signer<'info>,
    /// The [MergePool] to withdraw from.
    pub pool: Account<'info, MergePool>,
    /// The [MergeMiner] to withdraw from.
    #[account(mut)]
    pub mm: Account<'info, MergeMiner>,

    /// The [Mint] being withdrawn from the [MergeMiner].
    pub withdraw_mint: Account<'info, Mint>,
    /// A [TokenAccount] owned by the [MergeMiner] to withdraw from.
    /// Must be the [MergePool::primary_mint] or the [MergePool::replica_mint].
    #[account(mut)]
    pub mm_token_account: Account<'info, TokenAccount>,
    /// Account to send tokens to.
    #[account(mut)]
    pub token_destination: Account<'info, TokenAccount>,

    /// The token program
    pub token_program: Program<'info, Token>,
}

/// [quarry_merge_mine::claim_rewards] accounts
#[derive(Accounts)]
pub struct ClaimRewards<'info> {
    /// Mint wrapper.
    #[account(mut)]
    pub mint_wrapper: Box<Account<'info, quarry_mint_wrapper::MintWrapper>>,
    /// Mint wrapper program.
    pub mint_wrapper_program: Program<'info, quarry_mint_wrapper::program::QuarryMintWrapper>,
    /// [quarry_mint_wrapper::Minter].
    #[account(mut)]
    pub minter: Box<Account<'info, quarry_mint_wrapper::Minter>>,

    /// [Mint] of the [quarry_mine] rewards token.
    #[account(mut)]
    pub rewards_token_mint: Box<Account<'info, Mint>>,

    /// Account to claim rewards for.
    #[account(mut)]
    pub rewards_token_account: Box<Account<'info, TokenAccount>>,

    /// Account to send claim fees to.
    #[account(mut)]
    pub claim_fee_token_account: Box<Account<'info, TokenAccount>>,

    /// Arbitrary account holding the [Mint] of the quarry staked token.
    /// Passed to [quarry_mine] but unused.
    #[account(mut)]
    pub stake_token_account: Box<Account<'info, TokenAccount>>,

    /// User's stake.
    pub stake: QuarryStake<'info>,
}

/// [quarry_merge_mine::stake_primary_miner] accounts
#[derive(Accounts)]
pub struct QuarryStakePrimary<'info> {
    /// The [MergeMiner::owner].
    pub mm_owner: Signer<'info>,

    /// The [TokenAccount] holding the [MergeMiner]'s primary tokens.
    #[account(mut)]
    pub mm_primary_token_account: Account<'info, TokenAccount>,

    /// Staking accounts for the [quarry_mine::Quarry].
    pub stake: QuarryStake<'info>,
}

/// [quarry_merge_mine::stake_replica_miner] accounts
#[derive(Accounts)]
pub struct QuarryStakeReplica<'info> {
    /// The [MergeMiner::owner].
    pub mm_owner: Signer<'info>,

    /// [Mint] of a token that can be staked into a farming program.
    /// This token should not be distributed to users, as it can depeg and can cause minters to lose their funds.
    /// The [MergePool] must be the `mint_authority` and the `freeze_authority`.
    #[account(mut)]
    pub replica_mint: Account<'info, Mint>,

    /// The [TokenAccount] holding the [MergeMiner]'s minted pool tokens.
    #[account(mut)]
    pub replica_mint_token_account: Account<'info, TokenAccount>,

    /// Staking accounts for the [quarry_mine::Quarry].
    pub stake: QuarryStake<'info>,
}

// --------------------------------
// Context Structs
// --------------------------------

/// Staking accounts for a [quarry_mine::Quarry].
#[derive(Accounts)]
pub struct QuarryStake<'info> {
    /// The [MergePool].
    #[account(mut)]
    pub pool: Account<'info, MergePool>,

    /// The [MergeMiner] (also the [quarry_mine::Miner] authority).
    #[account(mut)]
    pub mm: Account<'info, MergeMiner>,

    /// The [quarry_mine::Rewarder] to stake into.
    pub rewarder: Box<Account<'info, quarry_mine::Rewarder>>,

    /// The [quarry_mine::Quarry] to claim from.
    #[account(mut)]
    pub quarry: Box<Account<'info, quarry_mine::Quarry>>,

    /// The [quarry_mine::Miner].
    #[account(mut)]
    pub miner: Box<Account<'info, quarry_mine::Miner>>,

    /// The [TokenAccount] of the [quarry_mine::Miner] that holds the staked tokens.
    #[account(mut)]
    pub miner_vault: Account<'info, TokenAccount>,

    /// [anchor_spl::token] program.
    pub token_program: Program<'info, Token>,

    /// [quarry_mine] program.
    pub mine_program: Program<'info, quarry_mine::program::QuarryMine>,

    /// Unused variable used as a filler for deprecated accounts. Handled by [quarry_mine].
    /// One should pass in a randomly generated Keypair for this account.
    /// CHECK: OK
    #[account(mut)]
    pub unused_account: UncheckedAccount<'info>,
}

/// Error Codes
#[error_code]
pub enum ErrorCode {
    #[msg("Unauthorized.")]
    Unauthorized,
    #[msg("Insufficient balance.")]
    InsufficientBalance,
    #[msg("Invalid miner for the given quarry.")]
    InvalidMiner,
    #[msg("Cannot withdraw a replica mint.")]
    CannotWithdrawReplicaMint,
    #[msg("User must first withdraw from all replica quarries.")]
    OutstandingReplicaTokens,
}