crate-token 0.6.0

Fractional ownership of a basket of fungible assets.
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
//! Crate Token.
#![deny(rustdoc::all)]
#![allow(rustdoc::missing_doc_code_examples)]

mod account_validators;
mod macros;

pub mod events;
pub mod state;

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

use events::*;
pub use state::*;

declare_id!("CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs");

/// Address where fees are sent to.
pub static FEE_TO_ADDRESS: Pubkey = static_pubkey!("AAqAKWdsUPepSgXf7Msbp1pQ7yCPgYkBvXmNfTFBGAqp");

/// Issuance fee as a portion of the crate's fee, in bps.
pub static ISSUE_FEE_BPS: u16 = 2_000;

/// Withdraw fee as a portion of the crate's fee, in bps.
pub static WITHDRAW_FEE_BPS: u16 = 2_000;

/// Maximum fee for anything.
pub const MAX_FEE_BPS: u16 = 10_000;

/// [crate_token] program.
#[program]
pub mod crate_token {
    use super::*;

    /// Provisions a new Crate.
    #[access_control(ctx.accounts.validate())]
    pub fn new_crate(ctx: Context<NewCrate>, _bump: u8) -> Result<()> {
        let info = &mut ctx.accounts.crate_token;
        info.mint = ctx.accounts.crate_mint.key();
        info.bump = unwrap_bump!(ctx, "crate_token");

        info.fee_to_setter = ctx.accounts.fee_to_setter.key();
        info.fee_setter_authority = ctx.accounts.fee_setter_authority.key();
        info.issue_authority = ctx.accounts.issue_authority.key();
        info.withdraw_authority = ctx.accounts.withdraw_authority.key();
        info.author_fee_to = ctx.accounts.author_fee_to.key();

        info.issue_fee_bps = 0;
        info.withdraw_fee_bps = 0;

        emit!(NewCrateEvent {
            issue_authority: ctx.accounts.issue_authority.key(),
            withdraw_authority: ctx.accounts.withdraw_authority.key(),
            crate_key: ctx.accounts.crate_token.key(),
        });

        Ok(())
    }

    /// Set the issue fee.
    /// Only the `fee_setter_authority` can call this.
    #[access_control(ctx.accounts.validate())]
    pub fn set_issue_fee(ctx: Context<SetFees>, issue_fee_bps: u16) -> Result<()> {
        invariant!(issue_fee_bps <= MAX_FEE_BPS, MaxFeeExceeded);
        let crate_token = &mut ctx.accounts.crate_token;
        crate_token.issue_fee_bps = issue_fee_bps;
        Ok(())
    }

    /// Set the withdraw fee.
    /// Only the `fee_setter_authority` can call this.
    #[access_control(ctx.accounts.validate())]
    pub fn set_withdraw_fee(ctx: Context<SetFees>, withdraw_fee_bps: u16) -> Result<()> {
        invariant!(withdraw_fee_bps <= MAX_FEE_BPS, MaxFeeExceeded);
        let crate_token = &mut ctx.accounts.crate_token;
        crate_token.withdraw_fee_bps = withdraw_fee_bps;
        Ok(())
    }

    /// Set the next recipient of the fees.
    /// Only the `fee_to_setter` can call this.
    #[access_control(ctx.accounts.validate())]
    pub fn set_fee_to(ctx: Context<SetFeeTo>) -> Result<()> {
        let crate_token = &mut ctx.accounts.crate_token;
        crate_token.author_fee_to = ctx.accounts.author_fee_to.key();
        Ok(())
    }

    /// Sets who can change who sets the fees.
    /// Only the `fee_to_setter` can call this.
    #[access_control(ctx.accounts.validate())]
    pub fn set_fee_to_setter(ctx: Context<SetFeeToSetter>) -> Result<()> {
        let crate_token = &mut ctx.accounts.crate_token;
        crate_token.fee_to_setter = ctx.accounts.next_fee_to_setter.key();
        Ok(())
    }

