jito-priority-fee-distribution 0.1.7

Priority fee distribution program, responsible for distributing funds to entitled parties.
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
use anchor_lang::{prelude::*, solana_program::clock::Clock};
#[cfg(not(feature = "no-entrypoint"))]
use solana_security_txt::security_txt;

use crate::{
    state::{
        ClaimStatus, Config, MerkleRoot, MerkleRootUploadConfig, PriorityFeeDistributionAccount,
    },
    ErrorCode::Unauthorized,
};

#[cfg(not(feature = "no-entrypoint"))]
security_txt! {
    // Required fields
    name: "Jito Priority Fee Program",
    project_url: "https://jito.network/",
    contacts: "email:support@jito.network",
    policy: "https://github.com/jito-foundation/jito-programs",
    // Optional Fields
    preferred_languages: "en",
    source_code: "https://github.com/jito-foundation/jito-programs",
    source_revision: std::env!("GIT_SHA"),
    source_release: std::env!("GIT_REF_NAME")
}

pub mod merkle_proof;
pub mod state;

declare_id!("Priority6weCZ5HwDn29NxLFpb7TDp2iLZ6XKc5e8d3");

#[program]
pub mod jito_priority_fee_distribution {
    use jito_programs_vote_state::VoteState;
    use solana_program::native_token::lamports_to_sol;

    use super::*;
    use crate::ErrorCode::*;

    /// Initialize a singleton instance of the [Config] account.
    pub fn initialize(
        ctx: Context<Initialize>,
        authority: Pubkey,
        expired_funds_account: Pubkey,
        num_epochs_valid: u64,
        max_validator_commission_bps: u16,
        bump: u8,
    ) -> Result<()> {
        let cfg = &mut ctx.accounts.config;
        cfg.authority = authority;
        cfg.expired_funds_account = expired_funds_account;
        cfg.num_epochs_valid = num_epochs_valid;
        cfg.max_validator_commission_bps = max_validator_commission_bps;
        cfg.go_live_epoch = u64::MAX;
        cfg.bump = bump;
        cfg.validate()?;

        Ok(())
    }

    /// Initialize a new [PriorityFeeDistributionAccount] associated with the given validator vote key
    /// and current epoch.
    pub fn initialize_priority_fee_distribution_account(
        ctx: Context<InitializePriorityFeeDistributionAccount>,
        merkle_root_upload_authority: Pubkey,
        validator_commission_bps: u16,
        bump: u8,
    ) -> Result<()> {
        if validator_commission_bps > ctx.accounts.config.max_validator_commission_bps {
            return Err(MaxValidatorCommissionFeeBpsExceeded.into());
        }

        let validator_vote_account_node_pubkey =
            VoteState::deserialize_node_pubkey(&ctx.accounts.validator_vote_account)?;
        if validator_vote_account_node_pubkey != *ctx.accounts.signer.key {
            return Err(Unauthorized.into());
        }

        let current_epoch = Clock::get()?.epoch;

        let distribution_acc = &mut ctx.accounts.priority_fee_distribution_account;
        distribution_acc.validator_vote_account = ctx.accounts.validator_vote_account.key();
        distribution_acc.epoch_created_at = current_epoch;
        distribution_acc.validator_commission_bps = validator_commission_bps;
        distribution_acc.merkle_root_upload_authority = merkle_root_upload_authority;
        distribution_acc.merkle_root = None;
        distribution_acc.expires_at = current_epoch
            .checked_add(ctx.accounts.config.num_epochs_valid)
            .ok_or(ArithmeticError)?;
        distribution_acc.bump = bump;
        distribution_acc.validate()?;

        emit!(PriorityFeeDistributionAccountInitializedEvent {
            priority_fee_distribution_account: distribution_acc.key(),
        });

        Ok(())
    }

    /// Update config fields. Only the [Config] authority can invoke this.
    pub fn update_config(ctx: Context<UpdateConfig>, new_config: Config) -> Result<()> {
        UpdateConfig::auth(&ctx)?;

        let config = &mut ctx.accounts.config;
        config.authority = new_config.authority;
        config.expired_funds_account = new_config.expired_funds_account;
        config.num_epochs_valid = new_config.num_epochs_valid;
        config.max_validator_commission_bps = new_config.max_validator_commission_bps;
        config.go_live_epoch = new_config.go_live_epoch;
        config.validate()?;

        emit!(ConfigUpdatedEvent {
            authority: ctx.accounts.authority.key(),
        });

        Ok(())
    }

