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
//! Delegates Quarry Rewarder authority roles.
#![deny(rustdoc::all)]
#![allow(rustdoc::missing_doc_code_examples)]

use anchor_lang::prelude::*;
use quarry_mine::{Quarry, Rewarder};
use vipers::prelude::*;

mod account_validators;
mod macros;

declare_id!("QoP6NfrQbaGnccXQrMLUkog2tQZ4C1RFgJcwDnT8Kmz");

/// Quarry Operator program.
#[program]
pub mod quarry_operator {
    use super::*;

    /// Creates a new [Operator].
    #[access_control(ctx.accounts.validate())]
    pub fn create_operator(ctx: Context<CreateOperator>, _bump: u8) -> Result<()> {
        let operator = &mut ctx.accounts.operator;
        operator.base = ctx.accounts.base.key();
        operator.bump = *unwrap_int!(ctx.bumps.get("operator"));

        operator.rewarder = ctx.accounts.rewarder.key();
        operator.admin = ctx.accounts.admin.key();

        operator.rate_setter = operator.admin;
        operator.quarry_creator = operator.admin;
        operator.share_allocator = operator.admin;
        operator.record_update()?;

        let signer_seeds: &[&[&[u8]]] = &[gen_operator_signer_seeds!(operator)];
        quarry_mine::cpi::accept_authority(CpiContext::new_with_signer(
            ctx.accounts.quarry_mine_program.to_account_info(),
            quarry_mine::cpi::accounts::AcceptAuthority {
                authority: ctx.accounts.operator.to_account_info(),
                rewarder: ctx.accounts.rewarder.to_account_info(),
            },
            signer_seeds,
        ))?;

        Ok(())
    }

    /// Sets the account that can set roles.
    #[access_control(ctx.accounts.validate())]
    pub fn set_admin(ctx: Context<SetRole>) -> Result<()> {
        let operator = &mut ctx.accounts.operator;
        operator.admin = ctx.accounts.delegate.key();
        operator.record_update()?;
        Ok(())
    }

    /// Sets who can call [quarry_mine::quarry_mine::set_annual_rewards].
    #[access_control(ctx.accounts.validate())]
    pub fn set_rate_setter(ctx: Context<SetRole>) -> Result<()> {
        let operator = &mut ctx.accounts.operator;
        operator.rate_setter = ctx.accounts.delegate.key();
        operator.record_update()?;
        Ok(())
    }

    /// Sets who can call [quarry_mine::quarry_mine::create_quarry].
    #[access_control(ctx.accounts.validate())]
    pub fn set_quarry_creator(ctx: Context<SetRole>) -> Result<()> {
        let operator = &mut ctx.accounts.operator;
        operator.quarry_creator = ctx.accounts.delegate.key();
        operator.record_update()?;
        Ok(())
    }

    /// Sets who can call [quarry_mine::quarry_mine::set_rewards_share].
    #[access_control(ctx.accounts.validate())]
    pub fn set_share_allocator(ctx: Context<SetRole>) -> Result<()> {
        let operator = &mut ctx.accounts.operator;
        operator.share_allocator = ctx.accounts.delegate.key();
        operator.record_update()?;
        Ok(())
    }

    /// Calls [quarry_mine::quarry_mine::set_annual_rewards].
    #[access_control(ctx.accounts.validate())]
    pub fn delegate_set_annual_rewards(
        ctx: Context<DelegateSetAnnualRewards>,
        new_rate: u64,
    ) -> Result<()> {
        let operator = &ctx.accounts.with_delegate.operator;
        let signer_seeds: &[&[&[u8]]] = &[gen_operator_signer_seeds!(operator)];
        quarry_mine::cpi::set_annual_rewards(
            CpiContext::new_with_signer(
                ctx.accounts
                    .with_delegate
                    .quarry_mine_program
                    .to_account_info(),
                quarry_mine::cpi::accounts::SetAnnualRewards {
                    auth: ctx.accounts.with_delegate.to_auth_accounts(),
                },
                signer_seeds,
            ),
            new_rate,
        )?;
        Ok(())
    }

