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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! A native [SOL] multisig on-chain program.
//!
//! [sol]: https://solana.com/

use std::collections::{HashMap, HashSet};
use std::ops::DerefMut;

use anchor_lang::prelude::*;
use anchor_lang::solana_program::program::{invoke, invoke_signed};
use anchor_lang::solana_program::system_instruction;

#[cfg(not(feature = "localnet"))]
declare_id!("Ecycmji8eeggXrA3rD2cdEHpHDnP4btvVfcyTBS9cG9t");
#[cfg(feature = "localnet")]
declare_id!("AeAQKcvUbG6LmunEAiL2Vim5dN2uL5TNwJfgsGdyroQ3");

/// A multisig program specific error code.
#[error_code]
pub enum Error {
    /// Multisig [`State`] queue is empty.
    #[msg("Multisig account is empty. Please create transactions")]
    AccountEmpty,

    /// Multisig [`State`] queue is full.
    #[msg("Multisig transaction queue is full. Please approve those.")]
    AccountFull,

    /// Multisig [`State`] account is locked.
    #[msg("Multisig account is locked. Please approve the transactions")]
    AccountLocked,

    /// Missing transfer recipient AccountInfo.
    #[msg("Missing transfer recipient AccountInfo")]
    MissingRecipientAccountInfo,

    /// Multisig `Fund` account is not writable.
    #[msg("Fund account is not writable")]
    FundAccountNotWritable,

    /// Multisig `Fund` account data is not empty")]
    #[msg("Fund account data is not empty")]
    FundAccountIsNotEmpty,

    /// Invalid Multisig `Fund` PDA.
    #[msg("Invalid fund account")]
    InvalidFundAddress,

    /// Invalid Multisig `Fund` account bump.
    #[msg("Invalid fund bump seed")]
    InvalidFundBumpSeed,

    /// No signers.
    #[msg("No signers provided")]
    NoSigners,

    /// Too many signers provided.
    #[msg("Too many signers provided")]
    TooManySigners,

    /// The threshold, e.g. `m`, is too high.
    #[msg("Threshold too high")]
    ThresholdTooHigh,

    /// Invalid signer given.
    #[msg("Invalid signer")]
    InvalidSigner,

    /// Not enough `Fund` balance.
    #[msg("There is not enough fund balance")]
    NotEnoughFundBalance,
}

/// A multisig [`State`] PDA account data.
#[account]
#[derive(Debug)]
pub struct State {
    /// A threshold.
    pub m: u8,

    /// An array of signers Pubkey.
    pub signers: Vec<Pubkey>,

    /// A current signed state.
    pub signed: Vec<bool>,

    /// A fund PDA account, holding the native SOL.
    pub fund: Pubkey,

    /// A balance of the fund in lamports.
    pub balance: u64,

    /// A limit of the pending transactions.
    pub q: u8,

    /// An array of the pending transactions.
    pub queue: Vec<Pubkey>,
}

impl State {
    /// A minimum signers.
    const MIN_SIGNERS: u8 = 1;

    /// A maximum signers.
    const MAX_SIGNERS: u8 = u8::MAX;

    /// A maximum transaction queue.
    const MIN_QUEUE: u8 = 1;

    /// A maximum transaction queue.
    const MAX_QUEUE: u8 = u8::MAX;

    fn space(signers: &[Pubkey], q: u8) -> usize {
        let n = Self::valid_n(signers.len() as u8) as usize;
        let q = Self::valid_q(q) as usize;
        8 + 1 + 4 + 32 * n + 4 + n + 32 + 8 + 1 + 4 + 32 * q
    }

    /// Returns the valid n, number of signers.
    fn valid_n(n: u8) -> u8 {
        n.clamp(Self::MIN_SIGNERS, Self::MAX_SIGNERS)
    }

    /// Returns the valid q, queue length.
    fn valid_q(q: u8) -> u8 {
        q.clamp(Self::MIN_QUEUE, Self::MAX_QUEUE)
    }

    /// Checks if the transfer queue is empty.
    fn is_queue_empty(&self) -> bool {
        self.queue.is_empty()
    }

    /// Check if the multisig queue is full.
    fn is_queue_full(&self) -> bool {
        self.queue.len() == self.q as usize
    }