    /// Uploads a merkle root to the provided [PriorityFeeDistributionAccount]. This instruction may be
    /// invoked many times as long as the account is at least one epoch old and not expired; and
    /// no funds have already been claimed. Only the `merkle_root_upload_authority` has the
    /// authority to invoke.
    pub fn upload_merkle_root(
        ctx: Context<UploadMerkleRoot>,
        root: [u8; 32],
        max_total_claim: u64,
        max_num_nodes: u64,
    ) -> Result<()> {
        UploadMerkleRoot::auth(&ctx)?;

        let current_epoch = Clock::get()?.epoch;
        let distribution_acc = &mut ctx.accounts.priority_fee_distribution_account;

        if let Some(merkle_root) = &distribution_acc.merkle_root {
            if merkle_root.num_nodes_claimed > 0 {
                return Err(Unauthorized.into());
            }
        }
        if current_epoch <= distribution_acc.epoch_created_at {
            return Err(PrematureMerkleRootUpload.into());
        }

        if current_epoch > distribution_acc.expires_at {
            return Err(ExpiredPriorityFeeDistributionAccount.into());
        }

        distribution_acc.merkle_root = Some(MerkleRoot {
            root,
            max_total_claim,
            max_num_nodes,
            total_funds_claimed: 0,
            num_nodes_claimed: 0,
        });
        distribution_acc.validate()?;

        emit!(MerkleRootUploadedEvent {
            merkle_root_upload_authority: ctx.accounts.merkle_root_upload_authority.key(),
            priority_fee_distribution_account: distribution_acc.key(),
        });

        Ok(())
    }

    /// Anyone can invoke this only after the [PriorityFeeDistributionAccount] has expired.
    /// This instruction will return any rent back to `claimant` and close the account
    pub fn close_claim_status(ctx: Context<CloseClaimStatus>) -> Result<()> {
        let claim_status = &ctx.accounts.claim_status;

        // can only claim after claim_status has expired to prevent draining.
        if Clock::get()?.epoch <= claim_status.expires_at {
            return Err(PrematureCloseClaimStatus.into());
        }

        emit!(ClaimStatusClosedEvent {
            claim_status_payer: ctx.accounts.claim_status_payer.key(),
            claim_status_account: claim_status.key(),
        });

        Ok(())
    }

    /// Anyone can invoke this only after the [PriorityFeeDistributionAccount] has expired.
    /// This instruction will send any unclaimed funds to the designated `expired_funds_account`
    /// before closing and returning the rent exempt funds to the validator.
    pub fn close_priority_fee_distribution_account(
        ctx: Context<ClosePriorityFeeDistributionAccount>,
        _epoch: u64,
    ) -> Result<()> {
        ClosePriorityFeeDistributionAccount::auth(&ctx)?;

        let priority_fee_distribution_account = &mut ctx.accounts.priority_fee_distribution_account;

        if Clock::get()?.epoch <= priority_fee_distribution_account.expires_at {
            return Err(PrematureClosePriorityFeeDistributionAccount.into());
        }

        let expired_amount = PriorityFeeDistributionAccount::claim_expired(
            priority_fee_distribution_account.to_account_info(),
            ctx.accounts.expired_funds_account.to_account_info(),
        )?;
        priority_fee_distribution_account.validate()?;

        emit!(PriorityFeeDistributionAccountClosedEvent {
            expired_funds_account: ctx.accounts.expired_funds_account.key(),
            priority_fee_distribution_account: priority_fee_distribution_account.key(),
            expired_amount,
        });

        Ok(())
    }

