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
//! Unlock ACCESS tokens bought through a bond account
//! When tokens are unlocked they are withdrawn from the pool and are not considered staked anymore
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
    account_info::{next_account_info, AccountInfo},
    clock::Clock,
    entrypoint::ProgramResult,
    msg,
    program::invoke_signed,
    program_error::ProgramError,
    pubkey::Pubkey,
    sysvar::Sysvar,
};

use crate::state::{BondAccount, StakePool, StakePoolHeader};
use crate::{error::AccessError, state::Tag};
use bonfida_utils::{BorshSize, InstructionsAccount};
use solana_program::program_pack::Pack;
use spl_token::state::Account;
use crate::instruction::ProgramInstruction::UnlockBondTokens;

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 `unlock_bond_tokens` instruction
pub struct Params {}

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

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

    /// The ACCESS mint token
    pub mint: &'a T,

    /// The ACCESS token destination
    #[cons(writable)]
    pub access_token_destination: &'a T,

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

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

    /// The vault of the staking pool
    #[cons(writable)]
    pub pool_vault: &'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)?,
            bond_owner: next_account_info(accounts_iter)?,
            mint: next_account_info(accounts_iter)?,
            access_token_destination: next_account_info(accounts_iter)?,
            central_state: next_account_info(accounts_iter)?,
            stake_pool: next_account_info(accounts_iter)?,
            pool_vault: 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.central_state, program_id, AccessError::WrongOwner)?;
        check_account_owner(accounts.stake_pool, program_id, AccessError::WrongOwner)?;

        // Check signer
        check_signer(accounts.bond_owner, AccessError::BuyerMustSign)?;

        Ok(accounts)
    }
}

pub fn process_unlock_bond_tokens(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    _params: Params,
) -> ProgramResult {
    let accounts = Accounts::parse(accounts, program_id)?;
    let mut central_state = CentralStateV2::from_account_info(accounts.central_state)?;
    central_state.assert_instruction_allowed(&UnlockBondTokens)?;
    let mut bond = BondAccount::from_account_info(accounts.bond_account, false)?;
    let mut stake_pool = StakePool::get_checked(accounts.stake_pool, vec![Tag::StakePool])?;
    let current_time = Clock::get()?.unix_timestamp;

    let destination_token_acc = Account::unpack(&accounts.access_token_destination.data.borrow())?;
    if destination_token_acc.mint != central_state.token_mint {
        msg!("Invalid ACCESS mint");
        #[cfg(not(feature = "no-mint-check"))]
        return Err(AccessError::WrongMint.into());
    }

    assert_bond_derivation(
        accounts.bond_account,
        accounts.bond_owner.key,
        bond.total_amount_sold,
        program_id,
    )?;
    check_account_key(
        accounts.stake_pool,
        &bond.stake_pool,
        AccessError::WrongStakePool,
    )?;
    check_account_key(
        accounts.mint,
        &central_state.token_mint,
        AccessError::WrongMint,
    )?;
    check_account_key(
        accounts.pool_vault,
        &Pubkey::from(stake_pool.header.vault),
        AccessError::StakePoolVaultMismatch,
    )?;

    if bond.total_amount_sold <= bond.total_unlocked_amount {
        msg!("All tokens have been unlocked");
        return Err(ProgramError::InvalidArgument);
    }

    if current_time < bond.unlock_start_date {
        msg!("The bond tokens have not started unlocking yet");
        return Err(ProgramError::InvalidArgument);
    }

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

    let delta = current_time
        .checked_sub(bond.last_unlock_time)
        .ok_or(AccessError::Overflow)?;

    if delta < bond.unlock_period {
        msg!("Need to wait the end of the current unlock period before unlocking the bond");
        return Err(ProgramError::InvalidArgument);
    }

    if bond.last_claimed_offset < central_state.get_current_offset()? {
        return Err(AccessError::UnclaimedRewards.into());
    }

    let missed_periods = delta
        .checked_div(bond.unlock_period)
        .ok_or(AccessError::Overflow)?;

    let unlock_amount = bond.calc_unlock_amount(missed_periods as u64)?;

    // Update the stake pool
    stake_pool.header.withdraw(unlock_amount)?;

    let signer_seeds: &[&[u8]] = &[
        StakePoolHeader::SEED,
        &stake_pool.header.owner.clone(),
        &[stake_pool.header.nonce],
    ];

    drop(stake_pool);

    // Transfer tokens
    let transfer_ix = spl_token::instruction::transfer(
        &spl_token::ID,
        accounts.pool_vault.key,
        accounts.access_token_destination.key,
        accounts.stake_pool.key,
        &[],
        unlock_amount,
    )?;

    invoke_signed(
        &transfer_ix,
        &[
            accounts.spl_token_program.clone(),
            accounts.pool_vault.clone(),
            accounts.access_token_destination.clone(),
            accounts.stake_pool.clone(),
        ],
        &[signer_seeds],
    )?;

    // Update bond state
    // bond.last_unlock_time += missed_periods * bond.unlock_period;
    bond.last_unlock_time = missed_periods
        .checked_mul(bond.unlock_period)
        .ok_or(AccessError::Overflow)?
        .checked_add(bond.last_unlock_time)
        .ok_or(AccessError::Overflow)?;

    // bond.total_unlocked_amount += unlock_amount;
    bond.total_unlocked_amount = bond
        .total_unlocked_amount
        .checked_add(unlock_amount)
        .ok_or(AccessError::Overflow)?;

    // bond.total_staked -= unlock_amount;
    bond.total_staked = bond
        .total_staked
        .checked_sub(unlock_amount)
        .ok_or(AccessError::Overflow)?;

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

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

    Ok(())
}