use crate::errors::AntegenFiberError;
use crate::state::*;
use anchor_lang::prelude::*;
use super::close::sweep_fiber_lamports;
use super::create::{write_legacy, write_versioned};
#[derive(Accounts)]
pub struct Swap<'info> {
#[account(mut)]
pub thread: Signer<'info>,
#[account(mut)]
pub target: UncheckedAccount<'info>,
#[account(mut)]
pub source: UncheckedAccount<'info>,
}
pub fn swap(ctx: Context<Swap>) -> Result<()> {
let thread_key = ctx.accounts.thread.key();
let target_info = ctx.accounts.target.to_account_info();
let source_info = ctx.accounts.source.to_account_info();
let source_read = {
let data = source_info.try_borrow_data()?;
Fiber::try_deserialize(&mut &data[..])?
};
require!(
source_read.thread() == thread_key,
AntegenFiberError::InvalidFiberPDA
);
let target_read = {
let data = target_info.try_borrow_data()?;
Fiber::try_deserialize(&mut &data[..])?
};
require!(
target_read.thread() == thread_key,
AntegenFiberError::InvalidFiberPDA
);
let new_compiled = source_read.compiled_instruction().to_vec();
let new_priority_fee = source_read.priority_fee();
match target_read {
Fiber::Legacy(mut state) => {
state.compiled_instruction = new_compiled;
state.priority_fee = new_priority_fee;
state.last_executed = 0;
state.exec_count = 0;
write_legacy(&target_info, &state)?;
}
Fiber::V1(mut state) => {
state.version = CURRENT_FIBER_VERSION;
state.compiled_instruction = new_compiled;
state.priority_fee = new_priority_fee;
state.last_executed = 0;
state.exec_count = 0;
write_versioned(&target_info, &state)?;
}
}
sweep_fiber_lamports(&source_info, &ctx.accounts.thread.to_account_info())?;
Ok(())
}