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
//! Unlock bond v2
use crate::{
    state::{Tag},
    utils::{check_account_key, check_account_owner, check_signer},
};
use bonfida_utils::{BorshSize, InstructionsAccount};
use borsh::{BorshDeserialize, BorshSerialize};

use solana_program::program::invoke_signed;
use solana_program::program_pack::Pack;
use solana_program::sysvar::Sysvar;
use solana_program::{
    account_info::{next_account_info, AccountInfo},
    clock::Clock,
    entrypoint::ProgramResult,
    msg,
    program_error::ProgramError,
    pubkey::Pubkey,
};
use spl_token::instruction::transfer;
use spl_token::state::Account;

use crate::error::AccessError;
use crate::instruction::ProgramInstruction::UnlockBondV2;
use crate::state::{BondV2Account, StakePool, StakePoolHeader};
use crate::state:: CentralStateV2;

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

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

    /// The bond account
    #[cons(writable)]
    pub bond_v2_account: &'a T,

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

    /// The destination of the locked tokens
    #[cons(writable)]
    pub owner_token_account: &'a T,

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

    /// The pool vault
    #[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 {
            central_state: next_account_info(accounts_iter)?,
            bond_v2_account: next_account_info(accounts_iter)?,
            owner: next_account_info(accounts_iter)?,
            owner_token_account: next_account_info(accounts_iter)?,
            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.central_state,
            program_id,
            AccessError::WrongOwner,
        )?;
        check_account_owner(
            accounts.bond_v2_account,
            program_id,
            AccessError::WrongStakeAccountOwner,
        )?;
        check_account_owner(
            accounts.pool,
            program_id,
            AccessError::WrongStakePoolAccountOwner,
        )?;
        check_account_owner(
            accounts.owner_token_account,
            &spl_token::ID,
            AccessError::WrongTokenAccountOwner,
        )?;
        check_account_owner(
            accounts.pool_vault,
            &spl_token::ID,
            AccessError::WrongTokenAccountOwner,
        )?;

        // Check signer
        check_signer(accounts.owner, AccessError::BondSellerMustSign)?;

        Ok(accounts)
    }
}

pub fn process_unlock_bond_v2(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    _params: Params,
) -> ProgramResult {
    let accounts = Accounts::parse(accounts, program_id)?;

    let mut stake_pool = StakePool::get_checked(accounts.pool, vec![Tag::StakePool])?;
    let mut bond_v2_account = BondV2Account::from_account_info(accounts.bond_v2_account)?;
    let mut central_state = CentralStateV2::from_account_info(accounts.central_state)?;
    central_state.assert_instruction_allowed(&UnlockBondV2)?;

    let destination_token_acc = Account::unpack(&accounts.owner_token_account.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());
    }
    if &destination_token_acc.owner != accounts.owner.key {
        return Err(AccessError::WrongTokenAccountOwner.into());
    }

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

    if bond_v2_account.last_claimed_offset < stake_pool.header.current_day_idx as u64 {
        return Err(AccessError::UnclaimedRewards.into());
    }

    check_account_key(
        accounts.owner,
        &bond_v2_account.owner,
        AccessError::StakeAccountOwnerMismatch,
    )?;
    check_account_key(
        accounts.pool,
        &bond_v2_account.pool,
        AccessError::StakePoolMismatch,
    )?;
    check_account_key(
        accounts.pool_vault,
        &Pubkey::new(&stake_pool.header.vault),
        AccessError::StakePoolVaultMismatch,
    )?;

    if stake_pool.header.minimum_stake_amount < bond_v2_account.pool_minimum_at_creation {
        bond_v2_account.pool_minimum_at_creation = stake_pool.header.minimum_stake_amount
    }

    // Check if the bond can be unlocked
    if bond_v2_account.unlock_timestamp.is_none() {
        msg!("Cannot unlock a Forever bond");
        return Err(ProgramError::InvalidArgument);
    }
    let current_time = Clock::get()?.unix_timestamp;
    if current_time < bond_v2_account.unlock_timestamp.unwrap() {
        msg!("The bond tokens have not started unlocking yet");
        return Err(ProgramError::InvalidArgument);
    }

    let amount = bond_v2_account.amount;
    msg!("Unlocking {} tokens", amount);
    if amount == 0 {
        msg!("All tokens have been unlocked");
        return Err(ProgramError::InvalidArgument);
    }

    // Update bond v2 account
    bond_v2_account.withdraw(amount)?;
    stake_pool.header.withdraw(amount)?;

    // Transfer tokens
    let signer_seeds: &[&[u8]] = &[
        StakePoolHeader::SEED,
        &stake_pool.header.owner.clone(),
        &[stake_pool.header.nonce],
    ];
    let transfer_instruction = transfer(
        &spl_token::ID,
        accounts.pool_vault.key,
        accounts.owner_token_account.key,
        accounts.pool.key,
        &[],
        amount,
    )?;

    drop(stake_pool);

    invoke_signed(
        &transfer_instruction,
        &[
            accounts.spl_token_program.clone(),
            accounts.pool_vault.clone(),
            accounts.owner_token_account.clone(),
            accounts.pool.clone(),
        ],
        &[signer_seeds],
    )?;

    // Save states
    bond_v2_account.save(&mut accounts.bond_v2_account.data.borrow_mut())?;

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

    Ok(())
}