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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
//! Create a Bond V2
use bonfida_utils::{BorshSize, InstructionsAccount};
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::program_pack::Pack;
use solana_program::{
    account_info::{next_account_info, AccountInfo},
    entrypoint::ProgramResult,
    program::invoke,
    program_error::ProgramError,
    pubkey::Pubkey,
    system_program,
    sysvar::Sysvar,
    clock::Clock,
    msg,
};
use spl_token::instruction::transfer;
use spl_token::state::Account;
use crate::state:: CentralStateV2;

use crate::error::AccessError;
use crate::state::{BondV2Account, StakePool};
use crate::utils::{
    assert_uninitialized, assert_valid_fee, check_account_key, check_account_owner, check_signer,
};
use crate::{cpi::Cpi, state::Tag};
use crate::instruction::ProgramInstruction::CreateBondV2;

#[derive(BorshDeserialize, BorshSerialize, BorshSize)]
/// The required parameters for the `create_bond_v2` instruction
pub struct Params {
    /// Total amount of ACCESS tokens being sold
    pub amount: u64,
    /// The timestamp of the unlock, if any
    pub unlock_timestamp: Option<i64>,
}

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

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

    /// From ATA
    #[cons(writable)]
    pub from_ata: &'a T,

    /// The bond recipient wallet
    pub to: &'a T,

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

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

    /// The vault of the central state
    #[cons(writable)]
    pub central_state_vault: &'a T,

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

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

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

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

    /// The system program account
    pub system_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 {
            fee_payer: next_account_info(accounts_iter)?,
            from: next_account_info(accounts_iter)?,
            from_ata: next_account_info(accounts_iter)?,
            to: next_account_info(accounts_iter)?,
            bond_v2_account: next_account_info(accounts_iter)?,
            central_state: next_account_info(accounts_iter)?,
            central_state_vault: next_account_info(accounts_iter)?,
            pool: next_account_info(accounts_iter)?,
            pool_vault: next_account_info(accounts_iter)?,
            mint: next_account_info(accounts_iter)?,
            spl_token_program: next_account_info(accounts_iter)?,
            system_program: next_account_info(accounts_iter)?,
        };

        // Check keys
        check_account_key(
            accounts.system_program,
            &system_program::ID,
            AccessError::WrongSystemProgram,
        )?;
        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.central_state_vault, &spl_token::ID, AccessError::WrongOwner)?;
        check_account_owner(
            accounts.pool,
            program_id,
            AccessError::WrongStakePoolAccountOwner,
        )?;
        check_account_owner(
            accounts.from_ata,
            &spl_token::ID,
            AccessError::WrongTokenAccountOwner,
        )?;
        check_account_owner(
            accounts.pool_vault,
            &spl_token::ID,
            AccessError::WrongTokenAccountOwner,
        )?;

        // Check signers
        check_signer(accounts.from, AccessError::BondSellerMustSign)?;

        Ok(accounts)
    }
}