    /// Claims tokens from the [PriorityFeeDistributionAccount].
    pub fn claim(ctx: Context<Claim>, _bump: u8, amount: u64, proof: Vec<[u8; 32]>) -> Result<()> {
        Claim::auth(&ctx)?;

        let claim_status = &mut ctx.accounts.claim_status;

        let claimant_account = &mut ctx.accounts.claimant;
        let priority_fee_distribution_account = &mut ctx.accounts.priority_fee_distribution_account;

        let clock = Clock::get()?;
        if clock.epoch > priority_fee_distribution_account.expires_at {
            return Err(ExpiredPriorityFeeDistributionAccount.into());
        }

        let tip_distribution_info = priority_fee_distribution_account.to_account_info();
        let tip_distribution_epoch_expires_at = priority_fee_distribution_account.expires_at;
        let merkle_root = priority_fee_distribution_account
            .merkle_root
            .as_mut()
            .ok_or(RootNotUploaded)?;

        // Verify the merkle proof.
        let node = &solana_program::hash::hashv(&[
            &[0u8],
            &solana_program::hash::hashv(&[
                &claimant_account.key().to_bytes(),
                &amount.to_le_bytes(),
            ])
            .to_bytes(),
        ]);

        if !merkle_proof::verify(proof, merkle_root.root, node.to_bytes()) {
            return Err(InvalidProof.into());
        }

        PriorityFeeDistributionAccount::claim(
            tip_distribution_info,
            claimant_account.to_account_info(),
            amount,
        )?;

        // Mark it claimed.
        claim_status.claim_status_payer = ctx.accounts.payer.key();
        claim_status.expires_at = tip_distribution_epoch_expires_at;

        merkle_root.total_funds_claimed = merkle_root
            .total_funds_claimed
            .checked_add(amount)
            .ok_or(ArithmeticError)?;
        if merkle_root.total_funds_claimed > merkle_root.max_total_claim {
            return Err(ExceedsMaxClaim.into());
        }

        merkle_root.num_nodes_claimed = merkle_root
            .num_nodes_claimed
            .checked_add(1)
            .ok_or(ArithmeticError)?;
        if merkle_root.num_nodes_claimed > merkle_root.max_num_nodes {
            return Err(ExceedsMaxNumNodes.into());
        }

        emit!(ClaimedEvent {
            priority_fee_distribution_account: priority_fee_distribution_account.key(),
            payer: ctx.accounts.payer.key(),
            claimant: claimant_account.key(),
            amount
        });

        priority_fee_distribution_account.validate()?;

        Ok(())
    }

    pub fn initialize_merkle_root_upload_config(
        ctx: Context<InitializeMerkleRootUploadConfig>,
        authority: Pubkey,
        original_authority: Pubkey,
    ) -> Result<()> {
        // Call the authorize function
        InitializeMerkleRootUploadConfig::auth(&ctx)?;

        // Set the bump and override authority
        let merkle_root_upload_config = &mut ctx.accounts.merkle_root_upload_config;
        merkle_root_upload_config.override_authority = authority;
        merkle_root_upload_config.original_upload_authority = original_authority;
        merkle_root_upload_config.bump = ctx.bumps.merkle_root_upload_config;
        Ok(())
    }

    pub fn update_merkle_root_upload_config(
        ctx: Context<UpdateMerkleRootUploadConfig>,
        authority: Pubkey,
        original_authority: Pubkey,
    ) -> Result<()> {
        // Call the authorize function
        UpdateMerkleRootUploadConfig::auth(&ctx)?;

        // Update override authority
        let merkle_root_upload_config = &mut ctx.accounts.merkle_root_upload_config;
        merkle_root_upload_config.override_authority = authority;
        merkle_root_upload_config.original_upload_authority = original_authority;

        Ok(())
    }

    pub fn migrate_tda_merkle_root_upload_authority(
        ctx: Context<MigrateTdaMerkleRootUploadAuthority>,
    ) -> Result<()> {
        let distribution_account = &mut ctx.accounts.priority_fee_distribution_account;
        // Validate TDA has no MerkleRoot uploaded to it
        if distribution_account.merkle_root.is_some() {
            return Err(InvalidTdaForMigration.into());
        }
        // Validate the TDA key is the acceptable original authority (i.e. the original Jito Lab's authority)
        if distribution_account.merkle_root_upload_authority
            != ctx
                .accounts
                .merkle_root_upload_config
                .original_upload_authority
        {
            return Err(InvalidTdaForMigration.into());
        }

        // Change the TDA's root upload authority
        distribution_account.merkle_root_upload_authority =
            ctx.accounts.merkle_root_upload_config.override_authority;

        Ok(())
    }

