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
//! Claim bond
//! This instruction allows a buyer to claim a bond once it has been signed by enough DAO members.
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
    account_info::{next_account_info, AccountInfo},
    entrypoint::ProgramResult,
    msg,
    program::{invoke, invoke_signed},
    program_error::ProgramError,
    pubkey::Pubkey,
};

use crate::state::{BondAccount, StakePool, BOND_SIGNER_THRESHOLD, V1_INSTRUCTIONS_ALLOWED};
use crate::{error::AccessError, state::Tag};
use bonfida_utils::{BorshSize, InstructionsAccount};
use spl_token;
use crate::instruction::ProgramInstruction::ClaimBond;

use crate::utils::{assert_bond_derivation, check_account_key, check_account_owner, check_signer};
use crate::state:: CentralStateV2;

#[derive(BorshDeserialize, BorshSerialize, BorshSize)]
/// The required parameters for the `claim_bond` instruction
pub struct Params {}

#[derive(InstructionsAccount)]
/// The required accounts for the `claim_bond_rewards` instruction
pub struct Accounts<'a, T> {
    /// The bond account
    #[cons(writable)]
    pub bond_account: &'a T,

    /// The account of the bond buyer
    #[cons(signer)]
    pub buyer: &'a T,

    /// The token account used to purchase the bond
    #[cons(writable)]
    pub quote_token_source: &'a T,

    /// The token account where the sell proceed is sent
    #[cons(writable)]
    pub quote_token_destination: &'a T,

    /// The stake pool account
    #[cons(writable)]
    pub stake_pool: &'a T,

    /// The mint of the ACCESS token
    #[cons(writable)]
    pub access_mint: &'a T,

    /// The vault of the stake pool
    #[cons(writable)]
    pub pool_vault: &'a T,

    /// The central state account
    #[cons(writable)]
    pub central_state: &'a T,

    /// The SPL token program account
    pub spl_token_program: &'a T,
}

impl<'a, 'b: 'a> Accounts<'a, AccountInfo<'b>> {
    pub fn parse(
        accounts: &'a [AccountInfo<'b>],
        program_id: &Pubkey,
    ) -> Result<Self, ProgramError> {
        let accounts_iter = &mut accounts.iter();
        let accounts = Accounts {
            bond_account: next_account_info(accounts_iter)?,
            buyer: next_account_info(accounts_iter)?,
            quote_token_source: next_account_info(accounts_iter)?,
            quote_token_destination: next_account_info(accounts_iter)?,
            stake_pool: next_account_info(accounts_iter)?,
            access_mint: next_account_info(accounts_iter)?,
            pool_vault: next_account_info(accounts_iter)?,
            central_state: next_account_info(accounts_iter)?,
            spl_token_program: next_account_info(accounts_iter)?,
        };

        // Check keys
        check_account_key(
            accounts.spl_token_program,
            &spl_token::id(),
            AccessError::WrongSplTokenProgramId,
        )?;

        // Check ownership
        check_account_owner(accounts.bond_account, program_id, AccessError::WrongOwner)?;
        check_account_owner(accounts.stake_pool, program_id, AccessError::WrongOwner)?;
        check_account_owner(accounts.central_state, program_id, AccessError::WrongOwner)?;

        Ok(accounts)
    }
}

pub fn process_claim_bond(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    _params: Params,
) -> ProgramResult {
    if !V1_INSTRUCTIONS_ALLOWED {
        return Err(AccessError::DeprecatedInstruction.into());
    }

    let accounts = Accounts::parse(accounts, program_id)?;
    let mut bond = BondAccount::from_account_info(accounts.bond_account, true)?;
    let mut central_state = CentralStateV2::from_account_info(accounts.central_state)?;
    central_state.assert_instruction_allowed(&ClaimBond)?;
    let mut stake_pool = StakePool::get_checked(accounts.stake_pool, vec![Tag::StakePool])?;

    check_account_key(
        accounts.stake_pool,
        &bond.stake_pool,
        AccessError::WrongStakePool,
    )?;
    check_account_key(
        accounts.access_mint,
        &central_state.token_mint,
        AccessError::WrongMint,
    )?;
    check_account_key(
        accounts.quote_token_destination,
        &bond.seller_token_account,
        AccessError::WrongQuoteDestination,
    )?;
    check_account_key(
        accounts.pool_vault,
        &Pubkey::from(stake_pool.header.vault),
        AccessError::StakePoolVaultMismatch,
    )?;

    if bond.sellers.len() < BOND_SIGNER_THRESHOLD as usize {
        msg!("Not enough sellers have signed");
        return Err(AccessError::NotEnoughSellers.into());
    }

    if (stake_pool.header.current_day_idx as u64) < central_state.get_current_offset()? {
        return Err(AccessError::PoolMustBeCranked.into());
    }

    // If there is a quote amount we need the buyer to sign the transaction, otherwise it can be permissionless
    if bond.total_quote_amount > 0 {
        assert_bond_derivation(
            accounts.bond_account,
            accounts.buyer.key,
            bond.total_amount_sold,
            program_id,
        )?;
        msg!("Checking buyer signature");
        // Check signer
        check_signer(accounts.buyer, AccessError::BuyerMustSign)?;
        // Transfer tokens
        let transfer_ix = spl_token::instruction::transfer(
            &spl_token::ID,
            accounts.quote_token_source.key,
            accounts.quote_token_destination.key,
            accounts.buyer.key,
            &[],
            bond.total_quote_amount,
        )?;
        invoke(
            &transfer_ix,
            &[
                accounts.spl_token_program.clone(),
                accounts.quote_token_destination.clone(),
                accounts.quote_token_source.clone(),
                accounts.buyer.clone(),
            ],
        )?;
    }

    // Activate the bond account
    bond.activate(central_state.last_snapshot_offset)?;

    bond.save(&mut accounts.bond_account.data.borrow_mut())?;

    // Mint ACCESS tokens into the pool vault
    let mint_ix = spl_token::instruction::mint_to(
        &spl_token::ID,
        accounts.access_mint.key,
        accounts.pool_vault.key,
        accounts.central_state.key,
        &[],
        bond.total_amount_sold,
    )?;

    invoke_signed(
        &mint_ix,
        &[
            accounts.spl_token_program.clone(),
            accounts.access_mint.clone(),
            accounts.pool_vault.clone(),
            accounts.central_state.clone(),
        ],
        &[&[&program_id.to_bytes(), &[central_state.bump_seed]]],
    )?;

    stake_pool.header.deposit(bond.total_amount_sold)?;

    // Update central state
    central_state.total_staked = central_state
        .total_staked
        .checked_add(bond.total_amount_sold)
        .ok_or(AccessError::Overflow)?;
    central_state.save(&mut accounts.central_state.data.borrow_mut())?;

    Ok(())
}