pub fn process_create_bond_v2(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    params: Params,
) -> ProgramResult {
    let Params {
        amount,
        unlock_timestamp,
    } = params;
    let accounts = Accounts::parse(accounts, program_id)?;

    let mut pool = StakePool::get_checked(accounts.pool, vec![Tag::StakePool])?;
    let mut central_state = CentralStateV2::from_account_info(accounts.central_state)?;
    central_state.assert_instruction_allowed(&CreateBondV2)?;
    assert_valid_fee(accounts.central_state_vault, accounts.central_state.key)?;

    check_account_key(
        accounts.pool_vault,
        &Pubkey::new(&pool.header.vault),
        AccessError::StakePoolVaultMismatch,
    )?;

    if (pool.header.current_day_idx as u64) < central_state.get_current_offset()? {
        msg!(
            "Pool must be cranked before adding to a bond, {}, {}",
            pool.header.current_day_idx,
            central_state.get_current_offset()?
        );
        return Err(AccessError::PoolMustBeCranked.into());
    }

    // We want to limit the bond amount by the pool minumum even in the case when the user has other subscriptions
    if pool.header.minimum_stake_amount > amount {
        return Err(AccessError::InvalidAmount.into());
    }

    let (derived_key, bump_seed) =
        BondV2Account::create_key(accounts.to.key, accounts.pool.key, unlock_timestamp, program_id);

    check_account_key(
        accounts.bond_v2_account,
        &derived_key,
        AccessError::AccountNotDeterministic,
    )?;
    check_account_key(
        accounts.mint,
        &central_state.token_mint,
        AccessError::WrongMint,
    )?;
    assert_uninitialized(accounts.bond_v2_account)?;

    let current_time = Clock::get()?.unix_timestamp;
    if unlock_timestamp.is_some() && current_time > unlock_timestamp.unwrap() {
        msg!("Cannot create a bond with an unlock timestamp in the past");
        return Err(ProgramError::InvalidArgument);
    }

    let from_ata = Account::unpack(&accounts.from_ata.data.borrow())?;
    if from_ata.mint != central_state.token_mint {
        return Err(AccessError::WrongMint.into());
    }
    if &from_ata.owner != accounts.from.key {
        return Err(AccessError::WrongOwner.into());
    }

    let bond = BondV2Account::new(
        *accounts.to.key,
        *accounts.pool.key,
        pool.header.minimum_stake_amount,
        amount,
        unlock_timestamp,
        central_state.last_snapshot_offset,
    );

    // Create bond account
    let seeds: &[&[u8]] = &[
        BondV2Account::SEED,
        &accounts.to.key.to_bytes(),
        &accounts.pool.key.to_bytes(),
        &unlock_timestamp.unwrap_or(0).to_le_bytes(),
        &[bump_seed],
    ];

    Cpi::create_account(
        program_id,
        accounts.system_program,
        accounts.fee_payer,
        accounts.bond_v2_account,
        seeds,
        bond.borsh_len(),
    )?;

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

    // Transfer the tokens to pool vault (or burn for forever bonds)
    if unlock_timestamp.is_some() {
        let transfer_instruction = transfer(
            &spl_token::ID,
            accounts.from_ata.key,
            accounts.pool_vault.key,
            accounts.from.key,
            &[],
            amount,
        )?;
        invoke(
            &transfer_instruction,
            &[
                accounts.spl_token_program.clone(),
                accounts.from_ata.clone(),
                accounts.pool_vault.clone(),
                accounts.from.clone(),
            ],
        )?;
    } else {
        let burn_instruction = spl_token::instruction::burn(
            &spl_token::ID,
            accounts.from_ata.key,
            accounts.mint.key,
            accounts.from.key,
            &[accounts.from.key],
            amount,
        )?;
        invoke(
            &burn_instruction,
            &[
                accounts.from_ata.clone(),
                accounts.mint.clone(),
                accounts.from.clone(),
                accounts.from.clone(),
            ],
        )?;
    }

    // Transfer fees
    let fee_amount = central_state.calculate_fee(amount)?;
    msg!("Transfer fees: {}", fee_amount);
    let transfer_fees = transfer(
        &spl_token::ID,
        accounts.from_ata.key,
        accounts.central_state_vault.key,
        accounts.from.key,
        &[],
        fee_amount,
    )?;
    invoke(
        &transfer_fees,
        &[
            accounts.spl_token_program.clone(),
            accounts.from_ata.clone(),
            accounts.central_state_vault.clone(),
            accounts.from.clone(),
        ],
    )?;

    // Update all the appropriate states
    pool.header.deposit(amount)?;
    central_state.total_staked = central_state
        .total_staked
        .checked_add(amount)
        .ok_or(AccessError::Overflow)?;
    central_state.save(&mut accounts.central_state.data.borrow_mut())?;

    Ok(())
}