    /// Checks if the account had been locked.
    ///
    /// The multisig account is locked once it's signed
    /// by anyone.  It will be unlocked once the current
    /// pending transactions were completed.
    fn is_locked(&self) -> bool {
        self.signed.iter().any(|signed| *signed)
    }

    /// Validates the multisig queue.
    #[allow(clippy::result_large_err)]
    fn validate_queue(&self) -> Result<()> {
        require!(!self.is_queue_full(), Error::AccountFull);
        Ok(())
    }

    /// Validates the multisig fund account.
    #[allow(clippy::result_large_err)]
    fn validate_fund<'info>(
        state: &Account<'info, Self>,
        fund: &UncheckedAccount<'info>,
        bump: u8,
    ) -> Result<()> {
        if !fund.is_writable {
            Err(Error::FundAccountNotWritable)?;
        }
        if !fund.data_is_empty() {
            Err(Error::FundAccountIsNotEmpty)?;
        }
        let state_key = state.key();
        let seed = [b"fund", state_key.as_ref(), &[bump]];
        let pda = match Pubkey::create_program_address(&seed, &id()) {
            Err(_e) => Err(Error::InvalidFundBumpSeed)?,
            Ok(pda) => pda,
        };
        require_keys_eq!(pda, fund.key(), Error::InvalidFundAddress);

        Ok(())
    }

    /// Creates a fund account.
    #[allow(clippy::result_large_err)]
    fn create_fund_account<'info>(
        state: &Account<'info, Self>,
        fund: &UncheckedAccount<'info>,
        funder: &Signer<'info>,
        bump: u8,
    ) -> Result<()> {
        let lamports = Rent::get()?.minimum_balance(0);
        let ix = system_instruction::create_account(&funder.key(), &fund.key(), lamports, 0, &id());
        let state_key = state.key();
        let accounts = [funder.to_account_info(), fund.to_account_info()];
        let seed = [b"fund", state_key.as_ref(), &[bump]];

        // CPI.
        invoke_signed(&ix, &accounts, &[&seed])?;

        Ok(())
    }

    /// Withdraw fund.
    #[allow(clippy::result_large_err)]
    fn transfer_fund(
        _state: &Account<'_, Self>,
        from: &AccountInfo<'_>,
        to: &AccountInfo<'_>,
        lamports: u64,
        _bump: u8,
    ) -> Result<()> {
        // The following code hit the runtime error, [`InstructionError::ExternalLamportSpend`].
        // Instead, we'll transfer the lamports natively,
        // as suggested by the [Solana cookbook].
        //
        // [`InstructionError::ExternalLamportSpend`]: https://docs.rs/solana-program/latest/solana_program/instruction/enum.InstructionError.html#variant.ExternalAccountLamportSpend
        // [solana cookbook]: https://solanacookbook.com/references/programs.html#how-to-transfer-sol-in-a-program

        /*
        let ix = system_instruction::transfer(from.key, &to.key, lamports);
        let accounts = [from, to];
        let state_key = state.key();
        let seed = [b"fund", state_key.as_ref(), &[bump]];
        invoke_signed(
            &ix,
            &accounts,
            &[&seed],
        )?;
        */
        **from.try_borrow_mut_lamports()? -= lamports;
        **to.try_borrow_mut_lamports()? += lamports;

        Ok(())
    }
}

/// A multisig [`Transfer`] account data.
#[account]
#[derive(Debug)]
pub struct Transfer {
    /// An creator of the transfer, one of the multisig
    /// signers.
    pub creator: Pubkey,

    /// A recipient of the transfer.
    pub recipient: Pubkey,

    /// A lamports to transfer.
    pub lamports: u64,
}

impl Transfer {
    const SPACE: usize = 8 + 32 + 32 + 8;
}

