spl-single-pool 6.0.0

Solana Program Library Single-Validator Stake Pool
Documentation
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
#![allow(clippy::arithmetic_side_effects)]

mod helpers;

use {
    helpers::*,
    solana_clock::Clock,
    solana_program_test::*,
    solana_signer::Signer,
    solana_stake_interface::{
        instruction as stake_instruction, stake_history::StakeHistory, state::StakeStateV2,
    },
    solana_transaction::Transaction,
    spl_single_pool::{error::SinglePoolError, id, instruction},
    test_case::test_matrix,
};

#[test_matrix(
    [StakeProgramVersion::Stable, StakeProgramVersion::Beta, StakeProgramVersion::Edge],
    [false, true],
    [false, true]
)]
#[tokio::test]
async fn reactivate_success(
    stake_version: StakeProgramVersion,
    reactivate_pool: bool,
    fund_onramp: bool,
) {
    let Some(program_test) = program_test(stake_version) else {
        return;
    };
    let mut context = program_test.start_with_context().await;

    let accounts = SinglePoolAccounts::default();
    accounts
        .initialize_for_deposit(&mut context, TEST_STAKE_AMOUNT, Some(TEST_STAKE_AMOUNT))
        .await;

    let transaction = Transaction::new_signed_with_payer(
        &[stake_instruction::deactivate_stake(
            &accounts.bob_stake.pubkey(),
            &accounts.bob.pubkey(),
        )],
        Some(&context.payer.pubkey()),
        &[&context.payer, &accounts.bob],
        context.last_blockhash,
    );

    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();

    advance_epoch(&mut context).await;

    if reactivate_pool {
        // deactivate the pool stake account
        force_deactivate_stake_account(&mut context, &accounts.stake_account).await;

        // active deposit into deactivated pool fails
        let instructions = instruction::deposit(
            &id(),
            &accounts.pool,
            &accounts.alice_stake.pubkey(),
            &accounts.alice_token,
            &accounts.alice.pubkey(),
            &accounts.alice.pubkey(),
        );
        let transaction = Transaction::new_signed_with_payer(
            &instructions,
            Some(&context.payer.pubkey()),
            &[&context.payer, &accounts.alice],
            context.last_blockhash,
        );

        let e = context
            .banks_client
            .process_transaction(transaction)
            .await
            .unwrap_err();
        check_error(e, SinglePoolError::ReplenishRequired);

        // inactive deposit into deactivated pool fails
        let instructions = instruction::deposit(
            &id(),
            &accounts.pool,
            &accounts.bob_stake.pubkey(),
            &accounts.bob_token,
            &accounts.bob.pubkey(),
            &accounts.bob.pubkey(),
        );
        let transaction = Transaction::new_signed_with_payer(
            &instructions,
            Some(&context.payer.pubkey()),
            &[&context.payer, &accounts.bob],
            context.last_blockhash,
        );

        let e = context
            .banks_client
            .process_transaction(transaction)
            .await
            .unwrap_err();
        check_error(e, SinglePoolError::ReplenishRequired);
    }

    // onramp is already inactive but it doesnt have lamports for delegation
    if fund_onramp {
        let minimum_delegation = get_minimum_delegation(
            &mut context.banks_client,
            &context.payer,
            &context.last_blockhash,
        )
        .await;

        transfer(
            &mut context.banks_client,
            &context.payer,
            &context.last_blockhash,
            &accounts.onramp_account,
            minimum_delegation,
        )
        .await;
    }

    // replenish and advance
    replenish(&mut context, &accounts.vote_account.pubkey()).await;
    advance_epoch(&mut context).await;

    // deposit works in all cases
    let instructions = instruction::deposit(
        &id(),
        &accounts.pool,
        &accounts.alice_stake.pubkey(),
        &accounts.alice_token,
        &accounts.alice.pubkey(),
        &accounts.alice.pubkey(),
    );
    let transaction = Transaction::new_signed_with_payer(
        &instructions,
        Some(&context.payer.pubkey()),
        &[&context.payer, &accounts.alice],
        context.last_blockhash,
    );

    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();

    assert!(context
        .banks_client
        .get_account(accounts.alice_stake.pubkey())
        .await
        .expect("get_account")
        .is_none());

    // onramp is active now if we transfered to it
    let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
    let (_, onramp_stake, _) =
        get_stake_account(&mut context.banks_client, &accounts.onramp_account).await;

    // we require a fully active pool for any onramp state change to reduce complexity
    // the pool for a healthy validator is never unstaked, and a fresh pool you can wait an epoch
    // NOTE we might relax this for DepositSol, in which case this test would change
    if fund_onramp && !reactivate_pool {
        let stake = onramp_stake.unwrap();
        assert_eq!(stake.delegation.activation_epoch, clock.epoch - 1);
        assert_eq!(stake.delegation.deactivation_epoch, u64::MAX);
    } else {
        assert_eq!(onramp_stake, None);
    }
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum OnRampState {
    Initialized,
    Activating,
    Active,
    Deactive,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum MoveLamportsCase {
    None,
    SubMinumumDelegation,
    MinimumDelegation,
}

// initialized/move: onramp is fresh from its last replenish, move lamports from pool, and delegate if minimum
// activating/no move: onramp has loose lamports, add them to its delegation unconditionally
// activating/move: pool has loose lamports, move and add them to onramp delegation unconditionally
// active/no move: move onramp stake to pool, onramp ends initialized with rent exemption only
// active/move: move onramp stake to pool, move lamports from pool, and delegate if minimum
// deactive/move: same as the initialized/move case, but if onramp was deactivated
// initialized/no move and deactive/no move: nothing happens. successfully!
// ALL variants return Ok(()). replenish is a "magic" instruction that only performs stake operations which should succeed
#[test_matrix(
    [StakeProgramVersion::Stable, StakeProgramVersion::Beta, StakeProgramVersion::Edge],
    [OnRampState::Initialized, OnRampState::Activating, OnRampState::Active, OnRampState::Deactive],
    [MoveLamportsCase::None, MoveLamportsCase::SubMinumumDelegation, MoveLamportsCase::MinimumDelegation]
)]
#[tokio::test]
async fn move_value_success(
    stake_version: StakeProgramVersion,
    onramp_state: OnRampState,
    move_lamports_case: MoveLamportsCase,
) {
    let Some(program_test) = program_test(stake_version) else {
        return;
    };
    let mut context = program_test.start_with_context().await;

    let rent = context.banks_client.get_rent().await.unwrap();
    let pool_rent = rent.minimum_balance(StakeStateV2::size_of());
    let onramp_rent = pool_rent;

    let accounts = SinglePoolAccounts::default();
    accounts
        .initialize_for_deposit(&mut context, TEST_STAKE_AMOUNT, None)
        .await;
    advance_epoch(&mut context).await;

    // active onramp can be as low as minimum_delegation
    let minimum_delegation = get_minimum_delegation(
        &mut context.banks_client,
        &context.payer,
        &context.last_blockhash,
    )
    .await;

    // if we dont move, we dont move; instruction succeeds
    // if we move less than minimum, we move and dont delegate; instruction succeeds
    // if we move the minimum, we move and delegate; instruction succeeds
    let move_lamports_to_onramp = match move_lamports_case {
        MoveLamportsCase::None => None,
        MoveLamportsCase::SubMinumumDelegation => Some(minimum_delegation - 1),
        MoveLamportsCase::MinimumDelegation => Some(minimum_delegation),
    };

    let minimum_pool_balance = get_minimum_pool_balance(
        &mut context.banks_client,
        &context.payer,
        &context.last_blockhash,
    )
    .await;

    // set up an activating onramp
    if onramp_state >= OnRampState::Activating {
        transfer(
            &mut context.banks_client,
            &context.payer,
            &context.last_blockhash,
            &accounts.onramp_account,
            minimum_delegation,
        )
        .await;

        replenish(&mut context, &accounts.vote_account.pubkey()).await;
    }

    // allow the delegation to activate
    if onramp_state >= OnRampState::Active {
        advance_epoch(&mut context).await;
    }

    // move it over; this case is inactive and behaves identical to Initialized
    if onramp_state == OnRampState::Deactive {
        replenish(&mut context, &accounts.vote_account.pubkey()).await;
    }

    // if we are testing the pool -> onramp leg, add lamports for it
    if let Some(move_lamports_amount) = move_lamports_to_onramp {
        transfer(
            &mut context.banks_client,
            &context.payer,
            &context.last_blockhash,
            &accounts.stake_account,
            move_lamports_amount,
        )
        .await;
    };

    // this one case is to test reupping an activating delegation in place
    let existing_onramp_lamports =
        if onramp_state == OnRampState::Activating && move_lamports_to_onramp.is_none() {
            // NOTE we want a unique value to be sure our test cases are right and this didnt come from pool.
            // we also prefer sub-minimal, so we know we can add sub-minimal lamports to an already sufficient activation.
            // however stake v4 minimum is 1. this comment can be removed when stake v5 is Stable,
            // and the value can be changed to simply `minimum_delegation - 2`
            let existing_onramp_lamports = if minimum_delegation == 1 {
                minimum_delegation + 2
            } else {
                minimum_delegation - 2
            };

            transfer(
                &mut context.banks_client,
                &context.payer,
                &context.last_blockhash,
                &accounts.onramp_account,
                existing_onramp_lamports,
            )
            .await;

            existing_onramp_lamports
        } else {
            0
        };

    // this is the replenish we test
    replenish(&mut context, &accounts.vote_account.pubkey()).await;

    let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
    let stake_history = context
        .banks_client
        .get_sysvar::<StakeHistory>()
        .await
        .unwrap();

    let (_, pool_stake, pool_lamports) =
        get_stake_account(&mut context.banks_client, &accounts.stake_account).await;
    let pool_status = pool_stake
        .unwrap()
        .delegation
        .stake_activating_and_deactivating(clock.epoch, &stake_history, Some(0));

    let (_, onramp_stake, onramp_lamports) =
        get_stake_account(&mut context.banks_client, &accounts.onramp_account).await;
    let onramp_status = onramp_stake
        .map(|stake| {
            stake
                .delegation
                .stake_activating_and_deactivating(clock.epoch, &stake_history, Some(0))
        })
        .unwrap_or_default();

    match (onramp_state, move_lamports_to_onramp) {
        // stake moved already before test or because of test, new lamports were added to onramp
        (OnRampState::Deactive, Some(move_lamports_amount))
        | (OnRampState::Active, Some(move_lamports_amount)) => {
            assert_eq!(
                pool_status.effective,
                minimum_pool_balance + minimum_delegation
            );
            assert_eq!(
                pool_lamports,
                minimum_pool_balance + minimum_delegation + pool_rent
            );

            assert_eq!(onramp_status.effective, 0);
            assert_eq!(
                onramp_status.activating,
                if move_lamports_amount >= minimum_delegation {
                    move_lamports_amount
                } else {
                    0
                }
            );
            assert_eq!(onramp_lamports, move_lamports_amount + onramp_rent);
        }
        // no stake moved, but lamports did
        (OnRampState::Initialized, Some(move_lamports_amount)) => {
            assert_eq!(pool_status.effective, minimum_pool_balance);
            assert_eq!(pool_lamports, minimum_pool_balance + pool_rent);

            assert_eq!(onramp_status.effective, 0);
            assert_eq!(
                onramp_status.activating,
                if move_lamports_amount >= minimum_delegation {
                    move_lamports_amount
                } else {
                    0
                }
            );
            assert_eq!(onramp_lamports, move_lamports_amount + onramp_rent);
        }
        // no excess lamports moved, just stake
        (OnRampState::Active, None) => {
            assert_eq!(
                pool_status.effective,
                minimum_pool_balance + minimum_delegation
            );
            assert_eq!(
                pool_lamports,
                minimum_pool_balance + minimum_delegation + pool_rent
            );

            assert_eq!(onramp_status.effective, 0);
            assert_eq!(onramp_status.activating, 0);
            assert_eq!(onramp_lamports, onramp_rent);
        }
        // topped up an existing activation by moving from pool
        (OnRampState::Activating, Some(move_lamports_amount)) => {
            assert_eq!(pool_status.effective, minimum_pool_balance);
            assert_eq!(pool_lamports, minimum_pool_balance + pool_rent);

            assert_eq!(onramp_status.effective, 0);
            assert_eq!(
                onramp_status.activating,
                move_lamports_amount + minimum_delegation
            );
            assert_eq!(
                onramp_lamports,
                move_lamports_amount + minimum_delegation + onramp_rent
            );
        }
        // topped up an existing activation with lamports already in onramp
        (OnRampState::Activating, None) => {
            assert!(existing_onramp_lamports > 0);

            assert_eq!(pool_status.effective, minimum_pool_balance);
            assert_eq!(pool_lamports, minimum_pool_balance + pool_rent);

            assert_eq!(onramp_status.effective, 0);
            assert_eq!(
                onramp_status.activating,
                existing_onramp_lamports + minimum_delegation
            );
            assert_eq!(
                onramp_lamports,
                existing_onramp_lamports + minimum_delegation + onramp_rent
            );
        }
        // nothing happened
        (OnRampState::Initialized, None) => {
            assert_eq!(pool_status.effective, minimum_pool_balance);
            assert_eq!(pool_lamports, minimum_pool_balance + pool_rent);

            assert_eq!(onramp_status.effective, 0);
            assert_eq!(onramp_status.activating, 0);
            assert_eq!(onramp_lamports, onramp_rent);
        }
        // still nothing happened but setting up a deactive onramp added stake to pool already
        (OnRampState::Deactive, None) => {
            assert_eq!(
                pool_status.effective,
                minimum_delegation + minimum_pool_balance
            );
            assert_eq!(
                pool_lamports,
                minimum_delegation + minimum_pool_balance + pool_rent
            );

            assert_eq!(onramp_status.effective, 0);
            assert_eq!(onramp_status.activating, 0);
            assert_eq!(onramp_lamports, onramp_rent);
        }
    }
}