    /// Issues Crate tokens.
    /// Only the `issue_authority` can call this.
    #[access_control(ctx.accounts.validate())]
    pub fn issue(ctx: Context<Issue>, amount: u64) -> Result<()> {
        // Do nothing if there is a zero amount.
        if amount == 0 {
            return Ok(());
        }

        let seeds: &[&[u8]] = gen_crate_signer_seeds!(ctx.accounts.crate_token);
        let crate_token = &ctx.accounts.crate_token;
        let state::Fees {
            amount,
            author_fee,
            protocol_fee,
        } = crate_token.apply_issue_fee(amount)?;

        token::mint_to(
            CpiContext::new_with_signer(
                ctx.accounts.token_program.to_account_info(),
                token::MintTo {
                    mint: ctx.accounts.crate_mint.to_account_info(),
                    to: ctx.accounts.mint_destination.to_account_info(),
                    authority: ctx.accounts.crate_token.to_account_info(),
                },
                &[seeds],
            ),
            amount,
        )?;

        if author_fee > 0 {
            token::mint_to(
                CpiContext::new_with_signer(
                    ctx.accounts.token_program.to_account_info(),
                    token::MintTo {
                        mint: ctx.accounts.crate_mint.to_account_info(),
                        to: ctx.accounts.author_fee_destination.to_account_info(),
                        authority: ctx.accounts.crate_token.to_account_info(),
                    },
                    &[seeds],
                ),
                author_fee,
            )?;
        }

        if protocol_fee > 0 {
            token::mint_to(
                CpiContext::new_with_signer(
                    ctx.accounts.token_program.to_account_info(),
                    token::MintTo {
                        mint: ctx.accounts.crate_mint.to_account_info(),
                        to: ctx.accounts.protocol_fee_destination.to_account_info(),
                        authority: ctx.accounts.crate_token.to_account_info(),
                    },
                    &[seeds],
                ),
                protocol_fee,
            )?;
        }

        emit!(IssueEvent {
            crate_key: ctx.accounts.crate_token.key(),
            destination: ctx.accounts.mint_destination.key(),
            amount,
            author_fee,
            protocol_fee
        });

        Ok(())
    }

    /// Withdraws Crate tokens.
    /// Only the `withdraw_authority` can call this.
    #[access_control(ctx.accounts.validate())]
    pub fn withdraw(ctx: Context<Withdraw>, amount: u64) -> Result<()> {
        // Do nothing if there is a zero amount.
        if amount == 0 {
            return Ok(());
        }

        let token_program = ctx.accounts.token_program.to_account_info();
        let seeds = gen_crate_signer_seeds!(ctx.accounts.crate_token);
        let signer_seeds: &[&[&[u8]]] = &[seeds];
        let crate_token = &ctx.accounts.crate_token;
        let state::Fees {
            amount,
            author_fee,
            protocol_fee,
        } = crate_token.apply_withdraw_fee(amount)?;

        // share
        token::transfer(
            CpiContext::new_with_signer(
                token_program.clone(),
                token::Transfer {
                    from: ctx.accounts.crate_underlying.to_account_info(),
                    to: ctx.accounts.withdraw_destination.to_account_info(),
                    authority: ctx.accounts.crate_token.to_account_info(),
                },
                signer_seeds,
            ),
            amount,
        )?;

        if author_fee > 0 {
            token::transfer(
                CpiContext::new_with_signer(
                    token_program.clone(),
                    token::Transfer {
                        from: ctx.accounts.crate_underlying.to_account_info(),
                        to: ctx.accounts.author_fee_destination.to_account_info(),
                        authority: ctx.accounts.crate_token.to_account_info(),
                    },
                    signer_seeds,
                ),
                author_fee,
            )?;
        }

        if protocol_fee > 0 {
            token::transfer(
                CpiContext::new_with_signer(
                    token_program.clone(),
                    token::Transfer {
                        from: ctx.accounts.crate_underlying.to_account_info(),
                        to: ctx.accounts.protocol_fee_destination.to_account_info(),
                        authority: ctx.accounts.crate_token.to_account_info(),
                    },
                    signer_seeds,
                ),
                protocol_fee,
            )?;
        }

        emit!(WithdrawEvent {
            crate_key: ctx.accounts.crate_token.key(),
            token: ctx.accounts.crate_underlying.mint,
            destination: ctx.accounts.withdraw_destination.key(),
            amount,
            author_fee,
            protocol_fee,
        });

        Ok(())
    }
}

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