/// Accounts for the [`multisig_lite::create`] instruction handler.
#[derive(Accounts)]
#[instruction(m: u8, signers: Vec<Pubkey>, q: u8, state_bump: u8, fund_bump: u8)]
pub struct Create<'info> {
    /// A funder of the multisig account.
    #[account(mut)]
    pub funder: Signer<'info>,

    /// A multisig state PDA account.
    #[account(
        init,
        payer = funder,
        space = State::space(&signers, q),
        seeds = [b"state", funder.key.as_ref()],
        bump,
    )]
    pub state: Account<'info, State>,

    /// A multisig fund account.
    ///
    /// CHECK: Checked by the [`multisig_lite::create`] instruction handler.
    #[account(mut, seeds = [b"fund", state.key().as_ref()], bump = fund_bump)]
    pub fund: UncheckedAccount<'info>,

    /// The system program to create a multisig PDA accounts.
    pub system_program: Program<'info, System>,
}

/// Accounts for the [`multisig_lite::fund`] instruction handler.
#[derive(Accounts)]
#[instruction(lamports: u64, state_bump: u8, fund_bump: u8)]
pub struct Fund<'info> {
    /// A funder of the account.
    ///
    /// The funding is only allowed by the multisig account creator.
    #[account(mut)]
    pub funder: Signer<'info>,

    /// A multisig state PDA account.
    #[account(mut, seeds = [b"state", funder.key.as_ref()], bump = state_bump)]
    pub state: Box<Account<'info, State>>,

    /// A multisig fund account.
    ///
    /// CHECK: Checked by the [`multisig_lite::fund`] instruction handler.
    #[account(mut, seeds = [b"fund", state.key().as_ref()], bump = fund_bump)]
    pub fund: UncheckedAccount<'info>,

    /// The system program to make the transfer of the fund.
    pub system_program: Program<'info, System>,
}

/// Accounts for the [`multisig_lite::create_transfer`] instruction handler.
#[derive(Accounts)]
#[instruction(recipient: Pubkey, lamports: u64, fund_bump: u8)]
pub struct CreateTransfer<'info> {
    /// An initiator of the fund transfer.
    ///
    /// It should be one of the signers of the multisig account.
    #[account(mut)]
    pub creator: Signer<'info>,

    /// A multisig state PDA account.
    #[account(mut)]
    pub state: Box<Account<'info, State>>,

    /// A multisig fund PDA account.
    ///
    /// CHECK: Checked by the [`multisig_lite::create_transfer`] instruction handler.
    #[account(mut, seeds = [b"fund", state.key().as_ref()], bump = fund_bump)]
    pub fund: UncheckedAccount<'info>,

    /// A transfer account to keep the queued transfer info.
    #[account(init, payer = creator, space = Transfer::SPACE)]
    pub transfer: Box<Account<'info, Transfer>>,

    /// The system program to create a transfer account.
    pub system_program: Program<'info, System>,
}

/// Accounts for the [`multisig_lite::approve`] instruction handler.
///
/// Once one of the signer approves, the account is locked
/// for the new transfer unless:
///
/// 1) Meets the m number of signers approval.
/// 2) Closes the account.
///
/// In case of the 1 above, the account will be unlocked
/// and starts to take a new transfer again.
#[derive(Accounts)]
#[instruction(fund_bump: u8)]
pub struct Approve<'info> {
    /// An approver of the current state of the multisg account.
    #[account(mut)]
    pub signer: Signer<'info>,

    /// A multisig state PDA account.
    #[account(mut)]
    pub state: Box<Account<'info, State>>,

    /// A multisig fund account.
    ///
    /// CHECK: Checked by the [`multisig_lite::approve`] instruction handler.
    #[account(mut, seeds = [b"fund", state.key().as_ref()], bump = fund_bump)]
    pub fund: UncheckedAccount<'info>,
}

/// Accounts for the [`multisig_lite::close`] instruction handler.
#[derive(Accounts)]
#[instruction(state_bump: u8, fund_bump: u8)]
pub struct Close<'info> {
    /// An original funder of the multisig account.
    #[account(mut)]
    pub funder: Signer<'info>,

    /// A multisig state PDA account.
    #[account(mut, close = funder, seeds = [b"state", funder.key.as_ref()], bump = state_bump)]
    pub state: Box<Account<'info, State>>,

    /// A multisig fund PDA account.
    ///
    /// CHECK: Checked by the [`multisig_lite::close`] instruction handler.
    #[account(mut, seeds = [b"fund", state.key().as_ref()], bump = fund_bump)]
    pub fund: UncheckedAccount<'info>,
}

