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
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> {
pub authority: Signer<'info>,
#[account(mut)]
pub receiver: AccountInfo<'info>,
#[account(mut)]
pub margin_account: AccountLoader<'info, MarginAccount>,
pub position_token_mint: Account<'info, Mint>,
#[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(())
}