/// Accounts for [crate_token::new_crate].
#[derive(Accounts)]
pub struct NewCrate<'info> {
    /// Information about the crate.
    #[account(
        init,
        seeds = [
            b"CrateToken".as_ref(),
            crate_mint.key().to_bytes().as_ref()
        ],
        bump,
        space = 8 + CrateToken::LEN,
        payer = payer
    )]
    pub crate_token: Account<'info, CrateToken>,

    /// [Mint] of the [CrateToken].
    pub crate_mint: Account<'info, Mint>,

    /// The authority that can change who fees go to.
    /// CHECK: Arbitrary input.
    pub fee_to_setter: UncheckedAccount<'info>,

    /// The authority that can set fees.
    /// CHECK: Arbitrary input.
    pub fee_setter_authority: UncheckedAccount<'info>,

    /// The authority that can issue new [CrateToken] tokens.
    /// CHECK: Arbitrary input.
    pub issue_authority: UncheckedAccount<'info>,

    /// The authority that can redeem the [CrateToken] token underlying.
    /// CHECK: Arbitrary input.
    pub withdraw_authority: UncheckedAccount<'info>,

    /// Owner of the author fee accounts.
    /// CHECK: Arbitrary input.
    pub author_fee_to: UncheckedAccount<'info>,

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

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

/// Accounts for [crate_token::set_issue_fee] and [crate_token::set_withdraw_fee].
#[derive(Accounts)]
#[instruction(bump: u8)]
pub struct SetFees<'info> {
    /// Information about the crate.
    #[account(mut)]
    pub crate_token: Account<'info, CrateToken>,

    /// Account that can set the fees.
    pub fee_setter: Signer<'info>,
}

/// Accounts for [crate_token::set_fee_to].
#[derive(Accounts)]
#[instruction(bump: u8)]
pub struct SetFeeTo<'info> {
    /// Information about the crate.
    #[account(mut)]
    pub crate_token: Account<'info, CrateToken>,
    /// Account that can set the fee recipient.
    pub fee_to_setter: Signer<'info>,
    /// Who the fees go to.
    /// CHECK: Arbitrary input.
    pub author_fee_to: UncheckedAccount<'info>,
}

/// Accounts for [crate_token::set_fee_to_setter].
#[derive(Accounts)]
#[instruction(bump: u8)]
pub struct SetFeeToSetter<'info> {
    /// Information about the crate.
    #[account(mut)]
    pub crate_token: Account<'info, CrateToken>,
    /// Account that can set the fee recipient.
    pub fee_to_setter: Signer<'info>,
    /// Who will be able to change the fees next.
    /// CHECK: Arbitrary input.
    pub next_fee_to_setter: UncheckedAccount<'info>,
}

/// Accounts for [crate_token::issue].
#[derive(Accounts)]
pub struct Issue<'info> {
    /// Information about the crate.
    pub crate_token: Account<'info, CrateToken>,

    /// [Mint] of the [CrateToken].
    #[account(mut)]
    pub crate_mint: Account<'info, Mint>,

    /// Authority of the account issuing Crate tokens.
    pub issue_authority: Signer<'info>,

    /// Destination of the minted tokens.
    #[account(mut)]
    pub mint_destination: Account<'info, TokenAccount>,

    /// Destination of the author fee tokens.
    #[account(mut)]
    pub author_fee_destination: Account<'info, TokenAccount>,

    /// Destination of the protocol fee tokens.
    #[account(mut)]
    pub protocol_fee_destination: Account<'info, TokenAccount>,

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

/// Accounts for [crate_token::withdraw].
#[derive(Accounts)]
pub struct Withdraw<'info> {
    /// Information about the crate.
    pub crate_token: Account<'info, CrateToken>,

    /// Crate-owned account of the tokens
    #[account(mut)]
    pub crate_underlying: Account<'info, TokenAccount>,

    /// Authority that can withdraw.
    pub withdraw_authority: Signer<'info>,

    /// Destination of the withdrawn tokens.
    #[account(mut)]
    pub withdraw_destination: Account<'info, TokenAccount>,

    /// Destination of the author fee tokens.
    #[account(mut)]
    pub author_fee_destination: Account<'info, TokenAccount>,

    /// Destination of the protocol fee tokens.
    #[account(mut)]
    pub protocol_fee_destination: Account<'info, TokenAccount>,

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

#[error_code]
/// Error codes.
pub enum ErrorCode {
    #[msg("Maximum fee exceeded.")]
    MaxFeeExceeded,
    #[msg("Freeze authority must either be the issuer or the Crate itself.")]
    InvalidFreezeAuthority,
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_fee_to_address() {
        let (key, bump) = Pubkey::find_program_address(&[b"CrateFees"], &crate::ID);
        assert_eq!(key, FEE_TO_ADDRESS);
        assert_eq!(bump, 254);
    }
}