/// Module representing the program instruction handlers.
#[program]
pub mod multisig_lite {
    use super::*;

    /// Creates the multisig account.
    ///
    /// It's restricted one multisig account to each funder Pubkey,
    /// as it's used for the multisig PDA address generation.
    #[allow(clippy::result_large_err)]
    pub fn create(
        ctx: Context<Create>,
        m: u8,
        signers: Vec<Pubkey>,
        q: u8,
        _state_bump: u8,
        fund_bump: u8,
    ) -> Result<()> {
        let funder = &mut ctx.accounts.funder;
        let state = &mut ctx.accounts.state;
        let fund = &mut ctx.accounts.fund;

        // At least one signer is required.
        require_gte!(m, State::MIN_SIGNERS, Error::NoSigners);

        // Validate the multisig fund account.
        State::validate_fund(state, fund, fund_bump)?;

        // Checks the uniqueness of signer's address.
        let signers: HashSet<_> = signers.into_iter().collect();
        require_gte!(signers.len(), State::MIN_SIGNERS as usize, Error::NoSigners);
        require_gte!(
            State::MAX_SIGNERS as usize,
            signers.len(),
            Error::TooManySigners
        );

        let threshold = m as usize;
        require_gte!(signers.len(), threshold, Error::ThresholdTooHigh);

        // Creates a fund account.
        State::create_fund_account(state, fund, funder, fund_bump)?;

        // Initializes the multisig state account.
        state.m = m;
        state.signers = signers.into_iter().collect();
        state.signed = vec![false; state.signers.len()];
        state.fund = fund.key();
        state.balance = 0;
        state.q = State::valid_q(q);

        Ok(())
    }

    /// Funds lamports to the multisig account.
    ///
    /// The funding is only allowed by the multisig account funder.
    #[allow(clippy::result_large_err)]
    pub fn fund(ctx: Context<Fund>, lamports: u64, _state_bump: u8, fund_bump: u8) -> Result<()> {
        let funder = &ctx.accounts.funder;
        let state = &mut ctx.accounts.state;
        let fund = &mut ctx.accounts.fund;

        // Validate the multisig fund account.
        State::validate_fund(state, fund, fund_bump)?;

        // CPI to transfer fund to the multisig fund account.
        let ix = system_instruction::transfer(&funder.key(), &fund.key(), lamports);
        let accounts = [funder.to_account_info(), fund.to_account_info()];
        invoke(&ix, &accounts)?;

        // Update the balance.
        state.balance += lamports;

        Ok(())
    }

    /// Creates a queued transfer lamports to the recipient.
    ///
    /// Transfer account creation fee will be given back to the
    /// creator of the transfer from the multisig fund.
    #[allow(clippy::result_large_err)]
    pub fn create_transfer(
        ctx: Context<CreateTransfer>,
        recipient: Pubkey,
        lamports: u64,
        fund_bump: u8,
    ) -> Result<()> {
        let creator = &ctx.accounts.creator;
        let state = &mut ctx.accounts.state;
        let fund = &mut ctx.accounts.fund;
        let transfer = &mut ctx.accounts.transfer;

        // Checks if the account is locked.
        require!(!state.is_locked(), Error::AccountLocked);

        // Validate the multisig fund account.
        State::validate_fund(state, fund, fund_bump)?;

        // Checks the creator.
        let creator_key = creator.key();
        let signers = &state.signers;
        require!(signers.contains(&creator_key), Error::InvalidSigner);

        // Check the current transfer queue.
        state.validate_queue()?;

        // Checks the multisig fund balance.
        require_gte!(state.balance, lamports, Error::NotEnoughFundBalance);

        // Giving back the rent fee to the creator.
        let from = fund.to_account_info();
        let to = creator.to_account_info();
        let rent = transfer.to_account_info().lamports();
        State::transfer_fund(state, &from, &to, rent, fund_bump)?;

        // Initializes the transfer account, and
        // queue it under multisig account for the
        // future transfer execution.
        transfer.creator = creator_key;
        transfer.recipient = recipient;
        transfer.lamports = lamports;
        state.balance -= lamports;
        state.queue.push(transfer.key());

        Ok(())
    }