#[test_matrix(
    [StakeProgramVersion::Stable, StakeProgramVersion::Beta, StakeProgramVersion::Edge]
)]
#[tokio::test]
async fn move_value_deactivating(stake_version: StakeProgramVersion) {
    let Some(program_test) = program_test(stake_version) else {
        return;
    };
    let mut context = program_test.start_with_context().await;

    let accounts = SinglePoolAccounts::default();
    accounts
        .initialize_for_deposit(&mut context, TEST_STAKE_AMOUNT, None)
        .await;
    advance_epoch(&mut context).await;

    let minimum_delegation = get_minimum_delegation(
        &mut context.banks_client,
        &context.payer,
        &context.last_blockhash,
    )
    .await;

    transfer(
        &mut context.banks_client,
        &context.payer,
        &context.last_blockhash,
        &accounts.onramp_account,
        minimum_delegation,
    )
    .await;

    // set up a real active onramp
    replenish(&mut context, &accounts.vote_account.pubkey()).await;
    advance_epoch(&mut context).await;

    // edit the account to be deactivating instead
    let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
    let mut onramp_account = get_account(&mut context.banks_client, &accounts.onramp_account).await;
    let mut onramp_data: StakeStateV2 = bincode::deserialize(&onramp_account.data).unwrap();

    match onramp_data {
        StakeStateV2::Stake(_, ref mut stake, _) => {
            stake.delegation.deactivation_epoch = clock.epoch
        }
        _ => unreachable!(),
    }

    onramp_account.data = bincode::serialize(&onramp_data).unwrap();
    context.set_account(&accounts.onramp_account, &onramp_account.into());

    // this replenish call reactivates it in the same epoch
    replenish(&mut context, &accounts.vote_account.pubkey()).await;

    let (_, Some(stake), _) =
        get_stake_account(&mut context.banks_client, &accounts.onramp_account).await
    else {
        unreachable!()
    };

    assert_eq!(stake.delegation.deactivation_epoch, u64::MAX);
}