    /// Calls [quarry_mine::quarry_mine::create_quarry].
    #[access_control(ctx.accounts.validate())]
    pub fn delegate_create_quarry(ctx: Context<DelegateCreateQuarry>, bump: u8) -> Result<()> {
        let operator = &ctx.accounts.with_delegate.operator;
        let signer_seeds: &[&[&[u8]]] = &[gen_operator_signer_seeds!(operator)];
        quarry_mine::cpi::create_quarry(
            CpiContext::new_with_signer(
                ctx.accounts
                    .with_delegate
                    .quarry_mine_program
                    .to_account_info(),
                quarry_mine::cpi::accounts::CreateQuarry {
                    quarry: ctx.accounts.quarry.to_account_info(),
                    auth: ctx.accounts.with_delegate.to_auth_accounts(),
                    token_mint: ctx.accounts.token_mint.to_account_info(),
                    payer: ctx.accounts.payer.to_account_info(),
                    unused_clock: ctx.accounts.unused_clock.to_account_info(),
                    system_program: ctx.accounts.system_program.to_account_info(),
                },
                signer_seeds,
            ),
            bump,
        )?;
        Ok(())
    }

    /// Calls [quarry_mine::quarry_mine::set_rewards_share].
    #[access_control(ctx.accounts.validate())]
    pub fn delegate_set_rewards_share(
        ctx: Context<DelegateSetRewardsShare>,
        new_share: u64,
    ) -> Result<()> {
        let operator = &ctx.accounts.with_delegate.operator;
        let signer_seeds: &[&[&[u8]]] = &[gen_operator_signer_seeds!(operator)];
        quarry_mine::cpi::set_rewards_share(
            CpiContext::new_with_signer(
                ctx.accounts
                    .with_delegate
                    .quarry_mine_program
                    .to_account_info(),
                quarry_mine::cpi::accounts::SetRewardsShare {
                    auth: ctx.accounts.with_delegate.to_auth_accounts(),
                    quarry: ctx.accounts.quarry.to_account_info(),
                },
                signer_seeds,
            ),
            new_share,
        )?;
        Ok(())
    }

    /// Calls [quarry_mine::quarry_mine::set_famine].
    #[access_control(ctx.accounts.validate())]
    pub fn delegate_set_famine(ctx: Context<DelegateSetFamine>, famine_ts: i64) -> Result<()> {
        let operator = &ctx.accounts.with_delegate.operator;
        let signer_seeds: &[&[&[u8]]] = &[gen_operator_signer_seeds!(operator)];

        quarry_mine::cpi::set_famine(
            CpiContext::new_with_signer(
                ctx.accounts
                    .with_delegate
                    .quarry_mine_program
                    .to_account_info(),
                quarry_mine::cpi::accounts::SetFamine {
                    auth: ctx.accounts.with_delegate.to_readonly_auth_accounts(),
                    quarry: ctx.accounts.quarry.to_account_info(),
                },
                signer_seeds,
            ),
            famine_ts,
        )
    }
}

impl Operator {
    fn record_update(&mut self) -> Result<()> {
        self.last_modified_ts = Clock::get()?.unix_timestamp;
        self.generation = unwrap_int!(self.generation.checked_add(1));
        Ok(())
    }
}

// --------------------------------
// Accounts
// --------------------------------

/// Operator state
#[account]
#[derive(Copy, Default, Debug, PartialEq, Eq)]
pub struct Operator {
    /// The base.
    pub base: Pubkey,
    /// Bump seed.
    pub bump: u8,

    /// The [Rewarder].
    pub rewarder: Pubkey,
    /// Can modify the authorities below.
    pub admin: Pubkey,

    /// Can call [quarry_mine::quarry_mine::set_annual_rewards].
    pub rate_setter: Pubkey,
    /// Can call [quarry_mine::quarry_mine::create_quarry].
    pub quarry_creator: Pubkey,
    /// Can call [quarry_mine::quarry_mine::set_rewards_share].
    pub share_allocator: Pubkey,

    /// When the [Operator] was last modified.
    pub last_modified_ts: i64,
    /// Auto-incrementing sequence number of the set of authorities.
    /// Useful for checking if things were updated.
    pub generation: u64,
}

impl Operator {
    pub const LEN: usize = 32 + 1 + 32 + 32 + 32 + 32 + 32 + 8 + 8;
}

// --------------------------------
// Instructions
// --------------------------------

