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
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// Copyright (C) 2022 JET PROTOCOL HOLDINGS, LLC.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use anchor_lang::prelude::*;
use anchor_spl::token::{self, CloseAccount, Mint, Token, TokenAccount};

use crate::{events, Approver, MarginAccount, SignerSeeds};

#[derive(Accounts)]
pub struct ClosePosition<'info> {
    /// The authority that can change the margin account
    pub authority: Signer<'info>,

    /// The receiver for the rent released
    /// CHECK:
    #[account(mut)]
    pub receiver: AccountInfo<'info>,

    /// The margin account with the position to close
    #[account(mut)]
    pub margin_account: AccountLoader<'info, MarginAccount>,

    /// The mint for the position token being deregistered
    pub position_token_mint: Account<'info, Mint>,

    /// The token account for the position being closed
    #[account(mut)]
    pub token_account: Account<'info, TokenAccount>,

    pub token_program: Program<'info, Token>,
}

impl<'info> ClosePosition<'info> {
    fn close_token_account_ctx(&self) -> CpiContext<'_, '_, '_, 'info, CloseAccount<'info>> {
        CpiContext::new(
            self.token_program.to_account_info(),
            CloseAccount {
                account: self.token_account.to_account_info(),
                authority: self.margin_account.to_account_info(),
                destination: self.receiver.to_account_info(),
            },
        )
    }
}

pub fn close_position_handler(ctx: Context<ClosePosition>) -> Result<()> {
    {
        let mut account = ctx.accounts.margin_account.load_mut()?;
        account.verify_authority(ctx.accounts.authority.key())?;

        account.unregister_position(
            &ctx.accounts.position_token_mint.key(),
            &ctx.accounts.token_account.key(),
            &[Approver::MarginAccountAuthority],
        )?;
    }

    if ctx.accounts.token_account.owner == ctx.accounts.margin_account.key() {
        let account = ctx.accounts.margin_account.load()?;
        token::close_account(
            ctx.accounts
                .close_token_account_ctx()
                .with_signer(&[&account.signer_seeds()]),
        )?;
    }

    emit!(events::PositionClosed {
        margin_account: ctx.accounts.margin_account.key(),
        authority: ctx.accounts.authority.key(),
        token: ctx.accounts.position_token_mint.key(),
    });

    Ok(())
}