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
use {
    crate::{constants::*, state::*},
    anchor_lang::prelude::*,
    anchor_spl::{
        associated_token::AssociatedToken,
        token::{Mint, Token, TokenAccount},
    },
};

#[derive(Accounts)]
pub struct DelegationCreate<'info> {
    #[account(mut)]
    pub authority: Signer<'info>,

    #[account(address = Config::pubkey())]
    pub config: AccountLoader<'info, Config>,

    #[account(
        init,
        seeds = [
            SEED_DELEGATION,
            worker.key().as_ref(),
            worker.total_delegations.to_be_bytes().as_ref(),
        ],
        bump,
        payer = authority,
        space = 8 + Delegation::INIT_SPACE,
    )]
    pub delegation: Account<'info, Delegation>,

    #[account(
        init,
        payer = authority,
        associated_token::authority = delegation,
        associated_token::mint = mint,
    )]
    pub delegation_tokens: Account<'info, TokenAccount>,

    #[account(address = config.load()?.mint)]
    pub mint: Account<'info, Mint>,

    #[account(
        mut,
        seeds = [
            SEED_WORKER,
            worker.id.to_be_bytes().as_ref(),
        ],
        bump
    )]
    pub worker: Account<'info, Worker>,

    pub token_program: Program<'info, Token>,

    pub associated_token_program: Program<'info, AssociatedToken>,

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

pub fn handler(ctx: Context<DelegationCreate>) -> Result<()> {
    // Get accounts
    let authority = &ctx.accounts.authority;
    let delegation = &mut ctx.accounts.delegation;
    let worker = &mut ctx.accounts.worker;

    // Initialize the delegation account.
    delegation.init(authority.key(), worker.total_delegations, worker.key())?;

    // Increment the worker's total delegations counter.
    worker.total_delegations += 1;

    Ok(())
}