    pub fn transfer_priority_fee_tips(
        ctx: Context<TransferPriorityFeeTips>,
        lamports: u64,
    ) -> Result<()> {
        let epoch = Clock::get()?.epoch;
        // Valdiate the PFDA is in the current epoch
        require!(
            ctx.accounts
                .priority_fee_distribution_account
                .epoch_created_at
                == epoch,
            ErrorCode::AccountValidationFailure
        );

        ctx.accounts
            .priority_fee_distribution_account
            .increment_total_lamports_transferred(lamports)?;

        let go_live_epoch = ctx.accounts.config.go_live_epoch;
        if go_live_epoch > epoch {
            msg!(
                "Priority fee transfer is not live yet. {}/{} - ({:.5})",
                epoch,
                go_live_epoch,
                lamports_to_sol(lamports)
            );

            return Ok(());
        }

        // Transfer requested lamports from From to PFDA
        let ix = solana_program::system_instruction::transfer(
            ctx.accounts.from.key,
            &ctx.accounts.priority_fee_distribution_account.key(),
            lamports,
        );
        solana_program::program::invoke(
            &ix,
            &[
                ctx.accounts.from.to_account_info(),
                ctx.accounts
                    .priority_fee_distribution_account
                    .to_account_info(),
            ],
        )
        .map_err(Into::into)
    }
}

#[error_code]
pub enum ErrorCode {
    #[msg("Account failed validation.")]
    AccountValidationFailure,

    #[msg("Encountered an arithmetic under/overflow error.")]
    ArithmeticError,

    #[msg("The maximum number of funds to be claimed has been exceeded.")]
    ExceedsMaxClaim,

    #[msg("The maximum number of claims has been exceeded.")]
    ExceedsMaxNumNodes,

    #[msg("The given PriorityFeeDistributionAccount has expired.")]
    ExpiredPriorityFeeDistributionAccount,

    #[msg("The funds for the given index and PriorityFeeDistributionAccount have already been claimed.")]
    FundsAlreadyClaimed,

    #[msg("Supplied invalid parameters.")]
    InvalidParameters,

    #[msg("The given proof is invalid.")]
    InvalidProof,

    #[msg("Failed to deserialize the supplied vote account data.")]
    InvalidVoteAccountData,

    #[msg("Validator's commission basis points must be less than or equal to the Config account's max_validator_commission_bps.")]
    MaxValidatorCommissionFeeBpsExceeded,

    #[msg("The given PriorityFeeDistributionAccount is not ready to be closed.")]
    PrematureClosePriorityFeeDistributionAccount,

    #[msg("The given ClaimStatus account is not ready to be closed.")]
    PrematureCloseClaimStatus,

    #[msg("Must wait till at least one epoch after the tip distribution account was created to upload the merkle root.")]
    PrematureMerkleRootUpload,

    #[msg("No merkle root has been uploaded to the given PriorityFeeDistributionAccount.")]
    RootNotUploaded,

    #[msg("Unauthorized signer.")]
    Unauthorized,

    #[msg("TDA not valid for migration.")]
    InvalidTdaForMigration,
}

#[derive(Accounts)]
pub struct CloseClaimStatus<'info> {
    // bypass seed check since owner check prevents attacker from passing in invalid data
    // account can only be transferred to us if it is zeroed, failing the deserialization check
    #[account(
        mut,
        close = claim_status_payer,
        constraint = claim_status_payer.key() == claim_status.claim_status_payer
    )]
    pub claim_status: Account<'info, ClaimStatus>,

    /// CHECK: This is checked against claim_status in the constraint
    /// Receiver of the funds.
    #[account(mut)]
    pub claim_status_payer: UncheckedAccount<'info>,
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init,
        seeds = [Config::SEED],
        bump,
        payer = initializer,
        space = Config::SIZE,
        rent_exempt = enforce
    )]
    pub config: Account<'info, Config>,

    pub system_program: Program<'info, System>,

    #[account(mut)]
    pub initializer: Signer<'info>,
}

#[derive(Accounts)]
#[instruction(
    _merkle_root_upload_authority: Pubkey,
    _validator_commission_bps: u16,
    _bump: u8
)]
pub struct InitializePriorityFeeDistributionAccount<'info> {
    pub config: Account<'info, Config>,

    #[account(
        init,
        seeds = [
            PriorityFeeDistributionAccount::SEED,
            validator_vote_account.key().as_ref(),
            Clock::get().unwrap().epoch.to_le_bytes().as_ref(),
        ],
        bump,
        payer = signer,
        space = PriorityFeeDistributionAccount::SIZE,
        rent_exempt = enforce
    )]
    pub priority_fee_distribution_account: Account<'info, PriorityFeeDistributionAccount>,

    /// CHECK: Safe because we check the vote program is the owner before deserialization.
    /// The validator's vote account is used to check this transaction's signer is also the authorized withdrawer.
    pub validator_vote_account: AccountInfo<'info>,

    /// Must be equal to the supplied validator vote account's authorized withdrawer.
    #[account(mut)]
    pub signer: Signer<'info>,

    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct UpdateConfig<'info> {
    #[account(mut, rent_exempt = enforce)]
    pub config: Account<'info, Config>,

    #[account(mut)]
    pub authority: Signer<'info>,
}

