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
use anchor_lang::prelude::*;
use anchor_spl::token::{self, Token, TokenAccount, Transfer};
use crate::{events, ErrorCode, MarginAccount, SignerSeeds};
#[derive(Accounts)]
pub struct TransferDeposit<'info> {
pub owner: Signer<'info>,
#[account(mut, has_one = owner)]
pub margin_account: AccountLoader<'info, MarginAccount>,
pub source_owner: Signer<'info>,
#[account(mut)]
pub source: Account<'info, TokenAccount>,
#[account(mut)]
pub destination: Account<'info, TokenAccount>,
pub token_program: Program<'info, Token>,
}
pub fn transfer_deposit_handler(ctx: Context<TransferDeposit>, amount: u64) -> Result<()> {
let mut margin_account = ctx.accounts.margin_account.load_mut()?;
let source_owner = &ctx.accounts.source_owner;
let position = match margin_account.get_position(&ctx.accounts.source.mint) {
None => return err!(ErrorCode::PositionNotRegistered),
Some(pos) => pos,
};
let position = if position.address == ctx.accounts.source.key() {
let seeds = margin_account.signer_seeds_owned();
drop(margin_account);
token::transfer(
CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info(),
Transfer {
from: ctx.accounts.source.to_account_info(),
to: ctx.accounts.destination.to_account_info(),
authority: ctx.accounts.margin_account.to_account_info(),
},
&[&seeds.signer_seeds()],
),
amount,
)?;
let source = &mut ctx.accounts.source;
let mut margin_account = ctx.accounts.margin_account.load_mut()?;
source.reload()?;
margin_account.set_position_balance(&source.mint, &source.key(), source.amount)?
} else {
token::transfer(
CpiContext::new(
ctx.accounts.token_program.to_account_info(),
Transfer {
from: ctx.accounts.source.to_account_info(),
to: ctx.accounts.destination.to_account_info(),
authority: source_owner.to_account_info(),
},
),
amount,
)?;
let destination = &mut ctx.accounts.destination;
destination.reload()?;
margin_account.set_position_balance(
&destination.mint,
&destination.key(),
destination.amount,
)?
};
emit!(events::PositionBalanceUpdated { position });
Ok(())
}