    /// Approves the transactions and executes the transfer
    /// in case m approvals are met.
    #[allow(clippy::result_large_err)]
    pub fn approve(ctx: Context<Approve>, fund_bump: u8) -> Result<()> {
        let signer = &ctx.accounts.signer;
        let state = &mut ctx.accounts.state;
        let fund = &mut ctx.accounts.fund;
        let remaining_accounts: HashMap<_, _> = ctx
            .remaining_accounts
            .iter()
            .map(|account| (account.key, account))
            .collect();

        // Validate the multisig fund account.
        State::validate_fund(state, fund, fund_bump)?;

        // Nothing to approve.
        require!(!state.is_queue_empty(), Error::AccountEmpty);

        // Checks the signer.
        let signer_key = signer.key();
        let signers = &state.signers;
        let signer_index = match signers.iter().position(|pubkey| *pubkey == signer_key) {
            None => return Err(Error::InvalidSigner.into()),
            Some(signer_index) => signer_index,
        };

        // Due to the single transaction limitation, we allow the multiple approval
        // so that we take care of the transfer in batch.
        if !state.signed[signer_index] {
            state.signed[signer_index] = true;
        }

        // Checks the threshold.
        let signed = state.signed.iter().filter(|&signed| *signed).count() as u8;
        if signed < state.m {
            return Ok(());
        }

        // Finds out the executable transactions.
        let mut executable = Vec::new();
        let mut remaining = Vec::new();
        for transfer_addr in &state.queue {
            let transfer_info = match remaining_accounts.get(transfer_addr) {
                Some(transfer) => transfer,
                None => {
                    remaining.push(*transfer_addr);
                    continue;
                }
            };
            let mut ref_data = transfer_info.try_borrow_mut_data()?;
            let mut transfer_data: &[u8] = ref_data.deref_mut();
            let tx = Transfer::try_deserialize(&mut transfer_data)?;
            let to = match remaining_accounts.get(&tx.recipient) {
                None => return Err(Error::MissingRecipientAccountInfo.into()),
                Some(recipient) => recipient,
            };
            executable.push((transfer_info, to, tx.lamports));
        }

        // There is no executable account info.  Just returns the success.
        //
        // This is a case that the approver approved the multisig but didn't
        // provide the account info.
        if executable.is_empty() {
            return Ok(());
        }

        // Executes the queued transfers.
        let fund = fund.to_account_info();
        for (transfer, to, lamports) in executable {
            // Fund to the recipient and closes the transfer account.
            State::transfer_fund(state, &fund, to, lamports, fund_bump)?;
            let lamports = transfer.lamports();
            State::transfer_fund(state, transfer, &fund, lamports, fund_bump)?;
        }

        // Update the queue.
        state.queue = remaining;

        // Reset the signed status once the queue is empty.
        if state.is_queue_empty() {
            state.signed.iter_mut().for_each(|signed| *signed = false);
        }

        Ok(())
    }

    /// Closes a multisig account.
    ///
    /// It cleans up all the remaining accounts and return back to the
    /// funder.
    #[allow(clippy::result_large_err)]
    pub fn close(ctx: Context<Close>, _state_bump: u8, fund_bump: u8) -> Result<()> {
        let funder = &mut ctx.accounts.funder;
        let state = &mut ctx.accounts.state;
        let fund = &mut ctx.accounts.fund;
        let remaining_accounts: HashMap<_, _> = ctx
            .remaining_accounts
            .iter()
            .map(|account| (account.key, account))
            .collect();

        // Validate the multisig fund account.
        State::validate_fund(state, fund, fund_bump)?;

        // Closes the transfer accounts by transfering the
        // rent fee back to the fund account.
        let to = fund.to_account_info();
        for transfer_addr in &state.queue {
            let from = match remaining_accounts.get(transfer_addr) {
                Some(transfer) => transfer,
                None => continue,
            };
            let lamports = from.lamports();
            State::transfer_fund(state, from, &to, lamports, fund_bump)?;
        }

        // Closes the multisig fund account by transfering all the lamports
        // back to the funder.
        let from = fund.to_account_info();
        let to = funder.to_account_info();
        let lamports = fund.lamports();
        State::transfer_fund(state, &from, &to, lamports, fund_bump)?;

        Ok(())
    }
}