impl UpdateConfig<'_> {
    fn auth(ctx: &Context<UpdateConfig>) -> Result<()> {
        if ctx.accounts.config.authority != ctx.accounts.authority.key() {
            Err(Unauthorized.into())
        } else {
            Ok(())
        }
    }
}

#[derive(Accounts)]
#[instruction(epoch: u64)]
pub struct ClosePriorityFeeDistributionAccount<'info> {
    pub config: Account<'info, Config>,

    /// CHECK: safe see auth fn
    #[account(mut)]
    pub expired_funds_account: AccountInfo<'info>,

    #[account(
        mut,
        close = validator_vote_account,
        seeds = [
            PriorityFeeDistributionAccount::SEED,
            validator_vote_account.key().as_ref(),
            epoch.to_le_bytes().as_ref(),
        ],
        bump = priority_fee_distribution_account.bump,
    )]
    pub priority_fee_distribution_account: Account<'info, PriorityFeeDistributionAccount>,

    /// CHECK: safe see auth fn
    #[account(mut)]
    pub validator_vote_account: AccountInfo<'info>,

    /// Anyone can crank this instruction.
    #[account(mut)]
    pub signer: Signer<'info>,
}

impl ClosePriorityFeeDistributionAccount<'_> {
    fn auth(ctx: &Context<ClosePriorityFeeDistributionAccount>) -> Result<()> {
        if ctx.accounts.config.expired_funds_account != ctx.accounts.expired_funds_account.key() {
            Err(Unauthorized.into())
        } else {
            Ok(())
        }
    }
}

#[derive(Accounts)]
#[instruction(_bump: u8, _amount: u64, _proof: Vec<[u8; 32]>)]
pub struct Claim<'info> {
    pub config: Account<'info, Config>,

    #[account(mut, rent_exempt = enforce)]
    pub priority_fee_distribution_account: Account<'info, PriorityFeeDistributionAccount>,

    pub merkle_root_upload_authority: Signer<'info>,

    /// Status of the claim. Used to prevent the same party from claiming multiple times.
    #[account(
        init,
        rent_exempt = enforce,
        seeds = [
            ClaimStatus::SEED,
            claimant.key().as_ref(),
            priority_fee_distribution_account.key().as_ref()
        ],
        bump,
        space = ClaimStatus::SIZE,
        payer = payer
    )]
    pub claim_status: Account<'info, ClaimStatus>,

    /// CHECK: This is safe.
    /// Receiver of the funds.
    #[account(mut)]
    pub claimant: AccountInfo<'info>,

    /// Who is paying for the claim.
    #[account(mut)]
    pub payer: Signer<'info>,

    pub system_program: Program<'info, System>,
}
impl Claim<'_> {
    fn auth(ctx: &Context<Claim>) -> Result<()> {
        if ctx.accounts.merkle_root_upload_authority.key()
            != ctx
                .accounts
                .priority_fee_distribution_account
                .merkle_root_upload_authority
        {
            Err(Unauthorized.into())
        } else {
            Ok(())
        }
    }
}

#[derive(Accounts)]
pub struct UploadMerkleRoot<'info> {
    pub config: Account<'info, Config>,

    #[account(mut, rent_exempt = enforce)]
    pub priority_fee_distribution_account: Account<'info, PriorityFeeDistributionAccount>,

    #[account(mut)]
    pub merkle_root_upload_authority: Signer<'info>,
}

impl UploadMerkleRoot<'_> {
    fn auth(ctx: &Context<UploadMerkleRoot>) -> Result<()> {
        if ctx.accounts.merkle_root_upload_authority.key()
            != ctx
                .accounts
                .priority_fee_distribution_account
                .merkle_root_upload_authority
        {
            Err(Unauthorized.into())
        } else {
            Ok(())
        }
    }
}

