clockwork_network/instructions/
node_update.rs

1use {
2    crate::state::*,
3    anchor_lang::{
4        prelude::*,
5        solana_program::system_program,
6        system_program::{transfer, Transfer},
7    },
8};
9
10#[derive(Accounts)]
11#[instruction(settings: NodeSettings)]
12pub struct NodeUpdate<'info> {
13    #[account(mut)]
14    pub authority: Signer<'info>,
15
16    #[account(
17        mut,
18        seeds = [
19            SEED_NODE,
20            node.id.to_be_bytes().as_ref()
21        ],
22        bump,
23        has_one = authority,
24    )]
25    pub node: Account<'info, Node>,
26
27    #[account(address = system_program::ID)]
28    pub system_program: Program<'info, System>,
29}
30
31pub fn handler(ctx: Context<NodeUpdate>, settings: NodeSettings) -> Result<()> {
32    // Get accounts
33    let authority = &ctx.accounts.authority;
34    let node = &mut ctx.accounts.node;
35    let system_program = &ctx.accounts.system_program;
36
37    // Update the node
38    node.update(settings)?;
39
40    // Realloc memory for the node account
41    let data_len = 8 + node.try_to_vec()?.len();
42    node.to_account_info().realloc(data_len, false)?;
43
44    // If lamports are required to maintain rent-exemption, pay them
45    let minimum_rent = Rent::get().unwrap().minimum_balance(data_len);
46    if minimum_rent > node.to_account_info().lamports() {
47        transfer(
48            CpiContext::new(
49                system_program.to_account_info(),
50                Transfer {
51                    from: authority.to_account_info(),
52                    to: node.to_account_info(),
53                },
54            ),
55            minimum_rent
56                .checked_sub(node.to_account_info().lamports())
57                .unwrap(),
58        )?;
59    }
60
61    Ok(())
62}