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
use {
    crate::state::*,
    anchor_lang::{prelude::*, solana_program::system_program},
    std::mem::size_of,
};

#[derive(Accounts)]
#[instruction(
    role: Role,
    index_bump: u8,
    namespace_bump: u8
)]
pub struct CreatePaymentNamespace<'info> {
    #[account(
        mut, 
        seeds = [SEED_AUTHORITY], 
        bump = authority.bump,
        owner = crate::ID,
    )]
    pub authority: Account<'info, Authority>,

    #[account(mut)]
    pub index: AccountInfo<'info>,

    #[account(address = index_program::ID)]
    pub index_program: Program<'info, index_program::program::IndexProgram>,

    #[account(
        init,
        seeds = [
            SEED_PAYMENT_NAMESPACE,
            party.key().as_ref(),
            role.to_string().as_bytes()
        ],
        bump = namespace_bump,
        payer = payer,
        space = 8 + size_of::<PaymentNamespace>(),
    )]
    pub namespace: Account<'info, PaymentNamespace>,

    #[account(mut)]
    pub party: AccountInfo<'info>,

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

    #[account(address = system_program::ID)]
    pub system_program: Program<'info, System>,
}

pub fn handler(
    ctx: Context<CreatePaymentNamespace>,
    role: Role,
    index_bump: u8,
    namespace_bump: u8,
) -> ProgramResult {
    // Get accounts.
    let authority = &ctx.accounts.authority;
    let index = &ctx.accounts.index;
    let index_program = &ctx.accounts.index_program;
    let namespace = &mut ctx.accounts.namespace;
    let payer = &ctx.accounts.payer;
    let party = &ctx.accounts.party;
    let system_program = &ctx.accounts.system_program;

    // Initialize namespace account.
    namespace.party = party.key();
    namespace.role = role;
    namespace.bump = namespace_bump;

    // Create an index to lookup payments by (party, role) pairs.
    // (e.g. all the payments where Alice is a creditor or Bob is a debtor)
    index_program::cpi::create_index(
        CpiContext::new_with_signer(
            index_program.to_account_info(),
            index_program::cpi::accounts::CreateIndex {
                index: index.to_account_info(),
                namespace: namespace.to_account_info(),
                owner: authority.to_account_info(),
                payer: payer.to_account_info(),
                system_program: system_program.to_account_info(),
            },
            &[&[SEED_AUTHORITY, &[authority.bump]]],
        ),
        index_bump,
    )
}