#[derive(Accounts)]
pub struct InitializeMerkleRootUploadConfig<'info> {
    #[account(mut, rent_exempt = enforce)]
    pub config: Account<'info, Config>,

    #[account(
        init,
        rent_exempt = enforce,
        seeds = [
            MerkleRootUploadConfig::SEED,
        ],
        bump,
        space = MerkleRootUploadConfig::SIZE,
        payer = payer
    )]
    pub merkle_root_upload_config: Account<'info, MerkleRootUploadConfig>,

    pub authority: Signer<'info>,

    #[account(mut)]
    pub payer: Signer<'info>,

    pub system_program: Program<'info, System>,
}

impl InitializeMerkleRootUploadConfig<'_> {
    fn auth(ctx: &Context<InitializeMerkleRootUploadConfig>) -> Result<()> {
        if ctx.accounts.config.authority != ctx.accounts.authority.key() {
            Err(Unauthorized.into())
        } else {
            Ok(())
        }
    }
}

#[derive(Accounts)]
pub struct UpdateMerkleRootUploadConfig<'info> {
    #[account(rent_exempt = enforce)]
    pub config: Account<'info, Config>,

    #[account(
        mut,
        seeds = [MerkleRootUploadConfig::SEED],
        bump,
        rent_exempt = enforce,
    )]
    pub merkle_root_upload_config: Account<'info, MerkleRootUploadConfig>,

    pub authority: Signer<'info>,

    pub system_program: Program<'info, System>,
}

impl UpdateMerkleRootUploadConfig<'_> {
    fn auth(ctx: &Context<UpdateMerkleRootUploadConfig>) -> Result<()> {
        if ctx.accounts.config.authority != ctx.accounts.authority.key() {
            Err(Unauthorized.into())
        } else {
            Ok(())
        }
    }
}

#[derive(Accounts)]
pub struct MigrateTdaMerkleRootUploadAuthority<'info> {
    #[account(mut, rent_exempt = enforce)]
    pub priority_fee_distribution_account: Account<'info, PriorityFeeDistributionAccount>,

    #[account(
        seeds = [MerkleRootUploadConfig::SEED],
        bump,
        rent_exempt = enforce,
    )]
    pub merkle_root_upload_config: Account<'info, MerkleRootUploadConfig>,
}

#[derive(Accounts)]
pub struct TransferPriorityFeeTips<'info> {
    #[account(rent_exempt = enforce)]
    pub config: Account<'info, Config>,

    #[account(
        mut,
        rent_exempt = enforce
    )]
    pub priority_fee_distribution_account: Account<'info, PriorityFeeDistributionAccount>,

    #[account(mut)]
    pub from: Signer<'info>,
    pub system_program: Program<'info, System>,
}

// Events

#[event]
pub struct PriorityFeeDistributionAccountInitializedEvent {
    pub priority_fee_distribution_account: Pubkey,
}

#[event]
pub struct ValidatorCommissionBpsUpdatedEvent {
    pub priority_fee_distribution_account: Pubkey,
    pub old_commission_bps: u16,
    pub new_commission_bps: u16,
}

#[event]
pub struct MerkleRootUploadAuthorityUpdatedEvent {
    pub old_authority: Pubkey,
    pub new_authority: Pubkey,
}

#[event]
pub struct ConfigUpdatedEvent {
    /// Who updated it.
    authority: Pubkey,
}

#[event]
pub struct ClaimedEvent {
    /// [PriorityFeeDistributionAccount] claimed from.
    pub priority_fee_distribution_account: Pubkey,

    /// User that paid for the claim, may or may not be the same as claimant.
    pub payer: Pubkey,

    /// Account that received the funds.
    pub claimant: Pubkey,

    /// Amount of funds to distribute.
    pub amount: u64,
}

#[event]
pub struct MerkleRootUploadedEvent {
    /// Who uploaded the root.
    pub merkle_root_upload_authority: Pubkey,

    /// Where the root was uploaded to.
    pub priority_fee_distribution_account: Pubkey,
}

#[event]
pub struct PriorityFeeDistributionAccountClosedEvent {
    /// Account where unclaimed funds were transferred to.
    pub expired_funds_account: Pubkey,

    /// [PriorityFeeDistributionAccount] closed.
    pub priority_fee_distribution_account: Pubkey,

    /// Unclaimed amount transferred.
    pub expired_amount: u64,
}

#[event]
pub struct ClaimStatusClosedEvent {
    /// Account where funds were transferred to.
    pub claim_status_payer: Pubkey,

    /// [ClaimStatus] account that was closed.
    pub claim_status_account: Pubkey,
}