/// Accounts for [crate::quarry_operator::create_operator].
#[derive(Accounts)]
pub struct CreateOperator<'info> {
    /// Base key used to create the [Operator].
    pub base: Signer<'info>,
    /// Operator PDA.
    #[account(
        init,
        seeds = [
            b"Operator".as_ref(),
            base.key().to_bytes().as_ref()
        ],
        bump,
        payer = payer,
        space = 8 + Operator::LEN
    )]
    pub operator: Account<'info, Operator>,
    /// [Rewarder] of the token.
    #[account(mut)]
    pub rewarder: Box<Account<'info, Rewarder>>,
    /// CHECK: The admin to set.
    pub admin: UncheckedAccount<'info>,
    /// Payer.
    #[account(mut)]
    pub payer: Signer<'info>,
    /// [System] program.
    pub system_program: Program<'info, System>,
    /// Quarry mine
    pub quarry_mine_program: Program<'info, quarry_mine::program::QuarryMine>,
}

/// Accounts for setting roles.
#[derive(Accounts)]
pub struct SetRole<'info> {
    /// The [Operator] of the [Rewarder].
    #[account(mut)]
    pub operator: Account<'info, Operator>,
    /// The [Operator::admin].
    pub admin: Signer<'info>,
    /// The account to give the role to.
    /// CHECK: Ok
    pub delegate: UncheckedAccount<'info>,
}

/// Accounts for [crate::quarry_operator::delegate_set_annual_rewards].
#[derive(Accounts)]
pub struct DelegateSetAnnualRewards<'info> {
    pub with_delegate: WithDelegate<'info>,
}

/// Accounts for [crate::quarry_operator::delegate_create_quarry].
#[derive(Accounts)]
pub struct DelegateCreateQuarry<'info> {
    pub with_delegate: WithDelegate<'info>,
    #[account(mut)]
    pub quarry: SystemAccount<'info>,
    pub token_mint: Box<Account<'info, anchor_spl::token::Mint>>,

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

    /// Unused variable that held the clock. Placeholder.
    /// CHECK: OK
    pub unused_clock: UncheckedAccount<'info>,

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

/// Accounts for [crate::quarry_operator::delegate_set_rewards_share].
#[derive(Accounts)]
pub struct DelegateSetRewardsShare<'info> {
    /// Delegate accounts.
    pub with_delegate: WithDelegate<'info>,
    /// [Quarry].
    #[account(mut)]
    pub quarry: Box<Account<'info, Quarry>>,
}

/// Accounts for [crate::quarry_operator::delegate_set_famine].
#[derive(Accounts)]
pub struct DelegateSetFamine<'info> {
    /// Delegate accounts.
    pub with_delegate: WithDelegate<'info>,
    /// [Quarry].
    #[account(mut)]
    pub quarry: Box<Account<'info, Quarry>>,
}

/// Delegate accounts.
#[derive(Accounts)]
pub struct WithDelegate<'info> {
    /// The [Operator] of the [Rewarder].
    #[account(mut)]
    pub operator: Account<'info, Operator>,
    /// The account to give the role to.
    pub delegate: Signer<'info>,
    /// The [Rewarder].
    #[account(mut)]
    pub rewarder: Box<Account<'info, Rewarder>>,
    /// Quarry mine
    pub quarry_mine_program: Program<'info, quarry_mine::program::QuarryMine>,
}

impl<'info> WithDelegate<'info> {
    /// Creates the [quarry_mine::cpi::accounts::MutableRewarderWithAuthority] accounts.
    pub fn to_auth_accounts(
        &self,
    ) -> quarry_mine::cpi::accounts::MutableRewarderWithAuthority<'info> {
        quarry_mine::cpi::accounts::MutableRewarderWithAuthority {
            authority: self.operator.to_account_info(),
            rewarder: self.rewarder.to_account_info(),
        }
    }

    /// Creates the [quarry_mine::cpi::accounts::MutableRewarderWithAuthority] accounts.
    pub fn to_readonly_auth_accounts(
        &self,
    ) -> quarry_mine::cpi::accounts::ReadOnlyRewarderWithAuthority<'info> {
        quarry_mine::cpi::accounts::ReadOnlyRewarderWithAuthority {
            authority: self.operator.to_account_info(),
            rewarder: self.rewarder.to_account_info(),
        }
    }
}

/// Errors
#[error_code]
pub enum ErrorCode {
    #[msg("Signer is not authorized to perform this action.")]
    Unauthorized,
    #[msg("Pending authority must be set to the created operator.")]
    PendingAuthorityNotSet,
}