#[test_matrix(
    [StakeProgramVersion::Stable, StakeProgramVersion::Beta, StakeProgramVersion::Edge],
    [false, true]
)]
#[tokio::test]
async fn fail_onramp_doesnt_exist(stake_version: StakeProgramVersion, activate: bool) {
    let Some(program_test) = program_test(stake_version) else {
        return;
    };
    let mut context = program_test.start_with_context().await;

    let accounts = SinglePoolAccounts::default();

    let slot = context.genesis_config().epoch_schedule.first_normal_slot + 1;
    context.warp_to_slot(slot).unwrap();

    create_vote(
        &mut context.banks_client,
        &context.payer,
        &context.last_blockhash,
        &accounts.validator,
        &accounts.voter.pubkey(),
        &accounts.withdrawer.pubkey(),
        &accounts.vote_account,
    )
    .await;

    let rent = context.banks_client.get_rent().await.unwrap();
    let minimum_pool_balance = get_minimum_pool_balance(
        &mut context.banks_client,
        &context.payer,
        &context.last_blockhash,
    )
    .await;

    let mut instructions = instruction::initialize(
        &id(),
        &accounts.vote_account.pubkey(),
        &context.payer.pubkey(),
        &rent,
        minimum_pool_balance,
    );

    // guard against instruction moving in the builder function
    assert_eq!(&instructions[5].data, &[6]);
    let onramp_instruction = instructions.remove(5);

    let transaction = Transaction::new_signed_with_payer(
        &instructions,
        Some(&context.payer.pubkey()),
        &[&context.payer],
        context.last_blockhash,
    );

    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();

    if activate {
        advance_epoch(&mut context).await;
    }

    // pool is now activating or active with no onramp account
    // replenish should fail because the onramp is required
    let replenish_instruction = instruction::replenish_pool(&id(), &accounts.vote_account.pubkey());
    let transaction = Transaction::new_signed_with_payer(
        core::slice::from_ref(&replenish_instruction),
        Some(&context.payer.pubkey()),
        &[&context.payer],
        context.last_blockhash,
    );

    let e = context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap_err();
    check_error(e, SinglePoolError::OnRampDoesntExist);

    // creating onramp lets replenish succeed in the same epoch
    let transaction = Transaction::new_signed_with_payer(
        &[onramp_instruction],
        Some(&context.payer.pubkey()),
        &[&context.payer],
        context.last_blockhash,
    );

    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();

    refresh_blockhash(&mut context).await;
    let transaction = Transaction::new_signed_with_payer(
        &[replenish_instruction],
        Some(&context.payer.pubkey()),
        &[&context.payer],
        context.last_blockhash,
    );

    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();
}